Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 523170de

History | View | Annotate | Download (64.4 kB)

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

24 a8083063 Iustin Pop
This module provides small, mostly data-only objects which are safe to
25 a8083063 Iustin Pop
pass to and from external parties.
26 a8083063 Iustin Pop

27 a8083063 Iustin Pop
"""
28 a8083063 Iustin Pop
29 0007f3ab Andrea Spadaccini
# pylint: disable=E0203,W0201,R0902
30 6c881c52 Iustin Pop
31 6c881c52 Iustin Pop
# E0203: Access to member %r before its definition, since we use
32 2ed0e208 Iustin Pop
# objects.py which doesn't explicitly initialise its members
33 6c881c52 Iustin Pop
34 7260cfbe Iustin Pop
# W0201: Attribute '%s' defined outside __init__
35 a8083063 Iustin Pop
36 0007f3ab Andrea Spadaccini
# R0902: Allow instances of these objects to have more than 20 attributes
37 0007f3ab Andrea Spadaccini
38 a8083063 Iustin Pop
import ConfigParser
39 5c947f38 Iustin Pop
import re
40 5bf7b5cf Iustin Pop
import copy
41 250a9404 Bernardo Dal Seno
import logging
42 e11a1b77 Adeodato Simo
import time
43 d5835922 Michael Hanselmann
from cStringIO import StringIO
44 a8083063 Iustin Pop
45 a8083063 Iustin Pop
from ganeti import errors
46 5c947f38 Iustin Pop
from ganeti import constants
47 0007f3ab Andrea Spadaccini
from ganeti import netutils
48 473d87a3 Iustin Pop
from ganeti import outils
49 32017174 Agata Murawska
from ganeti import utils
50 a8083063 Iustin Pop
51 f4c9af7a Guido Trotter
from socket import AF_INET
52 f4c9af7a Guido Trotter
53 a8083063 Iustin Pop
54 a8083063 Iustin Pop
__all__ = ["ConfigObject", "ConfigData", "NIC", "Disk", "Instance",
55 eaa4c57c Dimitris Aragiorgis
           "OS", "Node", "NodeGroup", "Cluster", "FillDict", "Network"]
56 a8083063 Iustin Pop
57 d693c864 Iustin Pop
_TIMESTAMPS = ["ctime", "mtime"]
58 e1dcc53a Iustin Pop
_UUID = ["uuid"]
59 96acbc09 Michael Hanselmann
60 8d8d650c Michael Hanselmann
61 e11ddf13 Iustin Pop
def FillDict(defaults_dict, custom_dict, skip_keys=None):
62 29921401 Iustin Pop
  """Basic function to apply settings on top a default dict.
63 abe609b2 Guido Trotter

64 29921401 Iustin Pop
  @type defaults_dict: dict
65 29921401 Iustin Pop
  @param defaults_dict: dictionary holding the default values
66 29921401 Iustin Pop
  @type custom_dict: dict
67 29921401 Iustin Pop
  @param custom_dict: dictionary holding customized value
68 7736a5f2 Iustin Pop
  @type skip_keys: list
69 7736a5f2 Iustin Pop
  @param skip_keys: which keys not to fill
70 29921401 Iustin Pop
  @rtype: dict
71 29921401 Iustin Pop
  @return: dict with the 'full' values
72 abe609b2 Guido Trotter

73 29921401 Iustin Pop
  """
74 29921401 Iustin Pop
  ret_dict = copy.deepcopy(defaults_dict)
75 29921401 Iustin Pop
  ret_dict.update(custom_dict)
76 e11ddf13 Iustin Pop
  if skip_keys:
77 e11ddf13 Iustin Pop
    for k in skip_keys:
78 e11ddf13 Iustin Pop
      try:
79 e11ddf13 Iustin Pop
        del ret_dict[k]
80 e11ddf13 Iustin Pop
      except KeyError:
81 e11ddf13 Iustin Pop
        pass
82 29921401 Iustin Pop
  return ret_dict
83 a8083063 Iustin Pop
84 6e34b628 Guido Trotter
85 da5f09ef Bernardo Dal Seno
def FillIPolicy(default_ipolicy, custom_ipolicy):
86 2cc673a3 Iustin Pop
  """Fills an instance policy with defaults.
87 918eb80b Agata Murawska

88 918eb80b Agata Murawska
  """
89 2cc673a3 Iustin Pop
  assert frozenset(default_ipolicy.keys()) == constants.IPOLICY_ALL_KEYS
90 0f511c8a Bernardo Dal Seno
  ret_dict = copy.deepcopy(custom_ipolicy)
91 0f511c8a Bernardo Dal Seno
  for key in default_ipolicy:
92 0f511c8a Bernardo Dal Seno
    if key not in ret_dict:
93 0f511c8a Bernardo Dal Seno
      ret_dict[key] = copy.deepcopy(default_ipolicy[key])
94 0f511c8a Bernardo Dal Seno
    elif key == constants.ISPECS_STD:
95 0f511c8a Bernardo Dal Seno
      ret_dict[key] = FillDict(default_ipolicy[key], ret_dict[key])
96 918eb80b Agata Murawska
  return ret_dict
97 918eb80b Agata Murawska
98 918eb80b Agata Murawska
99 57987785 René Nussbaumer
def FillDiskParams(default_dparams, custom_dparams, skip_keys=None):
100 57987785 René Nussbaumer
  """Fills the disk parameter defaults.
101 57987785 René Nussbaumer

102 af9fb4cc René Nussbaumer
  @see: L{FillDict} for parameters and return value
103 57987785 René Nussbaumer

104 57987785 René Nussbaumer
  """
105 57987785 René Nussbaumer
  assert frozenset(default_dparams.keys()) == constants.DISK_TEMPLATES
106 57987785 René Nussbaumer
107 57987785 René Nussbaumer
  return dict((dt, FillDict(default_dparams[dt], custom_dparams.get(dt, {}),
108 57987785 René Nussbaumer
                             skip_keys=skip_keys))
109 57987785 René Nussbaumer
              for dt in constants.DISK_TEMPLATES)
110 57987785 René Nussbaumer
111 57987785 René Nussbaumer
112 6e34b628 Guido Trotter
def UpgradeGroupedParams(target, defaults):
113 6e34b628 Guido Trotter
  """Update all groups for the target parameter.
114 6e34b628 Guido Trotter

115 6e34b628 Guido Trotter
  @type target: dict of dicts
116 6e34b628 Guido Trotter
  @param target: {group: {parameter: value}}
117 6e34b628 Guido Trotter
  @type defaults: dict
118 6e34b628 Guido Trotter
  @param defaults: default parameter values
119 6e34b628 Guido Trotter

120 6e34b628 Guido Trotter
  """
121 6e34b628 Guido Trotter
  if target is None:
122 6e34b628 Guido Trotter
    target = {constants.PP_DEFAULT: defaults}
123 6e34b628 Guido Trotter
  else:
124 6e34b628 Guido Trotter
    for group in target:
125 6e34b628 Guido Trotter
      target[group] = FillDict(defaults, target[group])
126 6e34b628 Guido Trotter
  return target
127 6e34b628 Guido Trotter
128 6e34b628 Guido Trotter
129 8c72ab2b Guido Trotter
def UpgradeBeParams(target):
130 8c72ab2b Guido Trotter
  """Update the be parameters dict to the new format.
131 8c72ab2b Guido Trotter

132 8c72ab2b Guido Trotter
  @type target: dict
133 8c72ab2b Guido Trotter
  @param target: "be" parameters dict
134 8c72ab2b Guido Trotter

135 8c72ab2b Guido Trotter
  """
136 8c72ab2b Guido Trotter
  if constants.BE_MEMORY in target:
137 8c72ab2b Guido Trotter
    memory = target[constants.BE_MEMORY]
138 8c72ab2b Guido Trotter
    target[constants.BE_MAXMEM] = memory
139 8c72ab2b Guido Trotter
    target[constants.BE_MINMEM] = memory
140 b2e233a5 Guido Trotter
    del target[constants.BE_MEMORY]
141 8c72ab2b Guido Trotter
142 8c72ab2b Guido Trotter
143 bc5d0215 Andrea Spadaccini
def UpgradeDiskParams(diskparams):
144 bc5d0215 Andrea Spadaccini
  """Upgrade the disk parameters.
145 bc5d0215 Andrea Spadaccini

146 bc5d0215 Andrea Spadaccini
  @type diskparams: dict
147 bc5d0215 Andrea Spadaccini
  @param diskparams: disk parameters to upgrade
148 bc5d0215 Andrea Spadaccini
  @rtype: dict
149 765ada2b Iustin Pop
  @return: the upgraded disk parameters dict
150 bc5d0215 Andrea Spadaccini

151 bc5d0215 Andrea Spadaccini
  """
152 99ccf8b9 René Nussbaumer
  if not diskparams:
153 99ccf8b9 René Nussbaumer
    result = {}
154 bc5d0215 Andrea Spadaccini
  else:
155 57987785 René Nussbaumer
    result = FillDiskParams(constants.DISK_DT_DEFAULTS, diskparams)
156 bc5d0215 Andrea Spadaccini
157 bc5d0215 Andrea Spadaccini
  return result
158 bc5d0215 Andrea Spadaccini
159 bc5d0215 Andrea Spadaccini
160 2a27dac3 Iustin Pop
def UpgradeNDParams(ndparams):
161 2a27dac3 Iustin Pop
  """Upgrade ndparams structure.
162 2a27dac3 Iustin Pop

163 2a27dac3 Iustin Pop
  @type ndparams: dict
164 2a27dac3 Iustin Pop
  @param ndparams: disk parameters to upgrade
165 2a27dac3 Iustin Pop
  @rtype: dict
166 2a27dac3 Iustin Pop
  @return: the upgraded node parameters dict
167 2a27dac3 Iustin Pop

168 2a27dac3 Iustin Pop
  """
169 2a27dac3 Iustin Pop
  if ndparams is None:
170 2a27dac3 Iustin Pop
    ndparams = {}
171 2a27dac3 Iustin Pop
172 1df4d430 Iustin Pop
  if (constants.ND_OOB_PROGRAM in ndparams and
173 1df4d430 Iustin Pop
      ndparams[constants.ND_OOB_PROGRAM] is None):
174 1df4d430 Iustin Pop
    # will be reset by the line below
175 1df4d430 Iustin Pop
    del ndparams[constants.ND_OOB_PROGRAM]
176 2a27dac3 Iustin Pop
  return FillDict(constants.NDC_DEFAULTS, ndparams)
177 2a27dac3 Iustin Pop
178 2a27dac3 Iustin Pop
179 918eb80b Agata Murawska
def MakeEmptyIPolicy():
180 918eb80b Agata Murawska
  """Create empty IPolicy dictionary.
181 918eb80b Agata Murawska

182 918eb80b Agata Murawska
  """
183 0f511c8a Bernardo Dal Seno
  return {}
184 918eb80b Agata Murawska
185 918eb80b Agata Murawska
186 473d87a3 Iustin Pop
class ConfigObject(outils.ValidatedSlots):
187 a8083063 Iustin Pop
  """A generic config object.
188 a8083063 Iustin Pop

189 a8083063 Iustin Pop
  It has the following properties:
190 a8083063 Iustin Pop

191 a8083063 Iustin Pop
    - provides somewhat safe recursive unpickling and pickling for its classes
192 a8083063 Iustin Pop
    - unset attributes which are defined in slots are always returned
193 a8083063 Iustin Pop
      as None instead of raising an error
194 a8083063 Iustin Pop

195 a8083063 Iustin Pop
  Classes derived from this must always declare __slots__ (we use many
196 55224070 Guido Trotter
  config objects and the memory reduction is useful)
197 a8083063 Iustin Pop

198 a8083063 Iustin Pop
  """
199 a8083063 Iustin Pop
  __slots__ = []
200 a8083063 Iustin Pop
201 a8083063 Iustin Pop
  def __getattr__(self, name):
202 32683096 René Nussbaumer
    if name not in self.GetAllSlots():
203 3ecf6786 Iustin Pop
      raise AttributeError("Invalid object attribute %s.%s" %
204 3ecf6786 Iustin Pop
                           (type(self).__name__, name))
205 a8083063 Iustin Pop
    return None
206 a8083063 Iustin Pop
207 a8083063 Iustin Pop
  def __setstate__(self, state):
208 32683096 René Nussbaumer
    slots = self.GetAllSlots()
209 a8083063 Iustin Pop
    for name in state:
210 adf385c7 Iustin Pop
      if name in slots:
211 a8083063 Iustin Pop
        setattr(self, name, state[name])
212 a8083063 Iustin Pop
213 32683096 René Nussbaumer
  def Validate(self):
214 32683096 René Nussbaumer
    """Validates the slots.
215 adf385c7 Iustin Pop

216 adf385c7 Iustin Pop
    """
217 415feb2e René Nussbaumer
218 ff9c047c Iustin Pop
  def ToDict(self):
219 ff9c047c Iustin Pop
    """Convert to a dict holding only standard python types.
220 ff9c047c Iustin Pop

221 ff9c047c Iustin Pop
    The generic routine just dumps all of this object's attributes in
222 ff9c047c Iustin Pop
    a dict. It does not work if the class has children who are
223 ff9c047c Iustin Pop
    ConfigObjects themselves (e.g. the nics list in an Instance), in
224 ff9c047c Iustin Pop
    which case the object should subclass the function in order to
225 ff9c047c Iustin Pop
    make sure all objects returned are only standard python types.
226 ff9c047c Iustin Pop

227 ff9c047c Iustin Pop
    """
228 4c14965f Guido Trotter
    result = {}
229 32683096 René Nussbaumer
    for name in self.GetAllSlots():
230 4c14965f Guido Trotter
      value = getattr(self, name, None)
231 4c14965f Guido Trotter
      if value is not None:
232 4c14965f Guido Trotter
        result[name] = value
233 4c14965f Guido Trotter
    return result
234 4c14965f Guido Trotter
235 4c14965f Guido Trotter
  __getstate__ = ToDict
236 ff9c047c Iustin Pop
237 ff9c047c Iustin Pop
  @classmethod
238 ff9c047c Iustin Pop
  def FromDict(cls, val):
239 ff9c047c Iustin Pop
    """Create an object from a dictionary.
240 ff9c047c Iustin Pop

241 ff9c047c Iustin Pop
    This generic routine takes a dict, instantiates a new instance of
242 ff9c047c Iustin Pop
    the given class, and sets attributes based on the dict content.
243 ff9c047c Iustin Pop

244 ff9c047c Iustin Pop
    As for `ToDict`, this does not work if the class has children
245 ff9c047c Iustin Pop
    who are ConfigObjects themselves (e.g. the nics list in an
246 ff9c047c Iustin Pop
    Instance), in which case the object should subclass the function
247 ff9c047c Iustin Pop
    and alter the objects.
248 ff9c047c Iustin Pop

249 ff9c047c Iustin Pop
    """
250 ff9c047c Iustin Pop
    if not isinstance(val, dict):
251 ff9c047c Iustin Pop
      raise errors.ConfigurationError("Invalid object passed to FromDict:"
252 ff9c047c Iustin Pop
                                      " expected dict, got %s" % type(val))
253 319856a9 Michael Hanselmann
    val_str = dict([(str(k), v) for k, v in val.iteritems()])
254 b459a848 Andrea Spadaccini
    obj = cls(**val_str) # pylint: disable=W0142
255 ff9c047c Iustin Pop
    return obj
256 ff9c047c Iustin Pop
257 e8d563f3 Iustin Pop
  def Copy(self):
258 e8d563f3 Iustin Pop
    """Makes a deep copy of the current object and its children.
259 e8d563f3 Iustin Pop

260 e8d563f3 Iustin Pop
    """
261 e8d563f3 Iustin Pop
    dict_form = self.ToDict()
262 e8d563f3 Iustin Pop
    clone_obj = self.__class__.FromDict(dict_form)
263 e8d563f3 Iustin Pop
    return clone_obj
264 e8d563f3 Iustin Pop
265 ff9c047c Iustin Pop
  def __repr__(self):
266 ff9c047c Iustin Pop
    """Implement __repr__ for ConfigObjects."""
267 ff9c047c Iustin Pop
    return repr(self.ToDict())
268 ff9c047c Iustin Pop
269 560428be Guido Trotter
  def UpgradeConfig(self):
270 560428be Guido Trotter
    """Fill defaults for missing configuration values.
271 560428be Guido Trotter

272 90d726a8 Iustin Pop
    This method will be called at configuration load time, and its
273 90d726a8 Iustin Pop
    implementation will be object dependent.
274 560428be Guido Trotter

275 560428be Guido Trotter
    """
276 560428be Guido Trotter
    pass
277 560428be Guido Trotter
278 a8083063 Iustin Pop
279 ec29fe40 Iustin Pop
class TaggableObject(ConfigObject):
280 5c947f38 Iustin Pop
  """An generic class supporting tags.
281 5c947f38 Iustin Pop

282 5c947f38 Iustin Pop
  """
283 154b9580 Balazs Lecz
  __slots__ = ["tags"]
284 b5e5632e Iustin Pop
  VALID_TAG_RE = re.compile("^[\w.+*/:@-]+$")
285 2057f6c7 Iustin Pop
286 b5e5632e Iustin Pop
  @classmethod
287 b5e5632e Iustin Pop
  def ValidateTag(cls, tag):
288 5c947f38 Iustin Pop
    """Check if a tag is valid.
289 5c947f38 Iustin Pop

290 5c947f38 Iustin Pop
    If the tag is invalid, an errors.TagError will be raised. The
291 5c947f38 Iustin Pop
    function has no return value.
292 5c947f38 Iustin Pop

293 5c947f38 Iustin Pop
    """
294 5c947f38 Iustin Pop
    if not isinstance(tag, basestring):
295 3ecf6786 Iustin Pop
      raise errors.TagError("Invalid tag type (not a string)")
296 5c947f38 Iustin Pop
    if len(tag) > constants.MAX_TAG_LEN:
297 319856a9 Michael Hanselmann
      raise errors.TagError("Tag too long (>%d characters)" %
298 319856a9 Michael Hanselmann
                            constants.MAX_TAG_LEN)
299 5c947f38 Iustin Pop
    if not tag:
300 3ecf6786 Iustin Pop
      raise errors.TagError("Tags cannot be empty")
301 b5e5632e Iustin Pop
    if not cls.VALID_TAG_RE.match(tag):
302 3ecf6786 Iustin Pop
      raise errors.TagError("Tag contains invalid characters")
303 5c947f38 Iustin Pop
304 5c947f38 Iustin Pop
  def GetTags(self):
305 5c947f38 Iustin Pop
    """Return the tags list.
306 5c947f38 Iustin Pop

307 5c947f38 Iustin Pop
    """
308 5c947f38 Iustin Pop
    tags = getattr(self, "tags", None)
309 5c947f38 Iustin Pop
    if tags is None:
310 5c947f38 Iustin Pop
      tags = self.tags = set()
311 5c947f38 Iustin Pop
    return tags
312 5c947f38 Iustin Pop
313 5c947f38 Iustin Pop
  def AddTag(self, tag):
314 5c947f38 Iustin Pop
    """Add a new tag.
315 5c947f38 Iustin Pop

316 5c947f38 Iustin Pop
    """
317 5c947f38 Iustin Pop
    self.ValidateTag(tag)
318 5c947f38 Iustin Pop
    tags = self.GetTags()
319 5c947f38 Iustin Pop
    if len(tags) >= constants.MAX_TAGS_PER_OBJ:
320 3ecf6786 Iustin Pop
      raise errors.TagError("Too many tags")
321 5c947f38 Iustin Pop
    self.GetTags().add(tag)
322 5c947f38 Iustin Pop
323 5c947f38 Iustin Pop
  def RemoveTag(self, tag):
324 5c947f38 Iustin Pop
    """Remove a tag.
325 5c947f38 Iustin Pop

326 5c947f38 Iustin Pop
    """
327 5c947f38 Iustin Pop
    self.ValidateTag(tag)
328 5c947f38 Iustin Pop
    tags = self.GetTags()
329 5c947f38 Iustin Pop
    try:
330 5c947f38 Iustin Pop
      tags.remove(tag)
331 5c947f38 Iustin Pop
    except KeyError:
332 3ecf6786 Iustin Pop
      raise errors.TagError("Tag not found")
333 5c947f38 Iustin Pop
334 ff9c047c Iustin Pop
  def ToDict(self):
335 ff9c047c Iustin Pop
    """Taggable-object-specific conversion to standard python types.
336 ff9c047c Iustin Pop

337 ff9c047c Iustin Pop
    This replaces the tags set with a list.
338 ff9c047c Iustin Pop

339 ff9c047c Iustin Pop
    """
340 ff9c047c Iustin Pop
    bo = super(TaggableObject, self).ToDict()
341 ff9c047c Iustin Pop
342 ff9c047c Iustin Pop
    tags = bo.get("tags", None)
343 ff9c047c Iustin Pop
    if isinstance(tags, set):
344 ff9c047c Iustin Pop
      bo["tags"] = list(tags)
345 ff9c047c Iustin Pop
    return bo
346 ff9c047c Iustin Pop
347 ff9c047c Iustin Pop
  @classmethod
348 ff9c047c Iustin Pop
  def FromDict(cls, val):
349 ff9c047c Iustin Pop
    """Custom function for instances.
350 ff9c047c Iustin Pop

351 ff9c047c Iustin Pop
    """
352 ff9c047c Iustin Pop
    obj = super(TaggableObject, cls).FromDict(val)
353 ff9c047c Iustin Pop
    if hasattr(obj, "tags") and isinstance(obj.tags, list):
354 ff9c047c Iustin Pop
      obj.tags = set(obj.tags)
355 ff9c047c Iustin Pop
    return obj
356 ff9c047c Iustin Pop
357 5c947f38 Iustin Pop
358 061af273 Andrea Spadaccini
class MasterNetworkParameters(ConfigObject):
359 061af273 Andrea Spadaccini
  """Network configuration parameters for the master
360 061af273 Andrea Spadaccini

361 061af273 Andrea Spadaccini
  @ivar name: master name
362 061af273 Andrea Spadaccini
  @ivar ip: master IP
363 061af273 Andrea Spadaccini
  @ivar netmask: master netmask
364 061af273 Andrea Spadaccini
  @ivar netdev: master network device
365 061af273 Andrea Spadaccini
  @ivar ip_family: master IP family
366 061af273 Andrea Spadaccini

367 061af273 Andrea Spadaccini
  """
368 061af273 Andrea Spadaccini
  __slots__ = [
369 061af273 Andrea Spadaccini
    "name",
370 061af273 Andrea Spadaccini
    "ip",
371 061af273 Andrea Spadaccini
    "netmask",
372 061af273 Andrea Spadaccini
    "netdev",
373 3c286190 Dimitris Aragiorgis
    "ip_family",
374 061af273 Andrea Spadaccini
    ]
375 061af273 Andrea Spadaccini
376 061af273 Andrea Spadaccini
377 a8083063 Iustin Pop
class ConfigData(ConfigObject):
378 a8083063 Iustin Pop
  """Top-level config object."""
379 3df43542 Guido Trotter
  __slots__ = [
380 3df43542 Guido Trotter
    "version",
381 3df43542 Guido Trotter
    "cluster",
382 3df43542 Guido Trotter
    "nodes",
383 3df43542 Guido Trotter
    "nodegroups",
384 3df43542 Guido Trotter
    "instances",
385 eaa4c57c Dimitris Aragiorgis
    "networks",
386 3df43542 Guido Trotter
    "serial_no",
387 3df43542 Guido Trotter
    ] + _TIMESTAMPS
388 a8083063 Iustin Pop
389 ff9c047c Iustin Pop
  def ToDict(self):
390 ff9c047c Iustin Pop
    """Custom function for top-level config data.
391 ff9c047c Iustin Pop

392 ff9c047c Iustin Pop
    This just replaces the list of instances, nodes and the cluster
393 ff9c047c Iustin Pop
    with standard python types.
394 ff9c047c Iustin Pop

395 ff9c047c Iustin Pop
    """
396 ff9c047c Iustin Pop
    mydict = super(ConfigData, self).ToDict()
397 ff9c047c Iustin Pop
    mydict["cluster"] = mydict["cluster"].ToDict()
398 eaa4c57c Dimitris Aragiorgis
    for key in "nodes", "instances", "nodegroups", "networks":
399 fe502d25 Iustin Pop
      mydict[key] = outils.ContainerToDicts(mydict[key])
400 ff9c047c Iustin Pop
401 ff9c047c Iustin Pop
    return mydict
402 ff9c047c Iustin Pop
403 ff9c047c Iustin Pop
  @classmethod
404 ff9c047c Iustin Pop
  def FromDict(cls, val):
405 ff9c047c Iustin Pop
    """Custom function for top-level config data
406 ff9c047c Iustin Pop

407 ff9c047c Iustin Pop
    """
408 ff9c047c Iustin Pop
    obj = super(ConfigData, cls).FromDict(val)
409 ff9c047c Iustin Pop
    obj.cluster = Cluster.FromDict(obj.cluster)
410 fe502d25 Iustin Pop
    obj.nodes = outils.ContainerFromDicts(obj.nodes, dict, Node)
411 473ab806 Michael Hanselmann
    obj.instances = \
412 fe502d25 Iustin Pop
      outils.ContainerFromDicts(obj.instances, dict, Instance)
413 473ab806 Michael Hanselmann
    obj.nodegroups = \
414 fe502d25 Iustin Pop
      outils.ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
415 fe502d25 Iustin Pop
    obj.networks = outils.ContainerFromDicts(obj.networks, dict, Network)
416 ff9c047c Iustin Pop
    return obj
417 ff9c047c Iustin Pop
418 51cb1581 Luca Bigliardi
  def HasAnyDiskOfType(self, dev_type):
419 51cb1581 Luca Bigliardi
    """Check if in there is at disk of the given type in the configuration.
420 51cb1581 Luca Bigliardi

421 51cb1581 Luca Bigliardi
    @type dev_type: L{constants.LDS_BLOCK}
422 51cb1581 Luca Bigliardi
    @param dev_type: the type to look for
423 51cb1581 Luca Bigliardi
    @rtype: boolean
424 51cb1581 Luca Bigliardi
    @return: boolean indicating if a disk of the given type was found or not
425 51cb1581 Luca Bigliardi

426 51cb1581 Luca Bigliardi
    """
427 51cb1581 Luca Bigliardi
    for instance in self.instances.values():
428 51cb1581 Luca Bigliardi
      for disk in instance.disks:
429 51cb1581 Luca Bigliardi
        if disk.IsBasedOnDiskType(dev_type):
430 51cb1581 Luca Bigliardi
          return True
431 51cb1581 Luca Bigliardi
    return False
432 51cb1581 Luca Bigliardi
433 90d726a8 Iustin Pop
  def UpgradeConfig(self):
434 90d726a8 Iustin Pop
    """Fill defaults for missing configuration values.
435 90d726a8 Iustin Pop

436 90d726a8 Iustin Pop
    """
437 90d726a8 Iustin Pop
    self.cluster.UpgradeConfig()
438 90d726a8 Iustin Pop
    for node in self.nodes.values():
439 90d726a8 Iustin Pop
      node.UpgradeConfig()
440 90d726a8 Iustin Pop
    for instance in self.instances.values():
441 90d726a8 Iustin Pop
      instance.UpgradeConfig()
442 3df43542 Guido Trotter
    if self.nodegroups is None:
443 3df43542 Guido Trotter
      self.nodegroups = {}
444 3df43542 Guido Trotter
    for nodegroup in self.nodegroups.values():
445 3df43542 Guido Trotter
      nodegroup.UpgradeConfig()
446 ee2f0ed4 Luca Bigliardi
    if self.cluster.drbd_usermode_helper is None:
447 ee2f0ed4 Luca Bigliardi
      # To decide if we set an helper let's check if at least one instance has
448 ee2f0ed4 Luca Bigliardi
      # a DRBD disk. This does not cover all the possible scenarios but it
449 ee2f0ed4 Luca Bigliardi
      # gives a good approximation.
450 ee2f0ed4 Luca Bigliardi
      if self.HasAnyDiskOfType(constants.LD_DRBD8):
451 ee2f0ed4 Luca Bigliardi
        self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
452 eaa4c57c Dimitris Aragiorgis
    if self.networks is None:
453 eaa4c57c Dimitris Aragiorgis
      self.networks = {}
454 ee9516c8 Guido Trotter
    for network in self.networks.values():
455 ee9516c8 Guido Trotter
      network.UpgradeConfig()
456 1b02d7ef Helga Velroyen
    self._UpgradeEnabledDiskTemplates()
457 c66d8987 Helga Velroyen
458 1b02d7ef Helga Velroyen
  def _UpgradeEnabledDiskTemplates(self):
459 1b02d7ef Helga Velroyen
    """Upgrade the cluster's enabled disk templates by inspecting the currently
460 1b02d7ef Helga Velroyen
       enabled and/or used disk templates.
461 c66d8987 Helga Velroyen

462 c66d8987 Helga Velroyen
    """
463 1b02d7ef Helga Velroyen
    # enabled_disk_templates in the cluster config were introduced in 2.8.
464 1b02d7ef Helga Velroyen
    # Remove this code once upgrading from earlier versions is deprecated.
465 1b02d7ef Helga Velroyen
    if not self.cluster.enabled_disk_templates:
466 1b02d7ef Helga Velroyen
      template_set = \
467 1b02d7ef Helga Velroyen
        set([inst.disk_template for inst in self.instances.values()])
468 1b02d7ef Helga Velroyen
      # Add drbd and plain, if lvm is enabled (by specifying a volume group)
469 c66d8987 Helga Velroyen
      if self.cluster.volume_group_name:
470 1b02d7ef Helga Velroyen
        template_set.add(constants.DT_DRBD8)
471 1b02d7ef Helga Velroyen
        template_set.add(constants.DT_PLAIN)
472 c66d8987 Helga Velroyen
      # FIXME: Adapt this when dis/enabling at configure time is removed.
473 1b02d7ef Helga Velroyen
      # Enable 'file' and 'sharedfile', if they are enabled, even though they
474 1b02d7ef Helga Velroyen
      # might currently not be used.
475 c66d8987 Helga Velroyen
      if constants.ENABLE_FILE_STORAGE:
476 1b02d7ef Helga Velroyen
        template_set.add(constants.DT_FILE)
477 c66d8987 Helga Velroyen
      if constants.ENABLE_SHARED_FILE_STORAGE:
478 1b02d7ef Helga Velroyen
        template_set.add(constants.DT_SHARED_FILE)
479 1b02d7ef Helga Velroyen
      # Set enabled_disk_templates to the inferred disk templates. Order them
480 c66d8987 Helga Velroyen
      # according to a preference list that is based on Ganeti's history of
481 1b02d7ef Helga Velroyen
      # supported disk templates.
482 1b02d7ef Helga Velroyen
      self.cluster.enabled_disk_templates = []
483 1b02d7ef Helga Velroyen
      for preferred_template in constants.DISK_TEMPLATE_PREFERENCE:
484 1b02d7ef Helga Velroyen
        if preferred_template in template_set:
485 1b02d7ef Helga Velroyen
          self.cluster.enabled_disk_templates.append(preferred_template)
486 1b02d7ef Helga Velroyen
          template_set.remove(preferred_template)
487 1b02d7ef Helga Velroyen
      self.cluster.enabled_disk_templates.extend(list(template_set))
488 90d726a8 Iustin Pop
489 a8083063 Iustin Pop
490 a8083063 Iustin Pop
class NIC(ConfigObject):
491 a8083063 Iustin Pop
  """Config object representing a network card."""
492 238da95a Christos Stavrakakis
  __slots__ = ["name", "mac", "ip", "network", "nicparams", "netinfo"] + _UUID
493 a8083063 Iustin Pop
494 255e19d4 Guido Trotter
  @classmethod
495 255e19d4 Guido Trotter
  def CheckParameterSyntax(cls, nicparams):
496 255e19d4 Guido Trotter
    """Check the given parameters for validity.
497 255e19d4 Guido Trotter

498 255e19d4 Guido Trotter
    @type nicparams:  dict
499 255e19d4 Guido Trotter
    @param nicparams: dictionary with parameter names/value
500 255e19d4 Guido Trotter
    @raise errors.ConfigurationError: when a parameter is not valid
501 255e19d4 Guido Trotter

502 255e19d4 Guido Trotter
    """
503 53258324 Michael Hanselmann
    mode = nicparams[constants.NIC_MODE]
504 53258324 Michael Hanselmann
    if (mode not in constants.NIC_VALID_MODES and
505 53258324 Michael Hanselmann
        mode != constants.VALUE_AUTO):
506 53258324 Michael Hanselmann
      raise errors.ConfigurationError("Invalid NIC mode '%s'" % mode)
507 255e19d4 Guido Trotter
508 53258324 Michael Hanselmann
    if (mode == constants.NIC_MODE_BRIDGED and
509 255e19d4 Guido Trotter
        not nicparams[constants.NIC_LINK]):
510 53258324 Michael Hanselmann
      raise errors.ConfigurationError("Missing bridged NIC link")
511 255e19d4 Guido Trotter
512 a8083063 Iustin Pop
513 a8083063 Iustin Pop
class Disk(ConfigObject):
514 a8083063 Iustin Pop
  """Config object representing a block device."""
515 238da95a Christos Stavrakakis
  __slots__ = ["name", "dev_type", "logical_id", "physical_id",
516 238da95a Christos Stavrakakis
               "children", "iv_name", "size", "mode", "params"] + _UUID
517 a8083063 Iustin Pop
518 a8083063 Iustin Pop
  def CreateOnSecondary(self):
519 a8083063 Iustin Pop
    """Test if this device needs to be created on a secondary node."""
520 00fb8246 Michael Hanselmann
    return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
521 a8083063 Iustin Pop
522 a8083063 Iustin Pop
  def AssembleOnSecondary(self):
523 a8083063 Iustin Pop
    """Test if this device needs to be assembled on a secondary node."""
524 00fb8246 Michael Hanselmann
    return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
525 a8083063 Iustin Pop
526 a8083063 Iustin Pop
  def OpenOnSecondary(self):
527 a8083063 Iustin Pop
    """Test if this device needs to be opened on a secondary node."""
528 fe96220b Iustin Pop
    return self.dev_type in (constants.LD_LV,)
529 a8083063 Iustin Pop
530 222f2dd5 Iustin Pop
  def StaticDevPath(self):
531 222f2dd5 Iustin Pop
    """Return the device path if this device type has a static one.
532 222f2dd5 Iustin Pop

533 222f2dd5 Iustin Pop
    Some devices (LVM for example) live always at the same /dev/ path,
534 222f2dd5 Iustin Pop
    irrespective of their status. For such devices, we return this
535 222f2dd5 Iustin Pop
    path, for others we return None.
536 222f2dd5 Iustin Pop

537 e51db2a6 Iustin Pop
    @warning: The path returned is not a normalized pathname; callers
538 e51db2a6 Iustin Pop
        should check that it is a valid path.
539 e51db2a6 Iustin Pop

540 222f2dd5 Iustin Pop
    """
541 222f2dd5 Iustin Pop
    if self.dev_type == constants.LD_LV:
542 222f2dd5 Iustin Pop
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
543 b6135bbc Apollon Oikonomopoulos
    elif self.dev_type == constants.LD_BLOCKDEV:
544 b6135bbc Apollon Oikonomopoulos
      return self.logical_id[1]
545 7181fba0 Constantinos Venetsanopoulos
    elif self.dev_type == constants.LD_RBD:
546 7181fba0 Constantinos Venetsanopoulos
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
547 222f2dd5 Iustin Pop
    return None
548 222f2dd5 Iustin Pop
549 fc1dc9d7 Iustin Pop
  def ChildrenNeeded(self):
550 fc1dc9d7 Iustin Pop
    """Compute the needed number of children for activation.
551 fc1dc9d7 Iustin Pop

552 fc1dc9d7 Iustin Pop
    This method will return either -1 (all children) or a positive
553 fc1dc9d7 Iustin Pop
    number denoting the minimum number of children needed for
554 fc1dc9d7 Iustin Pop
    activation (only mirrored devices will usually return >=0).
555 fc1dc9d7 Iustin Pop

556 fc1dc9d7 Iustin Pop
    Currently, only DRBD8 supports diskless activation (therefore we
557 fc1dc9d7 Iustin Pop
    return 0), for all other we keep the previous semantics and return
558 fc1dc9d7 Iustin Pop
    -1.
559 fc1dc9d7 Iustin Pop

560 fc1dc9d7 Iustin Pop
    """
561 fc1dc9d7 Iustin Pop
    if self.dev_type == constants.LD_DRBD8:
562 fc1dc9d7 Iustin Pop
      return 0
563 fc1dc9d7 Iustin Pop
    return -1
564 fc1dc9d7 Iustin Pop
565 51cb1581 Luca Bigliardi
  def IsBasedOnDiskType(self, dev_type):
566 51cb1581 Luca Bigliardi
    """Check if the disk or its children are based on the given type.
567 51cb1581 Luca Bigliardi

568 51cb1581 Luca Bigliardi
    @type dev_type: L{constants.LDS_BLOCK}
569 51cb1581 Luca Bigliardi
    @param dev_type: the type to look for
570 51cb1581 Luca Bigliardi
    @rtype: boolean
571 51cb1581 Luca Bigliardi
    @return: boolean indicating if a device of the given type was found or not
572 51cb1581 Luca Bigliardi

573 51cb1581 Luca Bigliardi
    """
574 51cb1581 Luca Bigliardi
    if self.children:
575 51cb1581 Luca Bigliardi
      for child in self.children:
576 51cb1581 Luca Bigliardi
        if child.IsBasedOnDiskType(dev_type):
577 51cb1581 Luca Bigliardi
          return True
578 51cb1581 Luca Bigliardi
    return self.dev_type == dev_type
579 51cb1581 Luca Bigliardi
580 a8083063 Iustin Pop
  def GetNodes(self, node):
581 a8083063 Iustin Pop
    """This function returns the nodes this device lives on.
582 a8083063 Iustin Pop

583 a8083063 Iustin Pop
    Given the node on which the parent of the device lives on (or, in
584 a8083063 Iustin Pop
    case of a top-level device, the primary node of the devices'
585 a8083063 Iustin Pop
    instance), this function will return a list of nodes on which this
586 a8083063 Iustin Pop
    devices needs to (or can) be assembled.
587 a8083063 Iustin Pop

588 a8083063 Iustin Pop
    """
589 b6135bbc Apollon Oikonomopoulos
    if self.dev_type in [constants.LD_LV, constants.LD_FILE,
590 376631d1 Constantinos Venetsanopoulos
                         constants.LD_BLOCKDEV, constants.LD_RBD,
591 376631d1 Constantinos Venetsanopoulos
                         constants.LD_EXT]:
592 a8083063 Iustin Pop
      result = [node]
593 a1f445d3 Iustin Pop
    elif self.dev_type in constants.LDS_DRBD:
594 a8083063 Iustin Pop
      result = [self.logical_id[0], self.logical_id[1]]
595 a8083063 Iustin Pop
      if node not in result:
596 3ecf6786 Iustin Pop
        raise errors.ConfigurationError("DRBD device passed unknown node")
597 a8083063 Iustin Pop
    else:
598 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
599 a8083063 Iustin Pop
    return result
600 a8083063 Iustin Pop
601 a8083063 Iustin Pop
  def ComputeNodeTree(self, parent_node):
602 a8083063 Iustin Pop
    """Compute the node/disk tree for this disk and its children.
603 a8083063 Iustin Pop

604 a8083063 Iustin Pop
    This method, given the node on which the parent disk lives, will
605 a8083063 Iustin Pop
    return the list of all (node, disk) pairs which describe the disk
606 abdf0113 Iustin Pop
    tree in the most compact way. For example, a drbd/lvm stack
607 abdf0113 Iustin Pop
    will be returned as (primary_node, drbd) and (secondary_node, drbd)
608 abdf0113 Iustin Pop
    which represents all the top-level devices on the nodes.
609 a8083063 Iustin Pop

610 a8083063 Iustin Pop
    """
611 a8083063 Iustin Pop
    my_nodes = self.GetNodes(parent_node)
612 a8083063 Iustin Pop
    result = [(node, self) for node in my_nodes]
613 a8083063 Iustin Pop
    if not self.children:
614 a8083063 Iustin Pop
      # leaf device
615 a8083063 Iustin Pop
      return result
616 a8083063 Iustin Pop
    for node in my_nodes:
617 a8083063 Iustin Pop
      for child in self.children:
618 a8083063 Iustin Pop
        child_result = child.ComputeNodeTree(node)
619 a8083063 Iustin Pop
        if len(child_result) == 1:
620 a8083063 Iustin Pop
          # child (and all its descendants) is simple, doesn't split
621 a8083063 Iustin Pop
          # over multiple hosts, so we don't need to describe it, our
622 a8083063 Iustin Pop
          # own entry for this node describes it completely
623 a8083063 Iustin Pop
          continue
624 a8083063 Iustin Pop
        else:
625 a8083063 Iustin Pop
          # check if child nodes differ from my nodes; note that
626 a8083063 Iustin Pop
          # subdisk can differ from the child itself, and be instead
627 a8083063 Iustin Pop
          # one of its descendants
628 a8083063 Iustin Pop
          for subnode, subdisk in child_result:
629 a8083063 Iustin Pop
            if subnode not in my_nodes:
630 a8083063 Iustin Pop
              result.append((subnode, subdisk))
631 a8083063 Iustin Pop
            # otherwise child is under our own node, so we ignore this
632 a8083063 Iustin Pop
            # entry (but probably the other results in the list will
633 a8083063 Iustin Pop
            # be different)
634 a8083063 Iustin Pop
    return result
635 a8083063 Iustin Pop
636 6d33a6eb Iustin Pop
  def ComputeGrowth(self, amount):
637 6d33a6eb Iustin Pop
    """Compute the per-VG growth requirements.
638 6d33a6eb Iustin Pop

639 6d33a6eb Iustin Pop
    This only works for VG-based disks.
640 6d33a6eb Iustin Pop

641 6d33a6eb Iustin Pop
    @type amount: integer
642 6d33a6eb Iustin Pop
    @param amount: the desired increase in (user-visible) disk space
643 6d33a6eb Iustin Pop
    @rtype: dict
644 6d33a6eb Iustin Pop
    @return: a dictionary of volume-groups and the required size
645 6d33a6eb Iustin Pop

646 6d33a6eb Iustin Pop
    """
647 6d33a6eb Iustin Pop
    if self.dev_type == constants.LD_LV:
648 6d33a6eb Iustin Pop
      return {self.logical_id[0]: amount}
649 6d33a6eb Iustin Pop
    elif self.dev_type == constants.LD_DRBD8:
650 6d33a6eb Iustin Pop
      if self.children:
651 6d33a6eb Iustin Pop
        return self.children[0].ComputeGrowth(amount)
652 6d33a6eb Iustin Pop
      else:
653 6d33a6eb Iustin Pop
        return {}
654 6d33a6eb Iustin Pop
    else:
655 6d33a6eb Iustin Pop
      # Other disk types do not require VG space
656 6d33a6eb Iustin Pop
      return {}
657 6d33a6eb Iustin Pop
658 acec9d51 Iustin Pop
  def RecordGrow(self, amount):
659 acec9d51 Iustin Pop
    """Update the size of this disk after growth.
660 acec9d51 Iustin Pop

661 acec9d51 Iustin Pop
    This method recurses over the disks's children and updates their
662 acec9d51 Iustin Pop
    size correspondigly. The method needs to be kept in sync with the
663 acec9d51 Iustin Pop
    actual algorithms from bdev.
664 acec9d51 Iustin Pop

665 acec9d51 Iustin Pop
    """
666 7181fba0 Constantinos Venetsanopoulos
    if self.dev_type in (constants.LD_LV, constants.LD_FILE,
667 376631d1 Constantinos Venetsanopoulos
                         constants.LD_RBD, constants.LD_EXT):
668 acec9d51 Iustin Pop
      self.size += amount
669 acec9d51 Iustin Pop
    elif self.dev_type == constants.LD_DRBD8:
670 acec9d51 Iustin Pop
      if self.children:
671 acec9d51 Iustin Pop
        self.children[0].RecordGrow(amount)
672 acec9d51 Iustin Pop
      self.size += amount
673 acec9d51 Iustin Pop
    else:
674 acec9d51 Iustin Pop
      raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
675 acec9d51 Iustin Pop
                                   " disk type %s" % self.dev_type)
676 acec9d51 Iustin Pop
677 735e1318 Michael Hanselmann
  def Update(self, size=None, mode=None):
678 735e1318 Michael Hanselmann
    """Apply changes to size and mode.
679 735e1318 Michael Hanselmann

680 735e1318 Michael Hanselmann
    """
681 735e1318 Michael Hanselmann
    if self.dev_type == constants.LD_DRBD8:
682 735e1318 Michael Hanselmann
      if self.children:
683 735e1318 Michael Hanselmann
        self.children[0].Update(size=size, mode=mode)
684 735e1318 Michael Hanselmann
    else:
685 735e1318 Michael Hanselmann
      assert not self.children
686 735e1318 Michael Hanselmann
687 735e1318 Michael Hanselmann
    if size is not None:
688 735e1318 Michael Hanselmann
      self.size = size
689 735e1318 Michael Hanselmann
    if mode is not None:
690 735e1318 Michael Hanselmann
      self.mode = mode
691 735e1318 Michael Hanselmann
692 a805ec18 Iustin Pop
  def UnsetSize(self):
693 a805ec18 Iustin Pop
    """Sets recursively the size to zero for the disk and its children.
694 a805ec18 Iustin Pop

695 a805ec18 Iustin Pop
    """
696 a805ec18 Iustin Pop
    if self.children:
697 a805ec18 Iustin Pop
      for child in self.children:
698 a805ec18 Iustin Pop
        child.UnsetSize()
699 a805ec18 Iustin Pop
    self.size = 0
700 a805ec18 Iustin Pop
701 0402302c Iustin Pop
  def SetPhysicalID(self, target_node, nodes_ip):
702 0402302c Iustin Pop
    """Convert the logical ID to the physical ID.
703 0402302c Iustin Pop

704 0402302c Iustin Pop
    This is used only for drbd, which needs ip/port configuration.
705 0402302c Iustin Pop

706 0402302c Iustin Pop
    The routine descends down and updates its children also, because
707 0402302c Iustin Pop
    this helps when the only the top device is passed to the remote
708 0402302c Iustin Pop
    node.
709 0402302c Iustin Pop

710 0402302c Iustin Pop
    Arguments:
711 0402302c Iustin Pop
      - target_node: the node we wish to configure for
712 0402302c Iustin Pop
      - nodes_ip: a mapping of node name to ip
713 0402302c Iustin Pop

714 0402302c Iustin Pop
    The target_node must exist in in nodes_ip, and must be one of the
715 0402302c Iustin Pop
    nodes in the logical ID for each of the DRBD devices encountered
716 0402302c Iustin Pop
    in the disk tree.
717 0402302c Iustin Pop

718 0402302c Iustin Pop
    """
719 0402302c Iustin Pop
    if self.children:
720 0402302c Iustin Pop
      for child in self.children:
721 0402302c Iustin Pop
        child.SetPhysicalID(target_node, nodes_ip)
722 0402302c Iustin Pop
723 0402302c Iustin Pop
    if self.logical_id is None and self.physical_id is not None:
724 0402302c Iustin Pop
      return
725 0402302c Iustin Pop
    if self.dev_type in constants.LDS_DRBD:
726 f9518d38 Iustin Pop
      pnode, snode, port, pminor, sminor, secret = self.logical_id
727 0402302c Iustin Pop
      if target_node not in (pnode, snode):
728 0402302c Iustin Pop
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
729 0402302c Iustin Pop
                                        target_node)
730 0402302c Iustin Pop
      pnode_ip = nodes_ip.get(pnode, None)
731 0402302c Iustin Pop
      snode_ip = nodes_ip.get(snode, None)
732 0402302c Iustin Pop
      if pnode_ip is None or snode_ip is None:
733 0402302c Iustin Pop
        raise errors.ConfigurationError("Can't find primary or secondary node"
734 0402302c Iustin Pop
                                        " for %s" % str(self))
735 ffa1c0dc Iustin Pop
      p_data = (pnode_ip, port)
736 ffa1c0dc Iustin Pop
      s_data = (snode_ip, port)
737 0402302c Iustin Pop
      if pnode == target_node:
738 f9518d38 Iustin Pop
        self.physical_id = p_data + s_data + (pminor, secret)
739 0402302c Iustin Pop
      else: # it must be secondary, we tested above
740 f9518d38 Iustin Pop
        self.physical_id = s_data + p_data + (sminor, secret)
741 0402302c Iustin Pop
    else:
742 0402302c Iustin Pop
      self.physical_id = self.logical_id
743 0402302c Iustin Pop
    return
744 0402302c Iustin Pop
745 ff9c047c Iustin Pop
  def ToDict(self):
746 ff9c047c Iustin Pop
    """Disk-specific conversion to standard python types.
747 ff9c047c Iustin Pop

748 ff9c047c Iustin Pop
    This replaces the children lists of objects with lists of
749 ff9c047c Iustin Pop
    standard python types.
750 ff9c047c Iustin Pop

751 ff9c047c Iustin Pop
    """
752 ff9c047c Iustin Pop
    bo = super(Disk, self).ToDict()
753 ff9c047c Iustin Pop
754 ff9c047c Iustin Pop
    for attr in ("children",):
755 ff9c047c Iustin Pop
      alist = bo.get(attr, None)
756 ff9c047c Iustin Pop
      if alist:
757 fe502d25 Iustin Pop
        bo[attr] = outils.ContainerToDicts(alist)
758 ff9c047c Iustin Pop
    return bo
759 ff9c047c Iustin Pop
760 ff9c047c Iustin Pop
  @classmethod
761 ff9c047c Iustin Pop
  def FromDict(cls, val):
762 ff9c047c Iustin Pop
    """Custom function for Disks
763 ff9c047c Iustin Pop

764 ff9c047c Iustin Pop
    """
765 ff9c047c Iustin Pop
    obj = super(Disk, cls).FromDict(val)
766 ff9c047c Iustin Pop
    if obj.children:
767 fe502d25 Iustin Pop
      obj.children = outils.ContainerFromDicts(obj.children, list, Disk)
768 ff9c047c Iustin Pop
    if obj.logical_id and isinstance(obj.logical_id, list):
769 ff9c047c Iustin Pop
      obj.logical_id = tuple(obj.logical_id)
770 ff9c047c Iustin Pop
    if obj.physical_id and isinstance(obj.physical_id, list):
771 ff9c047c Iustin Pop
      obj.physical_id = tuple(obj.physical_id)
772 f9518d38 Iustin Pop
    if obj.dev_type in constants.LDS_DRBD:
773 f9518d38 Iustin Pop
      # we need a tuple of length six here
774 f9518d38 Iustin Pop
      if len(obj.logical_id) < 6:
775 f9518d38 Iustin Pop
        obj.logical_id += (None,) * (6 - len(obj.logical_id))
776 ff9c047c Iustin Pop
    return obj
777 ff9c047c Iustin Pop
778 65a15336 Iustin Pop
  def __str__(self):
779 65a15336 Iustin Pop
    """Custom str() formatter for disks.
780 65a15336 Iustin Pop

781 65a15336 Iustin Pop
    """
782 65a15336 Iustin Pop
    if self.dev_type == constants.LD_LV:
783 e687ec01 Michael Hanselmann
      val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
784 65a15336 Iustin Pop
    elif self.dev_type in constants.LDS_DRBD:
785 89f28b76 Iustin Pop
      node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
786 00fb8246 Michael Hanselmann
      val = "<DRBD8("
787 073ca59e Iustin Pop
      if self.physical_id is None:
788 073ca59e Iustin Pop
        phy = "unconfigured"
789 073ca59e Iustin Pop
      else:
790 073ca59e Iustin Pop
        phy = ("configured as %s:%s %s:%s" %
791 25a915d0 Iustin Pop
               (self.physical_id[0], self.physical_id[1],
792 25a915d0 Iustin Pop
                self.physical_id[2], self.physical_id[3]))
793 073ca59e Iustin Pop
794 89f28b76 Iustin Pop
      val += ("hosts=%s/%d-%s/%d, port=%s, %s, " %
795 89f28b76 Iustin Pop
              (node_a, minor_a, node_b, minor_b, port, phy))
796 65a15336 Iustin Pop
      if self.children and self.children.count(None) == 0:
797 65a15336 Iustin Pop
        val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
798 65a15336 Iustin Pop
      else:
799 65a15336 Iustin Pop
        val += "no local storage"
800 65a15336 Iustin Pop
    else:
801 65a15336 Iustin Pop
      val = ("<Disk(type=%s, logical_id=%s, physical_id=%s, children=%s" %
802 65a15336 Iustin Pop
             (self.dev_type, self.logical_id, self.physical_id, self.children))
803 65a15336 Iustin Pop
    if self.iv_name is None:
804 65a15336 Iustin Pop
      val += ", not visible"
805 65a15336 Iustin Pop
    else:
806 65a15336 Iustin Pop
      val += ", visible as /dev/%s" % self.iv_name
807 fd965830 Iustin Pop
    if isinstance(self.size, int):
808 fd965830 Iustin Pop
      val += ", size=%dm)>" % self.size
809 fd965830 Iustin Pop
    else:
810 fd965830 Iustin Pop
      val += ", size='%s')>" % (self.size,)
811 65a15336 Iustin Pop
    return val
812 65a15336 Iustin Pop
813 332d0e37 Iustin Pop
  def Verify(self):
814 332d0e37 Iustin Pop
    """Checks that this disk is correctly configured.
815 332d0e37 Iustin Pop

816 332d0e37 Iustin Pop
    """
817 7c4d6c7b Michael Hanselmann
    all_errors = []
818 332d0e37 Iustin Pop
    if self.mode not in constants.DISK_ACCESS_SET:
819 7c4d6c7b Michael Hanselmann
      all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
820 7c4d6c7b Michael Hanselmann
    return all_errors
821 332d0e37 Iustin Pop
822 90d726a8 Iustin Pop
  def UpgradeConfig(self):
823 90d726a8 Iustin Pop
    """Fill defaults for missing configuration values.
824 90d726a8 Iustin Pop

825 90d726a8 Iustin Pop
    """
826 90d726a8 Iustin Pop
    if self.children:
827 90d726a8 Iustin Pop
      for child in self.children:
828 90d726a8 Iustin Pop
        child.UpgradeConfig()
829 bc5d0215 Andrea Spadaccini
830 cce46164 René Nussbaumer
    # FIXME: Make this configurable in Ganeti 2.7
831 54666867 Dimitris Aragiorgis
    # Params should be an empty dict that gets filled any time needed
832 54666867 Dimitris Aragiorgis
    # In case of ext template we allow arbitrary params that should not
833 54666867 Dimitris Aragiorgis
    # be overrided during a config reload/upgrade.
834 54666867 Dimitris Aragiorgis
    if not self.params or not isinstance(self.params, dict):
835 54666867 Dimitris Aragiorgis
      self.params = {}
836 54666867 Dimitris Aragiorgis
837 90d726a8 Iustin Pop
    # add here config upgrade for this disk
838 90d726a8 Iustin Pop
839 77b0d264 Michele Tartara
    # If the file driver is empty, fill it up with the default value
840 77b0d264 Michele Tartara
    if self.dev_type == constants.LD_FILE and self.physical_id[0] is None:
841 77b0d264 Michele Tartara
      self.physical_id[0] = constants.FD_DEFAULT
842 77b0d264 Michele Tartara
843 cd46491f René Nussbaumer
  @staticmethod
844 cd46491f René Nussbaumer
  def ComputeLDParams(disk_template, disk_params):
845 cd46491f René Nussbaumer
    """Computes Logical Disk parameters from Disk Template parameters.
846 cd46491f René Nussbaumer

847 cd46491f René Nussbaumer
    @type disk_template: string
848 cd46491f René Nussbaumer
    @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
849 cd46491f René Nussbaumer
    @type disk_params: dict
850 cd46491f René Nussbaumer
    @param disk_params: disk template parameters;
851 cd46491f René Nussbaumer
                        dict(template_name -> parameters
852 cd46491f René Nussbaumer
    @rtype: list(dict)
853 cd46491f René Nussbaumer
    @return: a list of dicts, one for each node of the disk hierarchy. Each dict
854 cd46491f René Nussbaumer
      contains the LD parameters of the node. The tree is flattened in-order.
855 cd46491f René Nussbaumer

856 cd46491f René Nussbaumer
    """
857 cd46491f René Nussbaumer
    if disk_template not in constants.DISK_TEMPLATES:
858 cd46491f René Nussbaumer
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
859 cd46491f René Nussbaumer
860 cd46491f René Nussbaumer
    assert disk_template in disk_params
861 cd46491f René Nussbaumer
862 cd46491f René Nussbaumer
    result = list()
863 cd46491f René Nussbaumer
    dt_params = disk_params[disk_template]
864 cd46491f René Nussbaumer
    if disk_template == constants.DT_DRBD8:
865 52f93ffd Michael Hanselmann
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_DRBD8], {
866 cd46491f René Nussbaumer
        constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
867 cd46491f René Nussbaumer
        constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
868 cd46491f René Nussbaumer
        constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
869 cd46491f René Nussbaumer
        constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
870 cd46491f René Nussbaumer
        constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
871 cd46491f René Nussbaumer
        constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
872 cd46491f René Nussbaumer
        constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
873 cd46491f René Nussbaumer
        constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
874 cd46491f René Nussbaumer
        constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
875 cd46491f René Nussbaumer
        constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
876 cd46491f René Nussbaumer
        constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
877 cd46491f René Nussbaumer
        constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
878 52f93ffd Michael Hanselmann
        }))
879 cd46491f René Nussbaumer
880 cd46491f René Nussbaumer
      # data LV
881 52f93ffd Michael Hanselmann
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
882 cd46491f René Nussbaumer
        constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
883 52f93ffd Michael Hanselmann
        }))
884 cd46491f René Nussbaumer
885 cd46491f René Nussbaumer
      # metadata LV
886 52f93ffd Michael Hanselmann
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
887 cd46491f René Nussbaumer
        constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
888 52f93ffd Michael Hanselmann
        }))
889 52f93ffd Michael Hanselmann
890 52f93ffd Michael Hanselmann
    elif disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
891 cd46491f René Nussbaumer
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_FILE])
892 cd46491f René Nussbaumer
893 cd46491f René Nussbaumer
    elif disk_template == constants.DT_PLAIN:
894 52f93ffd Michael Hanselmann
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
895 cd46491f René Nussbaumer
        constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
896 52f93ffd Michael Hanselmann
        }))
897 cd46491f René Nussbaumer
898 cd46491f René Nussbaumer
    elif disk_template == constants.DT_BLOCK:
899 cd46491f René Nussbaumer
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_BLOCKDEV])
900 cd46491f René Nussbaumer
901 cd46491f René Nussbaumer
    elif disk_template == constants.DT_RBD:
902 52f93ffd Michael Hanselmann
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_RBD], {
903 3c286190 Dimitris Aragiorgis
        constants.LDP_POOL: dt_params[constants.RBD_POOL],
904 52f93ffd Michael Hanselmann
        }))
905 cd46491f René Nussbaumer
906 938adc87 Constantinos Venetsanopoulos
    elif disk_template == constants.DT_EXT:
907 938adc87 Constantinos Venetsanopoulos
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_EXT])
908 938adc87 Constantinos Venetsanopoulos
909 cd46491f René Nussbaumer
    return result
910 cd46491f René Nussbaumer
911 a8083063 Iustin Pop
912 918eb80b Agata Murawska
class InstancePolicy(ConfigObject):
913 ffa339ca Iustin Pop
  """Config object representing instance policy limits dictionary.
914 918eb80b Agata Murawska

915 ffa339ca Iustin Pop
  Note that this object is not actually used in the config, it's just
916 ffa339ca Iustin Pop
  used as a placeholder for a few functions.
917 ffa339ca Iustin Pop

918 ffa339ca Iustin Pop
  """
919 918eb80b Agata Murawska
  @classmethod
920 8b057218 René Nussbaumer
  def CheckParameterSyntax(cls, ipolicy, check_std):
921 918eb80b Agata Murawska
    """ Check the instance policy for validity.
922 918eb80b Agata Murawska

923 da5f09ef Bernardo Dal Seno
    @type ipolicy: dict
924 da5f09ef Bernardo Dal Seno
    @param ipolicy: dictionary with min/max/std specs and policies
925 da5f09ef Bernardo Dal Seno
    @type check_std: bool
926 da5f09ef Bernardo Dal Seno
    @param check_std: Whether to check std value or just assume compliance
927 da5f09ef Bernardo Dal Seno
    @raise errors.ConfigurationError: when the policy is not legal
928 da5f09ef Bernardo Dal Seno

929 918eb80b Agata Murawska
    """
930 62fed51b Bernardo Dal Seno
    InstancePolicy.CheckISpecSyntax(ipolicy, check_std)
931 d04c9d45 Iustin Pop
    if constants.IPOLICY_DTS in ipolicy:
932 d04c9d45 Iustin Pop
      InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
933 ff6c5e55 Iustin Pop
    for key in constants.IPOLICY_PARAMETERS:
934 ff6c5e55 Iustin Pop
      if key in ipolicy:
935 ff6c5e55 Iustin Pop
        InstancePolicy.CheckParameter(key, ipolicy[key])
936 57dc299a Iustin Pop
    wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
937 57dc299a Iustin Pop
    if wrong_keys:
938 57dc299a Iustin Pop
      raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
939 57dc299a Iustin Pop
                                      utils.CommaJoin(wrong_keys))
940 918eb80b Agata Murawska
941 918eb80b Agata Murawska
  @classmethod
942 0f511c8a Bernardo Dal Seno
  def _CheckIncompleteSpec(cls, spec, keyname):
943 0f511c8a Bernardo Dal Seno
    missing_params = constants.ISPECS_PARAMETERS - frozenset(spec.keys())
944 0f511c8a Bernardo Dal Seno
    if missing_params:
945 0f511c8a Bernardo Dal Seno
      msg = ("Missing instance specs parameters for %s: %s" %
946 0f511c8a Bernardo Dal Seno
             (keyname, utils.CommaJoin(missing_params)))
947 0f511c8a Bernardo Dal Seno
      raise errors.ConfigurationError(msg)
948 0f511c8a Bernardo Dal Seno
949 0f511c8a Bernardo Dal Seno
  @classmethod
950 62fed51b Bernardo Dal Seno
  def CheckISpecSyntax(cls, ipolicy, check_std):
951 62fed51b Bernardo Dal Seno
    """Check the instance policy specs for validity.
952 62fed51b Bernardo Dal Seno

953 62fed51b Bernardo Dal Seno
    @type ipolicy: dict
954 62fed51b Bernardo Dal Seno
    @param ipolicy: dictionary with min/max/std specs
955 62fed51b Bernardo Dal Seno
    @type check_std: bool
956 62fed51b Bernardo Dal Seno
    @param check_std: Whether to check std value or just assume compliance
957 62fed51b Bernardo Dal Seno
    @raise errors.ConfigurationError: when specs are not valid
958 62fed51b Bernardo Dal Seno

959 62fed51b Bernardo Dal Seno
    """
960 62fed51b Bernardo Dal Seno
    if constants.ISPECS_MINMAX not in ipolicy:
961 62fed51b Bernardo Dal Seno
      # Nothing to check
962 62fed51b Bernardo Dal Seno
      return
963 62fed51b Bernardo Dal Seno
964 62fed51b Bernardo Dal Seno
    if check_std and constants.ISPECS_STD not in ipolicy:
965 62fed51b Bernardo Dal Seno
      msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
966 62fed51b Bernardo Dal Seno
      raise errors.ConfigurationError(msg)
967 62fed51b Bernardo Dal Seno
    stdspec = ipolicy.get(constants.ISPECS_STD)
968 b342c9dd Bernardo Dal Seno
    if check_std:
969 b342c9dd Bernardo Dal Seno
      InstancePolicy._CheckIncompleteSpec(stdspec, constants.ISPECS_STD)
970 b342c9dd Bernardo Dal Seno
971 41044e04 Bernardo Dal Seno
    if not ipolicy[constants.ISPECS_MINMAX]:
972 41044e04 Bernardo Dal Seno
      raise errors.ConfigurationError("Empty minmax specifications")
973 41044e04 Bernardo Dal Seno
    std_is_good = False
974 41044e04 Bernardo Dal Seno
    for minmaxspecs in ipolicy[constants.ISPECS_MINMAX]:
975 41044e04 Bernardo Dal Seno
      missing = constants.ISPECS_MINMAX_KEYS - frozenset(minmaxspecs.keys())
976 41044e04 Bernardo Dal Seno
      if missing:
977 41044e04 Bernardo Dal Seno
        msg = "Missing instance specification: %s" % utils.CommaJoin(missing)
978 41044e04 Bernardo Dal Seno
        raise errors.ConfigurationError(msg)
979 41044e04 Bernardo Dal Seno
      for (key, spec) in minmaxspecs.items():
980 41044e04 Bernardo Dal Seno
        InstancePolicy._CheckIncompleteSpec(spec, key)
981 41044e04 Bernardo Dal Seno
982 41044e04 Bernardo Dal Seno
      spec_std_ok = True
983 41044e04 Bernardo Dal Seno
      for param in constants.ISPECS_PARAMETERS:
984 41044e04 Bernardo Dal Seno
        par_std_ok = InstancePolicy._CheckISpecParamSyntax(minmaxspecs, stdspec,
985 41044e04 Bernardo Dal Seno
                                                           param, check_std)
986 41044e04 Bernardo Dal Seno
        spec_std_ok = spec_std_ok and par_std_ok
987 41044e04 Bernardo Dal Seno
      std_is_good = std_is_good or spec_std_ok
988 41044e04 Bernardo Dal Seno
    if not std_is_good:
989 b342c9dd Bernardo Dal Seno
      raise errors.ConfigurationError("Invalid std specifications")
990 62fed51b Bernardo Dal Seno
991 62fed51b Bernardo Dal Seno
  @classmethod
992 62fed51b Bernardo Dal Seno
  def _CheckISpecParamSyntax(cls, minmaxspecs, stdspec, name, check_std):
993 da5f09ef Bernardo Dal Seno
    """Check the instance policy specs for validity on a given key.
994 918eb80b Agata Murawska

995 da5f09ef Bernardo Dal Seno
    We check if the instance specs makes sense for a given key, that is
996 da5f09ef Bernardo Dal Seno
    if minmaxspecs[min][name] <= stdspec[name] <= minmaxspec[max][name].
997 918eb80b Agata Murawska

998 da5f09ef Bernardo Dal Seno
    @type minmaxspecs: dict
999 da5f09ef Bernardo Dal Seno
    @param minmaxspecs: dictionary with min and max instance spec
1000 da5f09ef Bernardo Dal Seno
    @type stdspec: dict
1001 da5f09ef Bernardo Dal Seno
    @param stdspec: dictionary with standard instance spec
1002 918eb80b Agata Murawska
    @type name: string
1003 918eb80b Agata Murawska
    @param name: what are the limits for
1004 8b057218 René Nussbaumer
    @type check_std: bool
1005 8b057218 René Nussbaumer
    @param check_std: Whether to check std value or just assume compliance
1006 b342c9dd Bernardo Dal Seno
    @rtype: bool
1007 b342c9dd Bernardo Dal Seno
    @return: C{True} when specs are valid, C{False} when standard spec for the
1008 b342c9dd Bernardo Dal Seno
        given name is not valid
1009 b342c9dd Bernardo Dal Seno
    @raise errors.ConfigurationError: when min/max specs for the given name
1010 b342c9dd Bernardo Dal Seno
        are not valid
1011 918eb80b Agata Murawska

1012 918eb80b Agata Murawska
    """
1013 da5f09ef Bernardo Dal Seno
    minspec = minmaxspecs[constants.ISPECS_MIN]
1014 da5f09ef Bernardo Dal Seno
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1015 0f511c8a Bernardo Dal Seno
    min_v = minspec[name]
1016 b342c9dd Bernardo Dal Seno
    max_v = maxspec[name]
1017 8b057218 René Nussbaumer
1018 b342c9dd Bernardo Dal Seno
    if min_v > max_v:
1019 b342c9dd Bernardo Dal Seno
      err = ("Invalid specification of min/max values for %s: %s/%s" %
1020 b342c9dd Bernardo Dal Seno
             (name, min_v, max_v))
1021 b342c9dd Bernardo Dal Seno
      raise errors.ConfigurationError(err)
1022 b342c9dd Bernardo Dal Seno
    elif check_std:
1023 da5f09ef Bernardo Dal Seno
      std_v = stdspec.get(name, min_v)
1024 b342c9dd Bernardo Dal Seno
      return std_v >= min_v and std_v <= max_v
1025 8b057218 René Nussbaumer
    else:
1026 b342c9dd Bernardo Dal Seno
      return True
1027 918eb80b Agata Murawska
1028 2cc673a3 Iustin Pop
  @classmethod
1029 2cc673a3 Iustin Pop
  def CheckDiskTemplates(cls, disk_templates):
1030 2cc673a3 Iustin Pop
    """Checks the disk templates for validity.
1031 2cc673a3 Iustin Pop

1032 2cc673a3 Iustin Pop
    """
1033 ba5c6c6b Bernardo Dal Seno
    if not disk_templates:
1034 ba5c6c6b Bernardo Dal Seno
      raise errors.ConfigurationError("Instance policy must contain" +
1035 ba5c6c6b Bernardo Dal Seno
                                      " at least one disk template")
1036 2cc673a3 Iustin Pop
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1037 2cc673a3 Iustin Pop
    if wrong:
1038 2cc673a3 Iustin Pop
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1039 2cc673a3 Iustin Pop
                                      utils.CommaJoin(wrong))
1040 2cc673a3 Iustin Pop
1041 ff6c5e55 Iustin Pop
  @classmethod
1042 ff6c5e55 Iustin Pop
  def CheckParameter(cls, key, value):
1043 ff6c5e55 Iustin Pop
    """Checks a parameter.
1044 ff6c5e55 Iustin Pop

1045 ff6c5e55 Iustin Pop
    Currently we expect all parameters to be float values.
1046 ff6c5e55 Iustin Pop

1047 ff6c5e55 Iustin Pop
    """
1048 ff6c5e55 Iustin Pop
    try:
1049 ff6c5e55 Iustin Pop
      float(value)
1050 ff6c5e55 Iustin Pop
    except (TypeError, ValueError), err:
1051 ff6c5e55 Iustin Pop
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1052 ff6c5e55 Iustin Pop
                                      " '%s', error: %s" % (key, value, err))
1053 ff6c5e55 Iustin Pop
1054 918eb80b Agata Murawska
1055 ec29fe40 Iustin Pop
class Instance(TaggableObject):
1056 a8083063 Iustin Pop
  """Config object representing an instance."""
1057 154b9580 Balazs Lecz
  __slots__ = [
1058 a8083063 Iustin Pop
    "name",
1059 a8083063 Iustin Pop
    "primary_node",
1060 a8083063 Iustin Pop
    "os",
1061 e69d05fd Iustin Pop
    "hypervisor",
1062 5bf7b5cf Iustin Pop
    "hvparams",
1063 5bf7b5cf Iustin Pop
    "beparams",
1064 1bdcbbab Iustin Pop
    "osparams",
1065 9ca8a7c5 Agata Murawska
    "admin_state",
1066 a8083063 Iustin Pop
    "nics",
1067 a8083063 Iustin Pop
    "disks",
1068 a8083063 Iustin Pop
    "disk_template",
1069 1d4a4b26 Thomas Thrainer
    "disks_active",
1070 58acb49d Alexander Schreiber
    "network_port",
1071 be1fa613 Iustin Pop
    "serial_no",
1072 e1dcc53a Iustin Pop
    ] + _TIMESTAMPS + _UUID
1073 a8083063 Iustin Pop
1074 a8083063 Iustin Pop
  def _ComputeSecondaryNodes(self):
1075 a8083063 Iustin Pop
    """Compute the list of secondary nodes.
1076 a8083063 Iustin Pop

1077 cfcc5c6d Iustin Pop
    This is a simple wrapper over _ComputeAllNodes.
1078 cfcc5c6d Iustin Pop

1079 cfcc5c6d Iustin Pop
    """
1080 cfcc5c6d Iustin Pop
    all_nodes = set(self._ComputeAllNodes())
1081 cfcc5c6d Iustin Pop
    all_nodes.discard(self.primary_node)
1082 cfcc5c6d Iustin Pop
    return tuple(all_nodes)
1083 cfcc5c6d Iustin Pop
1084 cfcc5c6d Iustin Pop
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1085 05325a35 Bernardo Dal Seno
                             "List of names of secondary nodes")
1086 cfcc5c6d Iustin Pop
1087 cfcc5c6d Iustin Pop
  def _ComputeAllNodes(self):
1088 cfcc5c6d Iustin Pop
    """Compute the list of all nodes.
1089 cfcc5c6d Iustin Pop

1090 a8083063 Iustin Pop
    Since the data is already there (in the drbd disks), keeping it as
1091 a8083063 Iustin Pop
    a separate normal attribute is redundant and if not properly
1092 a8083063 Iustin Pop
    synchronised can cause problems. Thus it's better to compute it
1093 a8083063 Iustin Pop
    dynamically.
1094 a8083063 Iustin Pop

1095 a8083063 Iustin Pop
    """
1096 cfcc5c6d Iustin Pop
    def _Helper(nodes, device):
1097 cfcc5c6d Iustin Pop
      """Recursively computes nodes given a top device."""
1098 a1f445d3 Iustin Pop
      if device.dev_type in constants.LDS_DRBD:
1099 cfcc5c6d Iustin Pop
        nodea, nodeb = device.logical_id[:2]
1100 cfcc5c6d Iustin Pop
        nodes.add(nodea)
1101 cfcc5c6d Iustin Pop
        nodes.add(nodeb)
1102 a8083063 Iustin Pop
      if device.children:
1103 a8083063 Iustin Pop
        for child in device.children:
1104 cfcc5c6d Iustin Pop
          _Helper(nodes, child)
1105 a8083063 Iustin Pop
1106 cfcc5c6d Iustin Pop
    all_nodes = set()
1107 99c7b2a1 Iustin Pop
    all_nodes.add(self.primary_node)
1108 a8083063 Iustin Pop
    for device in self.disks:
1109 cfcc5c6d Iustin Pop
      _Helper(all_nodes, device)
1110 cfcc5c6d Iustin Pop
    return tuple(all_nodes)
1111 a8083063 Iustin Pop
1112 cfcc5c6d Iustin Pop
  all_nodes = property(_ComputeAllNodes, None, None,
1113 05325a35 Bernardo Dal Seno
                       "List of names of all the nodes of the instance")
1114 a8083063 Iustin Pop
1115 a8083063 Iustin Pop
  def MapLVsByNode(self, lvmap=None, devs=None, node=None):
1116 a8083063 Iustin Pop
    """Provide a mapping of nodes to LVs this instance owns.
1117 a8083063 Iustin Pop

1118 c41eea6e Iustin Pop
    This function figures out what logical volumes should belong on
1119 c41eea6e Iustin Pop
    which nodes, recursing through a device tree.
1120 a8083063 Iustin Pop

1121 c41eea6e Iustin Pop
    @param lvmap: optional dictionary to receive the
1122 c41eea6e Iustin Pop
        'node' : ['lv', ...] data.
1123 a8083063 Iustin Pop

1124 84d7e26b Dmitry Chernyak
    @return: None if lvmap arg is given, otherwise, a dictionary of
1125 84d7e26b Dmitry Chernyak
        the form { 'nodename' : ['volume1', 'volume2', ...], ... };
1126 84d7e26b Dmitry Chernyak
        volumeN is of the form "vg_name/lv_name", compatible with
1127 84d7e26b Dmitry Chernyak
        GetVolumeList()
1128 a8083063 Iustin Pop

1129 a8083063 Iustin Pop
    """
1130 5ae4945a Iustin Pop
    if node is None:
1131 a8083063 Iustin Pop
      node = self.primary_node
1132 a8083063 Iustin Pop
1133 a8083063 Iustin Pop
    if lvmap is None:
1134 e687ec01 Michael Hanselmann
      lvmap = {
1135 e687ec01 Michael Hanselmann
        node: [],
1136 e687ec01 Michael Hanselmann
        }
1137 a8083063 Iustin Pop
      ret = lvmap
1138 a8083063 Iustin Pop
    else:
1139 a8083063 Iustin Pop
      if not node in lvmap:
1140 a8083063 Iustin Pop
        lvmap[node] = []
1141 a8083063 Iustin Pop
      ret = None
1142 a8083063 Iustin Pop
1143 a8083063 Iustin Pop
    if not devs:
1144 a8083063 Iustin Pop
      devs = self.disks
1145 a8083063 Iustin Pop
1146 a8083063 Iustin Pop
    for dev in devs:
1147 fe96220b Iustin Pop
      if dev.dev_type == constants.LD_LV:
1148 e687ec01 Michael Hanselmann
        lvmap[node].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1149 a8083063 Iustin Pop
1150 a1f445d3 Iustin Pop
      elif dev.dev_type in constants.LDS_DRBD:
1151 a8083063 Iustin Pop
        if dev.children:
1152 a8083063 Iustin Pop
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1153 a8083063 Iustin Pop
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1154 a8083063 Iustin Pop
1155 a8083063 Iustin Pop
      elif dev.children:
1156 a8083063 Iustin Pop
        self.MapLVsByNode(lvmap, dev.children, node)
1157 a8083063 Iustin Pop
1158 a8083063 Iustin Pop
    return ret
1159 a8083063 Iustin Pop
1160 ad24e046 Iustin Pop
  def FindDisk(self, idx):
1161 ad24e046 Iustin Pop
    """Find a disk given having a specified index.
1162 644eeef9 Iustin Pop

1163 ad24e046 Iustin Pop
    This is just a wrapper that does validation of the index.
1164 644eeef9 Iustin Pop

1165 ad24e046 Iustin Pop
    @type idx: int
1166 ad24e046 Iustin Pop
    @param idx: the disk index
1167 ad24e046 Iustin Pop
    @rtype: L{Disk}
1168 ad24e046 Iustin Pop
    @return: the corresponding disk
1169 ad24e046 Iustin Pop
    @raise errors.OpPrereqError: when the given index is not valid
1170 644eeef9 Iustin Pop

1171 ad24e046 Iustin Pop
    """
1172 ad24e046 Iustin Pop
    try:
1173 ad24e046 Iustin Pop
      idx = int(idx)
1174 ad24e046 Iustin Pop
      return self.disks[idx]
1175 691744c4 Iustin Pop
    except (TypeError, ValueError), err:
1176 debac808 Iustin Pop
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1177 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
1178 ad24e046 Iustin Pop
    except IndexError:
1179 ad24e046 Iustin Pop
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1180 daa55b04 Michael Hanselmann
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1181 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
1182 644eeef9 Iustin Pop
1183 ff9c047c Iustin Pop
  def ToDict(self):
1184 ff9c047c Iustin Pop
    """Instance-specific conversion to standard python types.
1185 ff9c047c Iustin Pop

1186 ff9c047c Iustin Pop
    This replaces the children lists of objects with lists of standard
1187 ff9c047c Iustin Pop
    python types.
1188 ff9c047c Iustin Pop

1189 ff9c047c Iustin Pop
    """
1190 ff9c047c Iustin Pop
    bo = super(Instance, self).ToDict()
1191 ff9c047c Iustin Pop
1192 ff9c047c Iustin Pop
    for attr in "nics", "disks":
1193 ff9c047c Iustin Pop
      alist = bo.get(attr, None)
1194 ff9c047c Iustin Pop
      if alist:
1195 fe502d25 Iustin Pop
        nlist = outils.ContainerToDicts(alist)
1196 ff9c047c Iustin Pop
      else:
1197 ff9c047c Iustin Pop
        nlist = []
1198 ff9c047c Iustin Pop
      bo[attr] = nlist
1199 ff9c047c Iustin Pop
    return bo
1200 ff9c047c Iustin Pop
1201 ff9c047c Iustin Pop
  @classmethod
1202 ff9c047c Iustin Pop
  def FromDict(cls, val):
1203 ff9c047c Iustin Pop
    """Custom function for instances.
1204 ff9c047c Iustin Pop

1205 ff9c047c Iustin Pop
    """
1206 9ca8a7c5 Agata Murawska
    if "admin_state" not in val:
1207 9ca8a7c5 Agata Murawska
      if val.get("admin_up", False):
1208 9ca8a7c5 Agata Murawska
        val["admin_state"] = constants.ADMINST_UP
1209 9ca8a7c5 Agata Murawska
      else:
1210 9ca8a7c5 Agata Murawska
        val["admin_state"] = constants.ADMINST_DOWN
1211 9ca8a7c5 Agata Murawska
    if "admin_up" in val:
1212 9ca8a7c5 Agata Murawska
      del val["admin_up"]
1213 ff9c047c Iustin Pop
    obj = super(Instance, cls).FromDict(val)
1214 fe502d25 Iustin Pop
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1215 fe502d25 Iustin Pop
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1216 ff9c047c Iustin Pop
    return obj
1217 ff9c047c Iustin Pop
1218 90d726a8 Iustin Pop
  def UpgradeConfig(self):
1219 90d726a8 Iustin Pop
    """Fill defaults for missing configuration values.
1220 90d726a8 Iustin Pop

1221 90d726a8 Iustin Pop
    """
1222 90d726a8 Iustin Pop
    for nic in self.nics:
1223 90d726a8 Iustin Pop
      nic.UpgradeConfig()
1224 90d726a8 Iustin Pop
    for disk in self.disks:
1225 90d726a8 Iustin Pop
      disk.UpgradeConfig()
1226 7736a5f2 Iustin Pop
    if self.hvparams:
1227 7736a5f2 Iustin Pop
      for key in constants.HVC_GLOBALS:
1228 7736a5f2 Iustin Pop
        try:
1229 7736a5f2 Iustin Pop
          del self.hvparams[key]
1230 7736a5f2 Iustin Pop
        except KeyError:
1231 7736a5f2 Iustin Pop
          pass
1232 1bdcbbab Iustin Pop
    if self.osparams is None:
1233 1bdcbbab Iustin Pop
      self.osparams = {}
1234 8c72ab2b Guido Trotter
    UpgradeBeParams(self.beparams)
1235 a8e07057 Thomas Thrainer
    if self.disks_active is None:
1236 a8e07057 Thomas Thrainer
      self.disks_active = self.admin_state == constants.ADMINST_UP
1237 90d726a8 Iustin Pop
1238 a8083063 Iustin Pop
1239 a8083063 Iustin Pop
class OS(ConfigObject):
1240 b41b3516 Iustin Pop
  """Config object representing an operating system.
1241 b41b3516 Iustin Pop

1242 b41b3516 Iustin Pop
  @type supported_parameters: list
1243 b41b3516 Iustin Pop
  @ivar supported_parameters: a list of tuples, name and description,
1244 b41b3516 Iustin Pop
      containing the supported parameters by this OS
1245 b41b3516 Iustin Pop

1246 870dc44c Iustin Pop
  @type VARIANT_DELIM: string
1247 870dc44c Iustin Pop
  @cvar VARIANT_DELIM: the variant delimiter
1248 870dc44c Iustin Pop

1249 b41b3516 Iustin Pop
  """
1250 a8083063 Iustin Pop
  __slots__ = [
1251 a8083063 Iustin Pop
    "name",
1252 a8083063 Iustin Pop
    "path",
1253 082a7f91 Guido Trotter
    "api_versions",
1254 a8083063 Iustin Pop
    "create_script",
1255 a8083063 Iustin Pop
    "export_script",
1256 386b57af Iustin Pop
    "import_script",
1257 386b57af Iustin Pop
    "rename_script",
1258 b41b3516 Iustin Pop
    "verify_script",
1259 6d79896b Guido Trotter
    "supported_variants",
1260 b41b3516 Iustin Pop
    "supported_parameters",
1261 a8083063 Iustin Pop
    ]
1262 a8083063 Iustin Pop
1263 870dc44c Iustin Pop
  VARIANT_DELIM = "+"
1264 870dc44c Iustin Pop
1265 870dc44c Iustin Pop
  @classmethod
1266 870dc44c Iustin Pop
  def SplitNameVariant(cls, name):
1267 870dc44c Iustin Pop
    """Splits the name into the proper name and variant.
1268 870dc44c Iustin Pop

1269 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1270 870dc44c Iustin Pop
    @rtype: list
1271 870dc44c Iustin Pop
    @return: a list of two elements; if the original name didn't
1272 870dc44c Iustin Pop
        contain a variant, it's returned as an empty string
1273 870dc44c Iustin Pop

1274 870dc44c Iustin Pop
    """
1275 870dc44c Iustin Pop
    nv = name.split(cls.VARIANT_DELIM, 1)
1276 870dc44c Iustin Pop
    if len(nv) == 1:
1277 870dc44c Iustin Pop
      nv.append("")
1278 870dc44c Iustin Pop
    return nv
1279 870dc44c Iustin Pop
1280 870dc44c Iustin Pop
  @classmethod
1281 870dc44c Iustin Pop
  def GetName(cls, name):
1282 870dc44c Iustin Pop
    """Returns the proper name of the os (without the variant).
1283 870dc44c Iustin Pop

1284 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1285 870dc44c Iustin Pop

1286 870dc44c Iustin Pop
    """
1287 870dc44c Iustin Pop
    return cls.SplitNameVariant(name)[0]
1288 870dc44c Iustin Pop
1289 870dc44c Iustin Pop
  @classmethod
1290 870dc44c Iustin Pop
  def GetVariant(cls, name):
1291 870dc44c Iustin Pop
    """Returns the variant the os (without the base name).
1292 870dc44c Iustin Pop

1293 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1294 870dc44c Iustin Pop

1295 870dc44c Iustin Pop
    """
1296 870dc44c Iustin Pop
    return cls.SplitNameVariant(name)[1]
1297 870dc44c Iustin Pop
1298 7c0d6283 Michael Hanselmann
1299 376631d1 Constantinos Venetsanopoulos
class ExtStorage(ConfigObject):
1300 376631d1 Constantinos Venetsanopoulos
  """Config object representing an External Storage Provider.
1301 376631d1 Constantinos Venetsanopoulos

1302 376631d1 Constantinos Venetsanopoulos
  """
1303 376631d1 Constantinos Venetsanopoulos
  __slots__ = [
1304 376631d1 Constantinos Venetsanopoulos
    "name",
1305 376631d1 Constantinos Venetsanopoulos
    "path",
1306 376631d1 Constantinos Venetsanopoulos
    "create_script",
1307 376631d1 Constantinos Venetsanopoulos
    "remove_script",
1308 376631d1 Constantinos Venetsanopoulos
    "grow_script",
1309 376631d1 Constantinos Venetsanopoulos
    "attach_script",
1310 376631d1 Constantinos Venetsanopoulos
    "detach_script",
1311 376631d1 Constantinos Venetsanopoulos
    "setinfo_script",
1312 938adc87 Constantinos Venetsanopoulos
    "verify_script",
1313 938adc87 Constantinos Venetsanopoulos
    "supported_parameters",
1314 376631d1 Constantinos Venetsanopoulos
    ]
1315 376631d1 Constantinos Venetsanopoulos
1316 376631d1 Constantinos Venetsanopoulos
1317 5f06ce5e Michael Hanselmann
class NodeHvState(ConfigObject):
1318 5f06ce5e Michael Hanselmann
  """Hypvervisor state on a node.
1319 5f06ce5e Michael Hanselmann

1320 5f06ce5e Michael Hanselmann
  @ivar mem_total: Total amount of memory
1321 5f06ce5e Michael Hanselmann
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1322 5f06ce5e Michael Hanselmann
    available)
1323 5f06ce5e Michael Hanselmann
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1324 5f06ce5e Michael Hanselmann
    rounding
1325 5f06ce5e Michael Hanselmann
  @ivar mem_inst: Memory used by instances living on node
1326 5f06ce5e Michael Hanselmann
  @ivar cpu_total: Total node CPU core count
1327 5f06ce5e Michael Hanselmann
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1328 5f06ce5e Michael Hanselmann

1329 5f06ce5e Michael Hanselmann
  """
1330 5f06ce5e Michael Hanselmann
  __slots__ = [
1331 5f06ce5e Michael Hanselmann
    "mem_total",
1332 5f06ce5e Michael Hanselmann
    "mem_node",
1333 5f06ce5e Michael Hanselmann
    "mem_hv",
1334 5f06ce5e Michael Hanselmann
    "mem_inst",
1335 5f06ce5e Michael Hanselmann
    "cpu_total",
1336 5f06ce5e Michael Hanselmann
    "cpu_node",
1337 5f06ce5e Michael Hanselmann
    ] + _TIMESTAMPS
1338 5f06ce5e Michael Hanselmann
1339 5f06ce5e Michael Hanselmann
1340 5f06ce5e Michael Hanselmann
class NodeDiskState(ConfigObject):
1341 5f06ce5e Michael Hanselmann
  """Disk state on a node.
1342 5f06ce5e Michael Hanselmann

1343 5f06ce5e Michael Hanselmann
  """
1344 5f06ce5e Michael Hanselmann
  __slots__ = [
1345 5f06ce5e Michael Hanselmann
    "total",
1346 5f06ce5e Michael Hanselmann
    "reserved",
1347 5f06ce5e Michael Hanselmann
    "overhead",
1348 5f06ce5e Michael Hanselmann
    ] + _TIMESTAMPS
1349 5f06ce5e Michael Hanselmann
1350 5f06ce5e Michael Hanselmann
1351 ec29fe40 Iustin Pop
class Node(TaggableObject):
1352 634d30f4 Michael Hanselmann
  """Config object representing a node.
1353 634d30f4 Michael Hanselmann

1354 634d30f4 Michael Hanselmann
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1355 634d30f4 Michael Hanselmann
  @ivar hv_state_static: Hypervisor state overriden by user
1356 634d30f4 Michael Hanselmann
  @ivar disk_state: Disk state (e.g. free space)
1357 634d30f4 Michael Hanselmann
  @ivar disk_state_static: Disk state overriden by user
1358 634d30f4 Michael Hanselmann

1359 634d30f4 Michael Hanselmann
  """
1360 154b9580 Balazs Lecz
  __slots__ = [
1361 ec29fe40 Iustin Pop
    "name",
1362 ec29fe40 Iustin Pop
    "primary_ip",
1363 ec29fe40 Iustin Pop
    "secondary_ip",
1364 be1fa613 Iustin Pop
    "serial_no",
1365 8b8b8b81 Iustin Pop
    "master_candidate",
1366 fc0fe88c Iustin Pop
    "offline",
1367 af64c0ea Iustin Pop
    "drained",
1368 f936c153 Iustin Pop
    "group",
1369 490acd18 Iustin Pop
    "master_capable",
1370 490acd18 Iustin Pop
    "vm_capable",
1371 095e71aa René Nussbaumer
    "ndparams",
1372 25124d4a René Nussbaumer
    "powered",
1373 5b49ed09 René Nussbaumer
    "hv_state",
1374 634d30f4 Michael Hanselmann
    "hv_state_static",
1375 5b49ed09 René Nussbaumer
    "disk_state",
1376 634d30f4 Michael Hanselmann
    "disk_state_static",
1377 e1dcc53a Iustin Pop
    ] + _TIMESTAMPS + _UUID
1378 a8083063 Iustin Pop
1379 490acd18 Iustin Pop
  def UpgradeConfig(self):
1380 490acd18 Iustin Pop
    """Fill defaults for missing configuration values.
1381 490acd18 Iustin Pop

1382 490acd18 Iustin Pop
    """
1383 b459a848 Andrea Spadaccini
    # pylint: disable=E0203
1384 490acd18 Iustin Pop
    # because these are "defined" via slots, not manually
1385 490acd18 Iustin Pop
    if self.master_capable is None:
1386 490acd18 Iustin Pop
      self.master_capable = True
1387 490acd18 Iustin Pop
1388 490acd18 Iustin Pop
    if self.vm_capable is None:
1389 490acd18 Iustin Pop
      self.vm_capable = True
1390 490acd18 Iustin Pop
1391 095e71aa René Nussbaumer
    if self.ndparams is None:
1392 095e71aa René Nussbaumer
      self.ndparams = {}
1393 250a9404 Bernardo Dal Seno
    # And remove any global parameter
1394 250a9404 Bernardo Dal Seno
    for key in constants.NDC_GLOBALS:
1395 250a9404 Bernardo Dal Seno
      if key in self.ndparams:
1396 250a9404 Bernardo Dal Seno
        logging.warning("Ignoring %s node parameter for node %s",
1397 250a9404 Bernardo Dal Seno
                        key, self.name)
1398 250a9404 Bernardo Dal Seno
        del self.ndparams[key]
1399 095e71aa René Nussbaumer
1400 25124d4a René Nussbaumer
    if self.powered is None:
1401 25124d4a René Nussbaumer
      self.powered = True
1402 25124d4a René Nussbaumer
1403 5f06ce5e Michael Hanselmann
  def ToDict(self):
1404 5f06ce5e Michael Hanselmann
    """Custom function for serializing.
1405 5f06ce5e Michael Hanselmann

1406 5f06ce5e Michael Hanselmann
    """
1407 5f06ce5e Michael Hanselmann
    data = super(Node, self).ToDict()
1408 5f06ce5e Michael Hanselmann
1409 5f06ce5e Michael Hanselmann
    hv_state = data.get("hv_state", None)
1410 5f06ce5e Michael Hanselmann
    if hv_state is not None:
1411 fe502d25 Iustin Pop
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1412 5f06ce5e Michael Hanselmann
1413 5f06ce5e Michael Hanselmann
    disk_state = data.get("disk_state", None)
1414 5f06ce5e Michael Hanselmann
    if disk_state is not None:
1415 5f06ce5e Michael Hanselmann
      data["disk_state"] = \
1416 fe502d25 Iustin Pop
        dict((key, outils.ContainerToDicts(value))
1417 5f06ce5e Michael Hanselmann
             for (key, value) in disk_state.items())
1418 5f06ce5e Michael Hanselmann
1419 5f06ce5e Michael Hanselmann
    return data
1420 5f06ce5e Michael Hanselmann
1421 5f06ce5e Michael Hanselmann
  @classmethod
1422 5f06ce5e Michael Hanselmann
  def FromDict(cls, val):
1423 5f06ce5e Michael Hanselmann
    """Custom function for deserializing.
1424 5f06ce5e Michael Hanselmann

1425 5f06ce5e Michael Hanselmann
    """
1426 5f06ce5e Michael Hanselmann
    obj = super(Node, cls).FromDict(val)
1427 5f06ce5e Michael Hanselmann
1428 5f06ce5e Michael Hanselmann
    if obj.hv_state is not None:
1429 473ab806 Michael Hanselmann
      obj.hv_state = \
1430 fe502d25 Iustin Pop
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1431 5f06ce5e Michael Hanselmann
1432 5f06ce5e Michael Hanselmann
    if obj.disk_state is not None:
1433 5f06ce5e Michael Hanselmann
      obj.disk_state = \
1434 fe502d25 Iustin Pop
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1435 5f06ce5e Michael Hanselmann
             for (key, value) in obj.disk_state.items())
1436 5f06ce5e Michael Hanselmann
1437 5f06ce5e Michael Hanselmann
    return obj
1438 5f06ce5e Michael Hanselmann
1439 a8083063 Iustin Pop
1440 1ffd2673 Michael Hanselmann
class NodeGroup(TaggableObject):
1441 24a3707f Guido Trotter
  """Config object representing a node group."""
1442 24a3707f Guido Trotter
  __slots__ = [
1443 24a3707f Guido Trotter
    "name",
1444 24a3707f Guido Trotter
    "members",
1445 095e71aa René Nussbaumer
    "ndparams",
1446 bc5d0215 Andrea Spadaccini
    "diskparams",
1447 81e3ab4f Agata Murawska
    "ipolicy",
1448 e11a1b77 Adeodato Simo
    "serial_no",
1449 a8282327 René Nussbaumer
    "hv_state_static",
1450 a8282327 René Nussbaumer
    "disk_state_static",
1451 90e99856 Adeodato Simo
    "alloc_policy",
1452 eaa4c57c Dimitris Aragiorgis
    "networks",
1453 24a3707f Guido Trotter
    ] + _TIMESTAMPS + _UUID
1454 24a3707f Guido Trotter
1455 24a3707f Guido Trotter
  def ToDict(self):
1456 24a3707f Guido Trotter
    """Custom function for nodegroup.
1457 24a3707f Guido Trotter

1458 c60abd62 Guido Trotter
    This discards the members object, which gets recalculated and is only kept
1459 c60abd62 Guido Trotter
    in memory.
1460 24a3707f Guido Trotter

1461 24a3707f Guido Trotter
    """
1462 24a3707f Guido Trotter
    mydict = super(NodeGroup, self).ToDict()
1463 24a3707f Guido Trotter
    del mydict["members"]
1464 24a3707f Guido Trotter
    return mydict
1465 24a3707f Guido Trotter
1466 24a3707f Guido Trotter
  @classmethod
1467 24a3707f Guido Trotter
  def FromDict(cls, val):
1468 24a3707f Guido Trotter
    """Custom function for nodegroup.
1469 24a3707f Guido Trotter

1470 24a3707f Guido Trotter
    The members slot is initialized to an empty list, upon deserialization.
1471 24a3707f Guido Trotter

1472 24a3707f Guido Trotter
    """
1473 24a3707f Guido Trotter
    obj = super(NodeGroup, cls).FromDict(val)
1474 24a3707f Guido Trotter
    obj.members = []
1475 24a3707f Guido Trotter
    return obj
1476 24a3707f Guido Trotter
1477 095e71aa René Nussbaumer
  def UpgradeConfig(self):
1478 095e71aa René Nussbaumer
    """Fill defaults for missing configuration values.
1479 095e71aa René Nussbaumer

1480 095e71aa René Nussbaumer
    """
1481 095e71aa René Nussbaumer
    if self.ndparams is None:
1482 095e71aa René Nussbaumer
      self.ndparams = {}
1483 095e71aa René Nussbaumer
1484 e11a1b77 Adeodato Simo
    if self.serial_no is None:
1485 e11a1b77 Adeodato Simo
      self.serial_no = 1
1486 e11a1b77 Adeodato Simo
1487 90e99856 Adeodato Simo
    if self.alloc_policy is None:
1488 90e99856 Adeodato Simo
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1489 90e99856 Adeodato Simo
1490 4b97458c Iustin Pop
    # We only update mtime, and not ctime, since we would not be able
1491 4b97458c Iustin Pop
    # to provide a correct value for creation time.
1492 e11a1b77 Adeodato Simo
    if self.mtime is None:
1493 e11a1b77 Adeodato Simo
      self.mtime = time.time()
1494 e11a1b77 Adeodato Simo
1495 7228ca91 René Nussbaumer
    if self.diskparams is None:
1496 7228ca91 René Nussbaumer
      self.diskparams = {}
1497 81e3ab4f Agata Murawska
    if self.ipolicy is None:
1498 81e3ab4f Agata Murawska
      self.ipolicy = MakeEmptyIPolicy()
1499 bc5d0215 Andrea Spadaccini
1500 eaa4c57c Dimitris Aragiorgis
    if self.networks is None:
1501 eaa4c57c Dimitris Aragiorgis
      self.networks = {}
1502 eaa4c57c Dimitris Aragiorgis
1503 095e71aa René Nussbaumer
  def FillND(self, node):
1504 ce523de1 Michael Hanselmann
    """Return filled out ndparams for L{objects.Node}
1505 095e71aa René Nussbaumer

1506 095e71aa René Nussbaumer
    @type node: L{objects.Node}
1507 095e71aa René Nussbaumer
    @param node: A Node object to fill
1508 095e71aa René Nussbaumer
    @return a copy of the node's ndparams with defaults filled
1509 095e71aa René Nussbaumer

1510 095e71aa René Nussbaumer
    """
1511 095e71aa René Nussbaumer
    return self.SimpleFillND(node.ndparams)
1512 095e71aa René Nussbaumer
1513 095e71aa René Nussbaumer
  def SimpleFillND(self, ndparams):
1514 095e71aa René Nussbaumer
    """Fill a given ndparams dict with defaults.
1515 095e71aa René Nussbaumer

1516 095e71aa René Nussbaumer
    @type ndparams: dict
1517 095e71aa René Nussbaumer
    @param ndparams: the dict to fill
1518 095e71aa René Nussbaumer
    @rtype: dict
1519 095e71aa René Nussbaumer
    @return: a copy of the passed in ndparams with missing keys filled
1520 e6e88de6 Adeodato Simo
        from the node group defaults
1521 095e71aa René Nussbaumer

1522 095e71aa René Nussbaumer
    """
1523 095e71aa René Nussbaumer
    return FillDict(self.ndparams, ndparams)
1524 095e71aa René Nussbaumer
1525 24a3707f Guido Trotter
1526 ec29fe40 Iustin Pop
class Cluster(TaggableObject):
1527 a8083063 Iustin Pop
  """Config object representing the cluster."""
1528 154b9580 Balazs Lecz
  __slots__ = [
1529 a8083063 Iustin Pop
    "serial_no",
1530 a8083063 Iustin Pop
    "rsahostkeypub",
1531 a9542a4f Thomas Thrainer
    "dsahostkeypub",
1532 a8083063 Iustin Pop
    "highest_used_port",
1533 b2fddf63 Iustin Pop
    "tcpudp_port_pool",
1534 a8083063 Iustin Pop
    "mac_prefix",
1535 a8083063 Iustin Pop
    "volume_group_name",
1536 999b183c Iustin Pop
    "reserved_lvs",
1537 9e33896b Luca Bigliardi
    "drbd_usermode_helper",
1538 a8083063 Iustin Pop
    "default_bridge",
1539 02691904 Alexander Schreiber
    "default_hypervisor",
1540 f6bd6e98 Michael Hanselmann
    "master_node",
1541 f6bd6e98 Michael Hanselmann
    "master_ip",
1542 f6bd6e98 Michael Hanselmann
    "master_netdev",
1543 5a8648eb Andrea Spadaccini
    "master_netmask",
1544 33be7576 Andrea Spadaccini
    "use_external_mip_script",
1545 f6bd6e98 Michael Hanselmann
    "cluster_name",
1546 f6bd6e98 Michael Hanselmann
    "file_storage_dir",
1547 4b97f902 Apollon Oikonomopoulos
    "shared_file_storage_dir",
1548 e69d05fd Iustin Pop
    "enabled_hypervisors",
1549 5bf7b5cf Iustin Pop
    "hvparams",
1550 918eb80b Agata Murawska
    "ipolicy",
1551 17463d22 René Nussbaumer
    "os_hvp",
1552 5bf7b5cf Iustin Pop
    "beparams",
1553 1bdcbbab Iustin Pop
    "osparams",
1554 c8fcde47 Guido Trotter
    "nicparams",
1555 095e71aa René Nussbaumer
    "ndparams",
1556 bc5d0215 Andrea Spadaccini
    "diskparams",
1557 4b7735f9 Iustin Pop
    "candidate_pool_size",
1558 b86a6bcd Guido Trotter
    "modify_etc_hosts",
1559 b989b9d9 Ken Wehr
    "modify_ssh_setup",
1560 3953242f Iustin Pop
    "maintain_node_health",
1561 4437d889 Balazs Lecz
    "uid_pool",
1562 bf4af505 Apollon Oikonomopoulos
    "default_iallocator",
1563 87b2cd45 Iustin Pop
    "hidden_os",
1564 87b2cd45 Iustin Pop
    "blacklisted_os",
1565 2f20d07b Manuel Franceschini
    "primary_ip_family",
1566 3d914585 René Nussbaumer
    "prealloc_wipe_disks",
1567 2da9f556 René Nussbaumer
    "hv_state_static",
1568 2da9f556 René Nussbaumer
    "disk_state_static",
1569 1b02d7ef Helga Velroyen
    "enabled_disk_templates",
1570 e1dcc53a Iustin Pop
    ] + _TIMESTAMPS + _UUID
1571 a8083063 Iustin Pop
1572 b86a6bcd Guido Trotter
  def UpgradeConfig(self):
1573 b86a6bcd Guido Trotter
    """Fill defaults for missing configuration values.
1574 b86a6bcd Guido Trotter

1575 b86a6bcd Guido Trotter
    """
1576 b459a848 Andrea Spadaccini
    # pylint: disable=E0203
1577 fe267188 Iustin Pop
    # because these are "defined" via slots, not manually
1578 c1b42c18 Guido Trotter
    if self.hvparams is None:
1579 c1b42c18 Guido Trotter
      self.hvparams = constants.HVC_DEFAULTS
1580 c1b42c18 Guido Trotter
    else:
1581 c1b42c18 Guido Trotter
      for hypervisor in self.hvparams:
1582 abe609b2 Guido Trotter
        self.hvparams[hypervisor] = FillDict(
1583 c1b42c18 Guido Trotter
            constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1584 c1b42c18 Guido Trotter
1585 17463d22 René Nussbaumer
    if self.os_hvp is None:
1586 17463d22 René Nussbaumer
      self.os_hvp = {}
1587 17463d22 René Nussbaumer
1588 1bdcbbab Iustin Pop
    # osparams added before 2.2
1589 1bdcbbab Iustin Pop
    if self.osparams is None:
1590 1bdcbbab Iustin Pop
      self.osparams = {}
1591 1bdcbbab Iustin Pop
1592 2a27dac3 Iustin Pop
    self.ndparams = UpgradeNDParams(self.ndparams)
1593 095e71aa René Nussbaumer
1594 6e34b628 Guido Trotter
    self.beparams = UpgradeGroupedParams(self.beparams,
1595 6e34b628 Guido Trotter
                                         constants.BEC_DEFAULTS)
1596 8c72ab2b Guido Trotter
    for beparams_group in self.beparams:
1597 8c72ab2b Guido Trotter
      UpgradeBeParams(self.beparams[beparams_group])
1598 8c72ab2b Guido Trotter
1599 c8fcde47 Guido Trotter
    migrate_default_bridge = not self.nicparams
1600 c8fcde47 Guido Trotter
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1601 c8fcde47 Guido Trotter
                                          constants.NICC_DEFAULTS)
1602 c8fcde47 Guido Trotter
    if migrate_default_bridge:
1603 c8fcde47 Guido Trotter
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1604 c8fcde47 Guido Trotter
        self.default_bridge
1605 c1b42c18 Guido Trotter
1606 b86a6bcd Guido Trotter
    if self.modify_etc_hosts is None:
1607 b86a6bcd Guido Trotter
      self.modify_etc_hosts = True
1608 b86a6bcd Guido Trotter
1609 b989b9d9 Ken Wehr
    if self.modify_ssh_setup is None:
1610 b989b9d9 Ken Wehr
      self.modify_ssh_setup = True
1611 b989b9d9 Ken Wehr
1612 73f1d185 Stephen Shirley
    # default_bridge is no longer used in 2.1. The slot is left there to
1613 90d118fd Guido Trotter
    # support auto-upgrading. It can be removed once we decide to deprecate
1614 90d118fd Guido Trotter
    # upgrading straight from 2.0.
1615 9b31ca85 Guido Trotter
    if self.default_bridge is not None:
1616 9b31ca85 Guido Trotter
      self.default_bridge = None
1617 9b31ca85 Guido Trotter
1618 90d118fd Guido Trotter
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1619 90d118fd Guido Trotter
    # code can be removed once upgrading straight from 2.0 is deprecated.
1620 066f465d Guido Trotter
    if self.default_hypervisor is not None:
1621 016d04b3 Michael Hanselmann
      self.enabled_hypervisors = ([self.default_hypervisor] +
1622 5ae4945a Iustin Pop
                                  [hvname for hvname in self.enabled_hypervisors
1623 5ae4945a Iustin Pop
                                   if hvname != self.default_hypervisor])
1624 066f465d Guido Trotter
      self.default_hypervisor = None
1625 066f465d Guido Trotter
1626 3953242f Iustin Pop
    # maintain_node_health added after 2.1.1
1627 3953242f Iustin Pop
    if self.maintain_node_health is None:
1628 3953242f Iustin Pop
      self.maintain_node_health = False
1629 3953242f Iustin Pop
1630 4437d889 Balazs Lecz
    if self.uid_pool is None:
1631 4437d889 Balazs Lecz
      self.uid_pool = []
1632 4437d889 Balazs Lecz
1633 bf4af505 Apollon Oikonomopoulos
    if self.default_iallocator is None:
1634 bf4af505 Apollon Oikonomopoulos
      self.default_iallocator = ""
1635 bf4af505 Apollon Oikonomopoulos
1636 999b183c Iustin Pop
    # reserved_lvs added before 2.2
1637 999b183c Iustin Pop
    if self.reserved_lvs is None:
1638 999b183c Iustin Pop
      self.reserved_lvs = []
1639 999b183c Iustin Pop
1640 546b1111 Iustin Pop
    # hidden and blacklisted operating systems added before 2.2.1
1641 87b2cd45 Iustin Pop
    if self.hidden_os is None:
1642 87b2cd45 Iustin Pop
      self.hidden_os = []
1643 546b1111 Iustin Pop
1644 87b2cd45 Iustin Pop
    if self.blacklisted_os is None:
1645 87b2cd45 Iustin Pop
      self.blacklisted_os = []
1646 546b1111 Iustin Pop
1647 f4c9af7a Guido Trotter
    # primary_ip_family added before 2.3
1648 f4c9af7a Guido Trotter
    if self.primary_ip_family is None:
1649 f4c9af7a Guido Trotter
      self.primary_ip_family = AF_INET
1650 f4c9af7a Guido Trotter
1651 0007f3ab Andrea Spadaccini
    if self.master_netmask is None:
1652 0007f3ab Andrea Spadaccini
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1653 0007f3ab Andrea Spadaccini
      self.master_netmask = ipcls.iplen
1654 0007f3ab Andrea Spadaccini
1655 3d914585 René Nussbaumer
    if self.prealloc_wipe_disks is None:
1656 3d914585 René Nussbaumer
      self.prealloc_wipe_disks = False
1657 3d914585 René Nussbaumer
1658 e8f472d1 Iustin Pop
    # shared_file_storage_dir added before 2.5
1659 e8f472d1 Iustin Pop
    if self.shared_file_storage_dir is None:
1660 e8f472d1 Iustin Pop
      self.shared_file_storage_dir = ""
1661 e8f472d1 Iustin Pop
1662 33be7576 Andrea Spadaccini
    if self.use_external_mip_script is None:
1663 33be7576 Andrea Spadaccini
      self.use_external_mip_script = False
1664 33be7576 Andrea Spadaccini
1665 99ccf8b9 René Nussbaumer
    if self.diskparams:
1666 99ccf8b9 René Nussbaumer
      self.diskparams = UpgradeDiskParams(self.diskparams)
1667 99ccf8b9 René Nussbaumer
    else:
1668 99ccf8b9 René Nussbaumer
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1669 bc5d0215 Andrea Spadaccini
1670 918eb80b Agata Murawska
    # instance policy added before 2.6
1671 918eb80b Agata Murawska
    if self.ipolicy is None:
1672 2cc673a3 Iustin Pop
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1673 38a6e2e1 Iustin Pop
    else:
1674 38a6e2e1 Iustin Pop
      # we can either make sure to upgrade the ipolicy always, or only
1675 38a6e2e1 Iustin Pop
      # do it in some corner cases (e.g. missing keys); note that this
1676 38a6e2e1 Iustin Pop
      # will break any removal of keys from the ipolicy dict
1677 4f7e5a1d Bernardo Dal Seno
      wrongkeys = frozenset(self.ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1678 4f7e5a1d Bernardo Dal Seno
      if wrongkeys:
1679 4f7e5a1d Bernardo Dal Seno
        # These keys would be silently removed by FillIPolicy()
1680 7fb852bd Michele Tartara
        msg = ("Cluster instance policy contains spurious keys: %s" %
1681 4f7e5a1d Bernardo Dal Seno
               utils.CommaJoin(wrongkeys))
1682 4f7e5a1d Bernardo Dal Seno
        raise errors.ConfigurationError(msg)
1683 38a6e2e1 Iustin Pop
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1684 918eb80b Agata Murawska
1685 0fbedb7a Michael Hanselmann
  @property
1686 0fbedb7a Michael Hanselmann
  def primary_hypervisor(self):
1687 0fbedb7a Michael Hanselmann
    """The first hypervisor is the primary.
1688 0fbedb7a Michael Hanselmann

1689 0fbedb7a Michael Hanselmann
    Useful, for example, for L{Node}'s hv/disk state.
1690 0fbedb7a Michael Hanselmann

1691 0fbedb7a Michael Hanselmann
    """
1692 0fbedb7a Michael Hanselmann
    return self.enabled_hypervisors[0]
1693 0fbedb7a Michael Hanselmann
1694 319856a9 Michael Hanselmann
  def ToDict(self):
1695 319856a9 Michael Hanselmann
    """Custom function for cluster.
1696 319856a9 Michael Hanselmann

1697 319856a9 Michael Hanselmann
    """
1698 b60ae2ca Iustin Pop
    mydict = super(Cluster, self).ToDict()
1699 4d36fbf4 Michael Hanselmann
1700 4d36fbf4 Michael Hanselmann
    if self.tcpudp_port_pool is None:
1701 4d36fbf4 Michael Hanselmann
      tcpudp_port_pool = []
1702 4d36fbf4 Michael Hanselmann
    else:
1703 4d36fbf4 Michael Hanselmann
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1704 4d36fbf4 Michael Hanselmann
1705 4d36fbf4 Michael Hanselmann
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1706 4d36fbf4 Michael Hanselmann
1707 319856a9 Michael Hanselmann
    return mydict
1708 319856a9 Michael Hanselmann
1709 319856a9 Michael Hanselmann
  @classmethod
1710 319856a9 Michael Hanselmann
  def FromDict(cls, val):
1711 319856a9 Michael Hanselmann
    """Custom function for cluster.
1712 319856a9 Michael Hanselmann

1713 319856a9 Michael Hanselmann
    """
1714 b60ae2ca Iustin Pop
    obj = super(Cluster, cls).FromDict(val)
1715 4d36fbf4 Michael Hanselmann
1716 4d36fbf4 Michael Hanselmann
    if obj.tcpudp_port_pool is None:
1717 4d36fbf4 Michael Hanselmann
      obj.tcpudp_port_pool = set()
1718 4d36fbf4 Michael Hanselmann
    elif not isinstance(obj.tcpudp_port_pool, set):
1719 319856a9 Michael Hanselmann
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1720 4d36fbf4 Michael Hanselmann
1721 319856a9 Michael Hanselmann
    return obj
1722 319856a9 Michael Hanselmann
1723 8a147bba René Nussbaumer
  def SimpleFillDP(self, diskparams):
1724 8a147bba René Nussbaumer
    """Fill a given diskparams dict with cluster defaults.
1725 8a147bba René Nussbaumer

1726 8a147bba René Nussbaumer
    @param diskparams: The diskparams
1727 8a147bba René Nussbaumer
    @return: The defaults dict
1728 8a147bba René Nussbaumer

1729 8a147bba René Nussbaumer
    """
1730 8a147bba René Nussbaumer
    return FillDiskParams(self.diskparams, diskparams)
1731 8a147bba René Nussbaumer
1732 d63479b5 Iustin Pop
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1733 d63479b5 Iustin Pop
    """Get the default hypervisor parameters for the cluster.
1734 d63479b5 Iustin Pop

1735 d63479b5 Iustin Pop
    @param hypervisor: the hypervisor name
1736 d63479b5 Iustin Pop
    @param os_name: if specified, we'll also update the defaults for this OS
1737 d63479b5 Iustin Pop
    @param skip_keys: if passed, list of keys not to use
1738 d63479b5 Iustin Pop
    @return: the defaults dict
1739 d63479b5 Iustin Pop

1740 d63479b5 Iustin Pop
    """
1741 d63479b5 Iustin Pop
    if skip_keys is None:
1742 d63479b5 Iustin Pop
      skip_keys = []
1743 d63479b5 Iustin Pop
1744 d63479b5 Iustin Pop
    fill_stack = [self.hvparams.get(hypervisor, {})]
1745 d63479b5 Iustin Pop
    if os_name is not None:
1746 d63479b5 Iustin Pop
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1747 d63479b5 Iustin Pop
      fill_stack.append(os_hvp)
1748 d63479b5 Iustin Pop
1749 d63479b5 Iustin Pop
    ret_dict = {}
1750 d63479b5 Iustin Pop
    for o_dict in fill_stack:
1751 d63479b5 Iustin Pop
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1752 d63479b5 Iustin Pop
1753 d63479b5 Iustin Pop
    return ret_dict
1754 d63479b5 Iustin Pop
1755 73e0328b Iustin Pop
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1756 73e0328b Iustin Pop
    """Fill a given hvparams dict with cluster defaults.
1757 73e0328b Iustin Pop

1758 73e0328b Iustin Pop
    @type hv_name: string
1759 73e0328b Iustin Pop
    @param hv_name: the hypervisor to use
1760 73e0328b Iustin Pop
    @type os_name: string
1761 73e0328b Iustin Pop
    @param os_name: the OS to use for overriding the hypervisor defaults
1762 73e0328b Iustin Pop
    @type skip_globals: boolean
1763 73e0328b Iustin Pop
    @param skip_globals: if True, the global hypervisor parameters will
1764 73e0328b Iustin Pop
        not be filled
1765 73e0328b Iustin Pop
    @rtype: dict
1766 73e0328b Iustin Pop
    @return: a copy of the given hvparams with missing keys filled from
1767 73e0328b Iustin Pop
        the cluster defaults
1768 73e0328b Iustin Pop

1769 73e0328b Iustin Pop
    """
1770 73e0328b Iustin Pop
    if skip_globals:
1771 73e0328b Iustin Pop
      skip_keys = constants.HVC_GLOBALS
1772 73e0328b Iustin Pop
    else:
1773 73e0328b Iustin Pop
      skip_keys = []
1774 73e0328b Iustin Pop
1775 73e0328b Iustin Pop
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1776 73e0328b Iustin Pop
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1777 d63479b5 Iustin Pop
1778 7736a5f2 Iustin Pop
  def FillHV(self, instance, skip_globals=False):
1779 73e0328b Iustin Pop
    """Fill an instance's hvparams dict with cluster defaults.
1780 5bf7b5cf Iustin Pop

1781 a2a24f4c Guido Trotter
    @type instance: L{objects.Instance}
1782 5bf7b5cf Iustin Pop
    @param instance: the instance parameter to fill
1783 7736a5f2 Iustin Pop
    @type skip_globals: boolean
1784 7736a5f2 Iustin Pop
    @param skip_globals: if True, the global hypervisor parameters will
1785 7736a5f2 Iustin Pop
        not be filled
1786 5bf7b5cf Iustin Pop
    @rtype: dict
1787 5bf7b5cf Iustin Pop
    @return: a copy of the instance's hvparams with missing keys filled from
1788 5bf7b5cf Iustin Pop
        the cluster defaults
1789 5bf7b5cf Iustin Pop

1790 5bf7b5cf Iustin Pop
    """
1791 73e0328b Iustin Pop
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1792 73e0328b Iustin Pop
                             instance.hvparams, skip_globals)
1793 17463d22 René Nussbaumer
1794 73e0328b Iustin Pop
  def SimpleFillBE(self, beparams):
1795 73e0328b Iustin Pop
    """Fill a given beparams dict with cluster defaults.
1796 73e0328b Iustin Pop

1797 06596a60 Guido Trotter
    @type beparams: dict
1798 06596a60 Guido Trotter
    @param beparams: the dict to fill
1799 73e0328b Iustin Pop
    @rtype: dict
1800 73e0328b Iustin Pop
    @return: a copy of the passed in beparams with missing keys filled
1801 73e0328b Iustin Pop
        from the cluster defaults
1802 73e0328b Iustin Pop

1803 73e0328b Iustin Pop
    """
1804 73e0328b Iustin Pop
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1805 5bf7b5cf Iustin Pop
1806 5bf7b5cf Iustin Pop
  def FillBE(self, instance):
1807 73e0328b Iustin Pop
    """Fill an instance's beparams dict with cluster defaults.
1808 5bf7b5cf Iustin Pop

1809 a2a24f4c Guido Trotter
    @type instance: L{objects.Instance}
1810 5bf7b5cf Iustin Pop
    @param instance: the instance parameter to fill
1811 5bf7b5cf Iustin Pop
    @rtype: dict
1812 5bf7b5cf Iustin Pop
    @return: a copy of the instance's beparams with missing keys filled from
1813 5bf7b5cf Iustin Pop
        the cluster defaults
1814 5bf7b5cf Iustin Pop

1815 5bf7b5cf Iustin Pop
    """
1816 73e0328b Iustin Pop
    return self.SimpleFillBE(instance.beparams)
1817 73e0328b Iustin Pop
1818 73e0328b Iustin Pop
  def SimpleFillNIC(self, nicparams):
1819 73e0328b Iustin Pop
    """Fill a given nicparams dict with cluster defaults.
1820 73e0328b Iustin Pop

1821 06596a60 Guido Trotter
    @type nicparams: dict
1822 06596a60 Guido Trotter
    @param nicparams: the dict to fill
1823 73e0328b Iustin Pop
    @rtype: dict
1824 73e0328b Iustin Pop
    @return: a copy of the passed in nicparams with missing keys filled
1825 73e0328b Iustin Pop
        from the cluster defaults
1826 73e0328b Iustin Pop

1827 73e0328b Iustin Pop
    """
1828 73e0328b Iustin Pop
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1829 5bf7b5cf Iustin Pop
1830 1bdcbbab Iustin Pop
  def SimpleFillOS(self, os_name, os_params):
1831 1bdcbbab Iustin Pop
    """Fill an instance's osparams dict with cluster defaults.
1832 1bdcbbab Iustin Pop

1833 1bdcbbab Iustin Pop
    @type os_name: string
1834 1bdcbbab Iustin Pop
    @param os_name: the OS name to use
1835 1bdcbbab Iustin Pop
    @type os_params: dict
1836 1bdcbbab Iustin Pop
    @param os_params: the dict to fill with default values
1837 1bdcbbab Iustin Pop
    @rtype: dict
1838 1bdcbbab Iustin Pop
    @return: a copy of the instance's osparams with missing keys filled from
1839 1bdcbbab Iustin Pop
        the cluster defaults
1840 1bdcbbab Iustin Pop

1841 1bdcbbab Iustin Pop
    """
1842 1bdcbbab Iustin Pop
    name_only = os_name.split("+", 1)[0]
1843 1bdcbbab Iustin Pop
    # base OS
1844 1bdcbbab Iustin Pop
    result = self.osparams.get(name_only, {})
1845 1bdcbbab Iustin Pop
    # OS with variant
1846 1bdcbbab Iustin Pop
    result = FillDict(result, self.osparams.get(os_name, {}))
1847 1bdcbbab Iustin Pop
    # specified params
1848 1bdcbbab Iustin Pop
    return FillDict(result, os_params)
1849 1bdcbbab Iustin Pop
1850 2da9f556 René Nussbaumer
  @staticmethod
1851 2da9f556 René Nussbaumer
  def SimpleFillHvState(hv_state):
1852 2da9f556 René Nussbaumer
    """Fill an hv_state sub dict with cluster defaults.
1853 2da9f556 René Nussbaumer

1854 2da9f556 René Nussbaumer
    """
1855 2da9f556 René Nussbaumer
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1856 2da9f556 René Nussbaumer
1857 2da9f556 René Nussbaumer
  @staticmethod
1858 2da9f556 René Nussbaumer
  def SimpleFillDiskState(disk_state):
1859 2da9f556 René Nussbaumer
    """Fill an disk_state sub dict with cluster defaults.
1860 2da9f556 René Nussbaumer

1861 2da9f556 René Nussbaumer
    """
1862 2da9f556 René Nussbaumer
    return FillDict(constants.DS_DEFAULTS, disk_state)
1863 2da9f556 René Nussbaumer
1864 095e71aa René Nussbaumer
  def FillND(self, node, nodegroup):
1865 ce523de1 Michael Hanselmann
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1866 095e71aa René Nussbaumer

1867 095e71aa René Nussbaumer
    @type node: L{objects.Node}
1868 095e71aa René Nussbaumer
    @param node: A Node object to fill
1869 095e71aa René Nussbaumer
    @type nodegroup: L{objects.NodeGroup}
1870 095e71aa René Nussbaumer
    @param nodegroup: A Node object to fill
1871 095e71aa René Nussbaumer
    @return a copy of the node's ndparams with defaults filled
1872 095e71aa René Nussbaumer

1873 095e71aa René Nussbaumer
    """
1874 095e71aa René Nussbaumer
    return self.SimpleFillND(nodegroup.FillND(node))
1875 095e71aa René Nussbaumer
1876 095e71aa René Nussbaumer
  def SimpleFillND(self, ndparams):
1877 095e71aa René Nussbaumer
    """Fill a given ndparams dict with defaults.
1878 095e71aa René Nussbaumer

1879 095e71aa René Nussbaumer
    @type ndparams: dict
1880 095e71aa René Nussbaumer
    @param ndparams: the dict to fill
1881 095e71aa René Nussbaumer
    @rtype: dict
1882 095e71aa René Nussbaumer
    @return: a copy of the passed in ndparams with missing keys filled
1883 095e71aa René Nussbaumer
        from the cluster defaults
1884 095e71aa René Nussbaumer

1885 095e71aa René Nussbaumer
    """
1886 095e71aa René Nussbaumer
    return FillDict(self.ndparams, ndparams)
1887 095e71aa René Nussbaumer
1888 918eb80b Agata Murawska
  def SimpleFillIPolicy(self, ipolicy):
1889 918eb80b Agata Murawska
    """ Fill instance policy dict with defaults.
1890 918eb80b Agata Murawska

1891 918eb80b Agata Murawska
    @type ipolicy: dict
1892 918eb80b Agata Murawska
    @param ipolicy: the dict to fill
1893 918eb80b Agata Murawska
    @rtype: dict
1894 918eb80b Agata Murawska
    @return: a copy of passed ipolicy with missing keys filled from
1895 918eb80b Agata Murawska
      the cluster defaults
1896 918eb80b Agata Murawska

1897 918eb80b Agata Murawska
    """
1898 2cc673a3 Iustin Pop
    return FillIPolicy(self.ipolicy, ipolicy)
1899 918eb80b Agata Murawska
1900 5c947f38 Iustin Pop
1901 96acbc09 Michael Hanselmann
class BlockDevStatus(ConfigObject):
1902 96acbc09 Michael Hanselmann
  """Config object representing the status of a block device."""
1903 96acbc09 Michael Hanselmann
  __slots__ = [
1904 96acbc09 Michael Hanselmann
    "dev_path",
1905 96acbc09 Michael Hanselmann
    "major",
1906 96acbc09 Michael Hanselmann
    "minor",
1907 96acbc09 Michael Hanselmann
    "sync_percent",
1908 96acbc09 Michael Hanselmann
    "estimated_time",
1909 96acbc09 Michael Hanselmann
    "is_degraded",
1910 f208978a Michael Hanselmann
    "ldisk_status",
1911 96acbc09 Michael Hanselmann
    ]
1912 96acbc09 Michael Hanselmann
1913 96acbc09 Michael Hanselmann
1914 2d76b580 Michael Hanselmann
class ImportExportStatus(ConfigObject):
1915 2d76b580 Michael Hanselmann
  """Config object representing the status of an import or export."""
1916 2d76b580 Michael Hanselmann
  __slots__ = [
1917 2d76b580 Michael Hanselmann
    "recent_output",
1918 2d76b580 Michael Hanselmann
    "listen_port",
1919 2d76b580 Michael Hanselmann
    "connected",
1920 c08d76f5 Michael Hanselmann
    "progress_mbytes",
1921 c08d76f5 Michael Hanselmann
    "progress_throughput",
1922 c08d76f5 Michael Hanselmann
    "progress_eta",
1923 c08d76f5 Michael Hanselmann
    "progress_percent",
1924 2d76b580 Michael Hanselmann
    "exit_status",
1925 2d76b580 Michael Hanselmann
    "error_message",
1926 2d76b580 Michael Hanselmann
    ] + _TIMESTAMPS
1927 2d76b580 Michael Hanselmann
1928 2d76b580 Michael Hanselmann
1929 eb630f50 Michael Hanselmann
class ImportExportOptions(ConfigObject):
1930 eb630f50 Michael Hanselmann
  """Options for import/export daemon
1931 eb630f50 Michael Hanselmann

1932 eb630f50 Michael Hanselmann
  @ivar key_name: X509 key name (None for cluster certificate)
1933 eb630f50 Michael Hanselmann
  @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1934 a5310c2a Michael Hanselmann
  @ivar compress: Compression method (one of L{constants.IEC_ALL})
1935 af1d39b1 Michael Hanselmann
  @ivar magic: Used to ensure the connection goes to the right disk
1936 855d2fc7 Michael Hanselmann
  @ivar ipv6: Whether to use IPv6
1937 4478301b Michael Hanselmann
  @ivar connect_timeout: Number of seconds for establishing connection
1938 eb630f50 Michael Hanselmann

1939 eb630f50 Michael Hanselmann
  """
1940 eb630f50 Michael Hanselmann
  __slots__ = [
1941 eb630f50 Michael Hanselmann
    "key_name",
1942 eb630f50 Michael Hanselmann
    "ca_pem",
1943 a5310c2a Michael Hanselmann
    "compress",
1944 af1d39b1 Michael Hanselmann
    "magic",
1945 855d2fc7 Michael Hanselmann
    "ipv6",
1946 4478301b Michael Hanselmann
    "connect_timeout",
1947 eb630f50 Michael Hanselmann
    ]
1948 eb630f50 Michael Hanselmann
1949 eb630f50 Michael Hanselmann
1950 18d750b9 Guido Trotter
class ConfdRequest(ConfigObject):
1951 18d750b9 Guido Trotter
  """Object holding a confd request.
1952 18d750b9 Guido Trotter

1953 18d750b9 Guido Trotter
  @ivar protocol: confd protocol version
1954 18d750b9 Guido Trotter
  @ivar type: confd query type
1955 18d750b9 Guido Trotter
  @ivar query: query request
1956 18d750b9 Guido Trotter
  @ivar rsalt: requested reply salt
1957 18d750b9 Guido Trotter

1958 18d750b9 Guido Trotter
  """
1959 18d750b9 Guido Trotter
  __slots__ = [
1960 18d750b9 Guido Trotter
    "protocol",
1961 18d750b9 Guido Trotter
    "type",
1962 18d750b9 Guido Trotter
    "query",
1963 18d750b9 Guido Trotter
    "rsalt",
1964 18d750b9 Guido Trotter
    ]
1965 18d750b9 Guido Trotter
1966 18d750b9 Guido Trotter
1967 18d750b9 Guido Trotter
class ConfdReply(ConfigObject):
1968 18d750b9 Guido Trotter
  """Object holding a confd reply.
1969 18d750b9 Guido Trotter

1970 18d750b9 Guido Trotter
  @ivar protocol: confd protocol version
1971 18d750b9 Guido Trotter
  @ivar status: reply status code (ok, error)
1972 18d750b9 Guido Trotter
  @ivar answer: confd query reply
1973 18d750b9 Guido Trotter
  @ivar serial: configuration serial number
1974 18d750b9 Guido Trotter

1975 18d750b9 Guido Trotter
  """
1976 18d750b9 Guido Trotter
  __slots__ = [
1977 18d750b9 Guido Trotter
    "protocol",
1978 18d750b9 Guido Trotter
    "status",
1979 18d750b9 Guido Trotter
    "answer",
1980 18d750b9 Guido Trotter
    "serial",
1981 18d750b9 Guido Trotter
    ]
1982 18d750b9 Guido Trotter
1983 18d750b9 Guido Trotter
1984 707f23b5 Michael Hanselmann
class QueryFieldDefinition(ConfigObject):
1985 707f23b5 Michael Hanselmann
  """Object holding a query field definition.
1986 707f23b5 Michael Hanselmann

1987 24d6d3e2 Michael Hanselmann
  @ivar name: Field name
1988 707f23b5 Michael Hanselmann
  @ivar title: Human-readable title
1989 707f23b5 Michael Hanselmann
  @ivar kind: Field type
1990 1ae17369 Michael Hanselmann
  @ivar doc: Human-readable description
1991 707f23b5 Michael Hanselmann

1992 707f23b5 Michael Hanselmann
  """
1993 707f23b5 Michael Hanselmann
  __slots__ = [
1994 707f23b5 Michael Hanselmann
    "name",
1995 707f23b5 Michael Hanselmann
    "title",
1996 707f23b5 Michael Hanselmann
    "kind",
1997 1ae17369 Michael Hanselmann
    "doc",
1998 707f23b5 Michael Hanselmann
    ]
1999 707f23b5 Michael Hanselmann
2000 707f23b5 Michael Hanselmann
2001 0538c375 Michael Hanselmann
class _QueryResponseBase(ConfigObject):
2002 0538c375 Michael Hanselmann
  __slots__ = [
2003 0538c375 Michael Hanselmann
    "fields",
2004 0538c375 Michael Hanselmann
    ]
2005 0538c375 Michael Hanselmann
2006 0538c375 Michael Hanselmann
  def ToDict(self):
2007 0538c375 Michael Hanselmann
    """Custom function for serializing.
2008 0538c375 Michael Hanselmann

2009 0538c375 Michael Hanselmann
    """
2010 0538c375 Michael Hanselmann
    mydict = super(_QueryResponseBase, self).ToDict()
2011 fe502d25 Iustin Pop
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2012 0538c375 Michael Hanselmann
    return mydict
2013 0538c375 Michael Hanselmann
2014 0538c375 Michael Hanselmann
  @classmethod
2015 0538c375 Michael Hanselmann
  def FromDict(cls, val):
2016 0538c375 Michael Hanselmann
    """Custom function for de-serializing.
2017 0538c375 Michael Hanselmann

2018 0538c375 Michael Hanselmann
    """
2019 0538c375 Michael Hanselmann
    obj = super(_QueryResponseBase, cls).FromDict(val)
2020 473ab806 Michael Hanselmann
    obj.fields = \
2021 fe502d25 Iustin Pop
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2022 0538c375 Michael Hanselmann
    return obj
2023 0538c375 Michael Hanselmann
2024 0538c375 Michael Hanselmann
2025 0538c375 Michael Hanselmann
class QueryResponse(_QueryResponseBase):
2026 24d6d3e2 Michael Hanselmann
  """Object holding the response to a query.
2027 24d6d3e2 Michael Hanselmann

2028 24d6d3e2 Michael Hanselmann
  @ivar fields: List of L{QueryFieldDefinition} objects
2029 24d6d3e2 Michael Hanselmann
  @ivar data: Requested data
2030 24d6d3e2 Michael Hanselmann

2031 24d6d3e2 Michael Hanselmann
  """
2032 24d6d3e2 Michael Hanselmann
  __slots__ = [
2033 24d6d3e2 Michael Hanselmann
    "data",
2034 24d6d3e2 Michael Hanselmann
    ]
2035 24d6d3e2 Michael Hanselmann
2036 24d6d3e2 Michael Hanselmann
2037 24d6d3e2 Michael Hanselmann
class QueryFieldsRequest(ConfigObject):
2038 24d6d3e2 Michael Hanselmann
  """Object holding a request for querying available fields.
2039 24d6d3e2 Michael Hanselmann

2040 24d6d3e2 Michael Hanselmann
  """
2041 24d6d3e2 Michael Hanselmann
  __slots__ = [
2042 24d6d3e2 Michael Hanselmann
    "what",
2043 24d6d3e2 Michael Hanselmann
    "fields",
2044 24d6d3e2 Michael Hanselmann
    ]
2045 24d6d3e2 Michael Hanselmann
2046 24d6d3e2 Michael Hanselmann
2047 0538c375 Michael Hanselmann
class QueryFieldsResponse(_QueryResponseBase):
2048 24d6d3e2 Michael Hanselmann
  """Object holding the response to a query for fields.
2049 24d6d3e2 Michael Hanselmann

2050 24d6d3e2 Michael Hanselmann
  @ivar fields: List of L{QueryFieldDefinition} objects
2051 24d6d3e2 Michael Hanselmann

2052 24d6d3e2 Michael Hanselmann
  """
2053 5ae4945a Iustin Pop
  __slots__ = []
2054 24d6d3e2 Michael Hanselmann
2055 24d6d3e2 Michael Hanselmann
2056 6a1434d7 Andrea Spadaccini
class MigrationStatus(ConfigObject):
2057 6a1434d7 Andrea Spadaccini
  """Object holding the status of a migration.
2058 6a1434d7 Andrea Spadaccini

2059 6a1434d7 Andrea Spadaccini
  """
2060 6a1434d7 Andrea Spadaccini
  __slots__ = [
2061 6a1434d7 Andrea Spadaccini
    "status",
2062 6a1434d7 Andrea Spadaccini
    "transferred_ram",
2063 6a1434d7 Andrea Spadaccini
    "total_ram",
2064 6a1434d7 Andrea Spadaccini
    ]
2065 6a1434d7 Andrea Spadaccini
2066 6a1434d7 Andrea Spadaccini
2067 25ce3ec4 Michael Hanselmann
class InstanceConsole(ConfigObject):
2068 25ce3ec4 Michael Hanselmann
  """Object describing how to access the console of an instance.
2069 25ce3ec4 Michael Hanselmann

2070 25ce3ec4 Michael Hanselmann
  """
2071 25ce3ec4 Michael Hanselmann
  __slots__ = [
2072 25ce3ec4 Michael Hanselmann
    "instance",
2073 25ce3ec4 Michael Hanselmann
    "kind",
2074 25ce3ec4 Michael Hanselmann
    "message",
2075 25ce3ec4 Michael Hanselmann
    "host",
2076 25ce3ec4 Michael Hanselmann
    "port",
2077 25ce3ec4 Michael Hanselmann
    "user",
2078 25ce3ec4 Michael Hanselmann
    "command",
2079 25ce3ec4 Michael Hanselmann
    "display",
2080 25ce3ec4 Michael Hanselmann
    ]
2081 25ce3ec4 Michael Hanselmann
2082 25ce3ec4 Michael Hanselmann
  def Validate(self):
2083 25ce3ec4 Michael Hanselmann
    """Validates contents of this object.
2084 25ce3ec4 Michael Hanselmann

2085 25ce3ec4 Michael Hanselmann
    """
2086 25ce3ec4 Michael Hanselmann
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2087 25ce3ec4 Michael Hanselmann
    assert self.instance, "Missing instance name"
2088 4d2cdb5a Andrea Spadaccini
    assert self.message or self.kind in [constants.CONS_SSH,
2089 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2090 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_VNC]
2091 25ce3ec4 Michael Hanselmann
    assert self.host or self.kind == constants.CONS_MESSAGE
2092 25ce3ec4 Michael Hanselmann
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2093 25ce3ec4 Michael Hanselmann
                                      constants.CONS_SSH]
2094 25ce3ec4 Michael Hanselmann
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2095 4d2cdb5a Andrea Spadaccini
                                      constants.CONS_SPICE,
2096 25ce3ec4 Michael Hanselmann
                                      constants.CONS_VNC]
2097 25ce3ec4 Michael Hanselmann
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2098 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2099 25ce3ec4 Michael Hanselmann
                                         constants.CONS_VNC]
2100 25ce3ec4 Michael Hanselmann
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2101 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2102 25ce3ec4 Michael Hanselmann
                                         constants.CONS_SSH]
2103 25ce3ec4 Michael Hanselmann
    return True
2104 25ce3ec4 Michael Hanselmann
2105 25ce3ec4 Michael Hanselmann
2106 8140e24f Dimitris Aragiorgis
class Network(TaggableObject):
2107 eaa4c57c Dimitris Aragiorgis
  """Object representing a network definition for ganeti.
2108 eaa4c57c Dimitris Aragiorgis

2109 eaa4c57c Dimitris Aragiorgis
  """
2110 eaa4c57c Dimitris Aragiorgis
  __slots__ = [
2111 eaa4c57c Dimitris Aragiorgis
    "name",
2112 eaa4c57c Dimitris Aragiorgis
    "serial_no",
2113 eaa4c57c Dimitris Aragiorgis
    "mac_prefix",
2114 eaa4c57c Dimitris Aragiorgis
    "network",
2115 eaa4c57c Dimitris Aragiorgis
    "network6",
2116 eaa4c57c Dimitris Aragiorgis
    "gateway",
2117 eaa4c57c Dimitris Aragiorgis
    "gateway6",
2118 eaa4c57c Dimitris Aragiorgis
    "reservations",
2119 eaa4c57c Dimitris Aragiorgis
    "ext_reservations",
2120 eaa4c57c Dimitris Aragiorgis
    ] + _TIMESTAMPS + _UUID
2121 eaa4c57c Dimitris Aragiorgis
2122 7e8f03e3 Dimitris Aragiorgis
  def HooksDict(self, prefix=""):
2123 d89168ff Guido Trotter
    """Export a dictionary used by hooks with a network's information.
2124 d89168ff Guido Trotter

2125 d89168ff Guido Trotter
    @type prefix: String
2126 d89168ff Guido Trotter
    @param prefix: Prefix to prepend to the dict entries
2127 d89168ff Guido Trotter

2128 d89168ff Guido Trotter
    """
2129 d89168ff Guido Trotter
    result = {
2130 7e8f03e3 Dimitris Aragiorgis
      "%sNETWORK_NAME" % prefix: self.name,
2131 d89168ff Guido Trotter
      "%sNETWORK_UUID" % prefix: self.uuid,
2132 5a76adf7 Dimitris Aragiorgis
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2133 d89168ff Guido Trotter
    }
2134 d89168ff Guido Trotter
    if self.network:
2135 d89168ff Guido Trotter
      result["%sNETWORK_SUBNET" % prefix] = self.network
2136 d89168ff Guido Trotter
    if self.gateway:
2137 d89168ff Guido Trotter
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2138 d89168ff Guido Trotter
    if self.network6:
2139 d89168ff Guido Trotter
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2140 d89168ff Guido Trotter
    if self.gateway6:
2141 d89168ff Guido Trotter
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2142 d89168ff Guido Trotter
    if self.mac_prefix:
2143 d89168ff Guido Trotter
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2144 d89168ff Guido Trotter
2145 d89168ff Guido Trotter
    return result
2146 d89168ff Guido Trotter
2147 5cfa6c37 Dimitris Aragiorgis
  @classmethod
2148 5cfa6c37 Dimitris Aragiorgis
  def FromDict(cls, val):
2149 5cfa6c37 Dimitris Aragiorgis
    """Custom function for networks.
2150 5cfa6c37 Dimitris Aragiorgis

2151 48616625 Dimitris Aragiorgis
    Remove deprecated network_type and family.
2152 5cfa6c37 Dimitris Aragiorgis

2153 5cfa6c37 Dimitris Aragiorgis
    """
2154 5cfa6c37 Dimitris Aragiorgis
    if "network_type" in val:
2155 5cfa6c37 Dimitris Aragiorgis
      del val["network_type"]
2156 48616625 Dimitris Aragiorgis
    if "family" in val:
2157 48616625 Dimitris Aragiorgis
      del val["family"]
2158 5cfa6c37 Dimitris Aragiorgis
    obj = super(Network, cls).FromDict(val)
2159 5cfa6c37 Dimitris Aragiorgis
    return obj
2160 5cfa6c37 Dimitris Aragiorgis
2161 eaa4c57c Dimitris Aragiorgis
2162 523170de Dimitris Aragiorgis
# need to inherit object in order to use super()
2163 523170de Dimitris Aragiorgis
class SerializableConfigParser(ConfigParser.SafeConfigParser, object):
2164 a8083063 Iustin Pop
  """Simple wrapper over ConfigParse that allows serialization.
2165 a8083063 Iustin Pop

2166 a8083063 Iustin Pop
  This class is basically ConfigParser.SafeConfigParser with two
2167 a8083063 Iustin Pop
  additional methods that allow it to serialize/unserialize to/from a
2168 a8083063 Iustin Pop
  buffer.
2169 a8083063 Iustin Pop

2170 a8083063 Iustin Pop
  """
2171 a8083063 Iustin Pop
  def Dumps(self):
2172 a8083063 Iustin Pop
    """Dump this instance and return the string representation."""
2173 a8083063 Iustin Pop
    buf = StringIO()
2174 a8083063 Iustin Pop
    self.write(buf)
2175 a8083063 Iustin Pop
    return buf.getvalue()
2176 a8083063 Iustin Pop
2177 b39bf4bb Guido Trotter
  @classmethod
2178 b39bf4bb Guido Trotter
  def Loads(cls, data):
2179 a8083063 Iustin Pop
    """Load data from a string."""
2180 a8083063 Iustin Pop
    buf = StringIO(data)
2181 b39bf4bb Guido Trotter
    cfp = cls()
2182 a8083063 Iustin Pop
    cfp.readfp(buf)
2183 a8083063 Iustin Pop
    return cfp
2184 59726e15 Bernardo Dal Seno
2185 523170de Dimitris Aragiorgis
  def get(self, section, option, **kwargs):
2186 523170de Dimitris Aragiorgis
    value = None
2187 523170de Dimitris Aragiorgis
    try:
2188 523170de Dimitris Aragiorgis
      value = super(SerializableConfigParser, self).get(section, option,
2189 523170de Dimitris Aragiorgis
                                                        **kwargs)
2190 523170de Dimitris Aragiorgis
      if value.lower() == constants.VALUE_NONE:
2191 523170de Dimitris Aragiorgis
        value = None
2192 523170de Dimitris Aragiorgis
    except ConfigParser.NoOptionError:
2193 523170de Dimitris Aragiorgis
      r = re.compile(r"(disk|nic)\d+_name")
2194 523170de Dimitris Aragiorgis
      match = r.match(option)
2195 523170de Dimitris Aragiorgis
      if match:
2196 523170de Dimitris Aragiorgis
        pass
2197 523170de Dimitris Aragiorgis
      else:
2198 523170de Dimitris Aragiorgis
        raise
2199 523170de Dimitris Aragiorgis
2200 523170de Dimitris Aragiorgis
    return value
2201 523170de Dimitris Aragiorgis
2202 59726e15 Bernardo Dal Seno
2203 59726e15 Bernardo Dal Seno
class LvmPvInfo(ConfigObject):
2204 59726e15 Bernardo Dal Seno
  """Information about an LVM physical volume (PV).
2205 59726e15 Bernardo Dal Seno

2206 59726e15 Bernardo Dal Seno
  @type name: string
2207 59726e15 Bernardo Dal Seno
  @ivar name: name of the PV
2208 59726e15 Bernardo Dal Seno
  @type vg_name: string
2209 59726e15 Bernardo Dal Seno
  @ivar vg_name: name of the volume group containing the PV
2210 59726e15 Bernardo Dal Seno
  @type size: float
2211 59726e15 Bernardo Dal Seno
  @ivar size: size of the PV in MiB
2212 59726e15 Bernardo Dal Seno
  @type free: float
2213 59726e15 Bernardo Dal Seno
  @ivar free: free space in the PV, in MiB
2214 59726e15 Bernardo Dal Seno
  @type attributes: string
2215 59726e15 Bernardo Dal Seno
  @ivar attributes: PV attributes
2216 b496abdb Bernardo Dal Seno
  @type lv_list: list of strings
2217 b496abdb Bernardo Dal Seno
  @ivar lv_list: names of the LVs hosted on the PV
2218 59726e15 Bernardo Dal Seno
  """
2219 59726e15 Bernardo Dal Seno
  __slots__ = [
2220 59726e15 Bernardo Dal Seno
    "name",
2221 59726e15 Bernardo Dal Seno
    "vg_name",
2222 59726e15 Bernardo Dal Seno
    "size",
2223 59726e15 Bernardo Dal Seno
    "free",
2224 59726e15 Bernardo Dal Seno
    "attributes",
2225 b496abdb Bernardo Dal Seno
    "lv_list"
2226 59726e15 Bernardo Dal Seno
    ]
2227 59726e15 Bernardo Dal Seno
2228 59726e15 Bernardo Dal Seno
  def IsEmpty(self):
2229 59726e15 Bernardo Dal Seno
    """Is this PV empty?
2230 59726e15 Bernardo Dal Seno

2231 59726e15 Bernardo Dal Seno
    """
2232 59726e15 Bernardo Dal Seno
    return self.size <= (self.free + 1)
2233 59726e15 Bernardo Dal Seno
2234 59726e15 Bernardo Dal Seno
  def IsAllocatable(self):
2235 59726e15 Bernardo Dal Seno
    """Is this PV allocatable?
2236 59726e15 Bernardo Dal Seno

2237 59726e15 Bernardo Dal Seno
    """
2238 59726e15 Bernardo Dal Seno
    return ("a" in self.attributes)