Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 6970c28b

History | View | Annotate | Download (64.3 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 19830e88 Thomas Thrainer
  def __eq__(self, other):
270 19830e88 Thomas Thrainer
    """Implement __eq__ for ConfigObjects."""
271 19830e88 Thomas Thrainer
    return isinstance(other, self.__class__) and self.ToDict() == other.ToDict()
272 19830e88 Thomas Thrainer
273 560428be Guido Trotter
  def UpgradeConfig(self):
274 560428be Guido Trotter
    """Fill defaults for missing configuration values.
275 560428be Guido Trotter

276 90d726a8 Iustin Pop
    This method will be called at configuration load time, and its
277 90d726a8 Iustin Pop
    implementation will be object dependent.
278 560428be Guido Trotter

279 560428be Guido Trotter
    """
280 560428be Guido Trotter
    pass
281 560428be Guido Trotter
282 a8083063 Iustin Pop
283 ec29fe40 Iustin Pop
class TaggableObject(ConfigObject):
284 5c947f38 Iustin Pop
  """An generic class supporting tags.
285 5c947f38 Iustin Pop

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

294 5c947f38 Iustin Pop
    If the tag is invalid, an errors.TagError will be raised. The
295 5c947f38 Iustin Pop
    function has no return value.
296 5c947f38 Iustin Pop

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

311 5c947f38 Iustin Pop
    """
312 5c947f38 Iustin Pop
    tags = getattr(self, "tags", None)
313 5c947f38 Iustin Pop
    if tags is None:
314 5c947f38 Iustin Pop
      tags = self.tags = set()
315 5c947f38 Iustin Pop
    return tags
316 5c947f38 Iustin Pop
317 5c947f38 Iustin Pop
  def AddTag(self, tag):
318 5c947f38 Iustin Pop
    """Add a new tag.
319 5c947f38 Iustin Pop

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

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

341 ff9c047c Iustin Pop
    This replaces the tags set with a list.
342 ff9c047c Iustin Pop

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

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

365 1c3231aa Thomas Thrainer
  @ivar uuid: master nodes UUID
366 061af273 Andrea Spadaccini
  @ivar ip: master IP
367 061af273 Andrea Spadaccini
  @ivar netmask: master netmask
368 061af273 Andrea Spadaccini
  @ivar netdev: master network device
369 061af273 Andrea Spadaccini
  @ivar ip_family: master IP family
370 061af273 Andrea Spadaccini

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

396 ff9c047c Iustin Pop
    This just replaces the list of instances, nodes and the cluster
397 ff9c047c Iustin Pop
    with standard python types.
398 ff9c047c Iustin Pop

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

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

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

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

440 90d726a8 Iustin Pop
    """
441 90d726a8 Iustin Pop
    self.cluster.UpgradeConfig()
442 90d726a8 Iustin Pop
    for node in self.nodes.values():
443 90d726a8 Iustin Pop
      node.UpgradeConfig()
444 90d726a8 Iustin Pop
    for instance in self.instances.values():
445 90d726a8 Iustin Pop
      instance.UpgradeConfig()
446 3df43542 Guido Trotter
    if self.nodegroups is None:
447 3df43542 Guido Trotter
      self.nodegroups = {}
448 3df43542 Guido Trotter
    for nodegroup in self.nodegroups.values():
449 3df43542 Guido Trotter
      nodegroup.UpgradeConfig()
450 ee2f0ed4 Luca Bigliardi
    if self.cluster.drbd_usermode_helper is None:
451 25e5e785 Helga Velroyen
      if self.cluster.IsDiskTemplateEnabled(constants.DT_DRBD8):
452 ee2f0ed4 Luca Bigliardi
        self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
453 eaa4c57c Dimitris Aragiorgis
    if self.networks is None:
454 eaa4c57c Dimitris Aragiorgis
      self.networks = {}
455 ee9516c8 Guido Trotter
    for network in self.networks.values():
456 ee9516c8 Guido Trotter
      network.UpgradeConfig()
457 1b02d7ef Helga Velroyen
    self._UpgradeEnabledDiskTemplates()
458 c66d8987 Helga Velroyen
459 1b02d7ef Helga Velroyen
  def _UpgradeEnabledDiskTemplates(self):
460 1b02d7ef Helga Velroyen
    """Upgrade the cluster's enabled disk templates by inspecting the currently
461 1b02d7ef Helga Velroyen
       enabled and/or used disk templates.
462 c66d8987 Helga Velroyen

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

492 255e19d4 Guido Trotter
    @type nicparams:  dict
493 255e19d4 Guido Trotter
    @param nicparams: dictionary with parameter names/value
494 255e19d4 Guido Trotter
    @raise errors.ConfigurationError: when a parameter is not valid
495 255e19d4 Guido Trotter

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

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

532 e51db2a6 Iustin Pop
    @warning: The path returned is not a normalized pathname; callers
533 e51db2a6 Iustin Pop
        should check that it is a valid path.
534 e51db2a6 Iustin Pop

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

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

551 fc1dc9d7 Iustin Pop
    Currently, only DRBD8 supports diskless activation (therefore we
552 fc1dc9d7 Iustin Pop
    return 0), for all other we keep the previous semantics and return
553 fc1dc9d7 Iustin Pop
    -1.
554 fc1dc9d7 Iustin Pop

555 fc1dc9d7 Iustin Pop
    """
556 fc1dc9d7 Iustin Pop
    if self.dev_type == constants.LD_DRBD8:
557 fc1dc9d7 Iustin Pop
      return 0
558 fc1dc9d7 Iustin Pop
    return -1
559 fc1dc9d7 Iustin Pop
560 51cb1581 Luca Bigliardi
  def IsBasedOnDiskType(self, dev_type):
561 51cb1581 Luca Bigliardi
    """Check if the disk or its children are based on the given type.
562 51cb1581 Luca Bigliardi

563 51cb1581 Luca Bigliardi
    @type dev_type: L{constants.LDS_BLOCK}
564 51cb1581 Luca Bigliardi
    @param dev_type: the type to look for
565 51cb1581 Luca Bigliardi
    @rtype: boolean
566 51cb1581 Luca Bigliardi
    @return: boolean indicating if a device of the given type was found or not
567 51cb1581 Luca Bigliardi

568 51cb1581 Luca Bigliardi
    """
569 51cb1581 Luca Bigliardi
    if self.children:
570 51cb1581 Luca Bigliardi
      for child in self.children:
571 51cb1581 Luca Bigliardi
        if child.IsBasedOnDiskType(dev_type):
572 51cb1581 Luca Bigliardi
          return True
573 51cb1581 Luca Bigliardi
    return self.dev_type == dev_type
574 51cb1581 Luca Bigliardi
575 1c3231aa Thomas Thrainer
  def GetNodes(self, node_uuid):
576 a8083063 Iustin Pop
    """This function returns the nodes this device lives on.
577 a8083063 Iustin Pop

578 a8083063 Iustin Pop
    Given the node on which the parent of the device lives on (or, in
579 a8083063 Iustin Pop
    case of a top-level device, the primary node of the devices'
580 a8083063 Iustin Pop
    instance), this function will return a list of nodes on which this
581 a8083063 Iustin Pop
    devices needs to (or can) be assembled.
582 a8083063 Iustin Pop

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

599 a8083063 Iustin Pop
    This method, given the node on which the parent disk lives, will
600 1c3231aa Thomas Thrainer
    return the list of all (node UUID, disk) pairs which describe the disk
601 abdf0113 Iustin Pop
    tree in the most compact way. For example, a drbd/lvm stack
602 abdf0113 Iustin Pop
    will be returned as (primary_node, drbd) and (secondary_node, drbd)
603 abdf0113 Iustin Pop
    which represents all the top-level devices on the nodes.
604 a8083063 Iustin Pop

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

634 6d33a6eb Iustin Pop
    This only works for VG-based disks.
635 6d33a6eb Iustin Pop

636 6d33a6eb Iustin Pop
    @type amount: integer
637 6d33a6eb Iustin Pop
    @param amount: the desired increase in (user-visible) disk space
638 6d33a6eb Iustin Pop
    @rtype: dict
639 6d33a6eb Iustin Pop
    @return: a dictionary of volume-groups and the required size
640 6d33a6eb Iustin Pop

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

656 acec9d51 Iustin Pop
    This method recurses over the disks's children and updates their
657 acec9d51 Iustin Pop
    size correspondigly. The method needs to be kept in sync with the
658 acec9d51 Iustin Pop
    actual algorithms from bdev.
659 acec9d51 Iustin Pop

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

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

692 a805ec18 Iustin Pop
    """
693 a805ec18 Iustin Pop
    if self.children:
694 a805ec18 Iustin Pop
      for child in self.children:
695 a805ec18 Iustin Pop
        child.UnsetSize()
696 a805ec18 Iustin Pop
    self.size = 0
697 a805ec18 Iustin Pop
698 1c3231aa Thomas Thrainer
  def SetPhysicalID(self, target_node_uuid, nodes_ip):
699 0402302c Iustin Pop
    """Convert the logical ID to the physical ID.
700 0402302c Iustin Pop

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

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

707 0402302c Iustin Pop
    Arguments:
708 1c3231aa Thomas Thrainer
      - target_node_uuid: the node UUID we wish to configure for
709 0402302c Iustin Pop
      - nodes_ip: a mapping of node name to ip
710 0402302c Iustin Pop

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

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

745 ff9c047c Iustin Pop
    This replaces the children lists of objects with lists of
746 ff9c047c Iustin Pop
    standard python types.
747 ff9c047c Iustin Pop

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

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

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

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

824 90d726a8 Iustin Pop
    """
825 90d726a8 Iustin Pop
    if self.children:
826 90d726a8 Iustin Pop
      for child in self.children:
827 90d726a8 Iustin Pop
        child.UpgradeConfig()
828 bc5d0215 Andrea Spadaccini
829 cce46164 Renรฉ Nussbaumer
    # FIXME: Make this configurable in Ganeti 2.7
830 5dbee5ea Iustin Pop
    self.params = {}
831 90d726a8 Iustin Pop
    # add here config upgrade for this disk
832 90d726a8 Iustin Pop
833 cd46491f Renรฉ Nussbaumer
  @staticmethod
834 cd46491f Renรฉ Nussbaumer
  def ComputeLDParams(disk_template, disk_params):
835 cd46491f Renรฉ Nussbaumer
    """Computes Logical Disk parameters from Disk Template parameters.
836 cd46491f Renรฉ Nussbaumer

837 cd46491f Renรฉ Nussbaumer
    @type disk_template: string
838 cd46491f Renรฉ Nussbaumer
    @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
839 cd46491f Renรฉ Nussbaumer
    @type disk_params: dict
840 cd46491f Renรฉ Nussbaumer
    @param disk_params: disk template parameters;
841 cd46491f Renรฉ Nussbaumer
                        dict(template_name -> parameters
842 cd46491f Renรฉ Nussbaumer
    @rtype: list(dict)
843 cd46491f Renรฉ Nussbaumer
    @return: a list of dicts, one for each node of the disk hierarchy. Each dict
844 cd46491f Renรฉ Nussbaumer
      contains the LD parameters of the node. The tree is flattened in-order.
845 cd46491f Renรฉ Nussbaumer

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

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

909 ffa339ca Iustin Pop
  """
910 918eb80b Agata Murawska
  @classmethod
911 8b057218 Renรฉ Nussbaumer
  def CheckParameterSyntax(cls, ipolicy, check_std):
912 918eb80b Agata Murawska
    """ Check the instance policy for validity.
913 918eb80b Agata Murawska

914 da5f09ef Bernardo Dal Seno
    @type ipolicy: dict
915 da5f09ef Bernardo Dal Seno
    @param ipolicy: dictionary with min/max/std specs and policies
916 da5f09ef Bernardo Dal Seno
    @type check_std: bool
917 da5f09ef Bernardo Dal Seno
    @param check_std: Whether to check std value or just assume compliance
918 da5f09ef Bernardo Dal Seno
    @raise errors.ConfigurationError: when the policy is not legal
919 da5f09ef Bernardo Dal Seno

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

944 62fed51b Bernardo Dal Seno
    @type ipolicy: dict
945 62fed51b Bernardo Dal Seno
    @param ipolicy: dictionary with min/max/std specs
946 62fed51b Bernardo Dal Seno
    @type check_std: bool
947 62fed51b Bernardo Dal Seno
    @param check_std: Whether to check std value or just assume compliance
948 62fed51b Bernardo Dal Seno
    @raise errors.ConfigurationError: when specs are not valid
949 62fed51b Bernardo Dal Seno

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

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

989 da5f09ef Bernardo Dal Seno
    @type minmaxspecs: dict
990 da5f09ef Bernardo Dal Seno
    @param minmaxspecs: dictionary with min and max instance spec
991 da5f09ef Bernardo Dal Seno
    @type stdspec: dict
992 da5f09ef Bernardo Dal Seno
    @param stdspec: dictionary with standard instance spec
993 918eb80b Agata Murawska
    @type name: string
994 918eb80b Agata Murawska
    @param name: what are the limits for
995 8b057218 Renรฉ Nussbaumer
    @type check_std: bool
996 8b057218 Renรฉ Nussbaumer
    @param check_std: Whether to check std value or just assume compliance
997 b342c9dd Bernardo Dal Seno
    @rtype: bool
998 b342c9dd Bernardo Dal Seno
    @return: C{True} when specs are valid, C{False} when standard spec for the
999 b342c9dd Bernardo Dal Seno
        given name is not valid
1000 b342c9dd Bernardo Dal Seno
    @raise errors.ConfigurationError: when min/max specs for the given name
1001 b342c9dd Bernardo Dal Seno
        are not valid
1002 918eb80b Agata Murawska

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

1023 2cc673a3 Iustin Pop
    """
1024 ba5c6c6b Bernardo Dal Seno
    if not disk_templates:
1025 ba5c6c6b Bernardo Dal Seno
      raise errors.ConfigurationError("Instance policy must contain" +
1026 ba5c6c6b Bernardo Dal Seno
                                      " at least one disk template")
1027 2cc673a3 Iustin Pop
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1028 2cc673a3 Iustin Pop
    if wrong:
1029 2cc673a3 Iustin Pop
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1030 2cc673a3 Iustin Pop
                                      utils.CommaJoin(wrong))
1031 2cc673a3 Iustin Pop
1032 ff6c5e55 Iustin Pop
  @classmethod
1033 ff6c5e55 Iustin Pop
  def CheckParameter(cls, key, value):
1034 ff6c5e55 Iustin Pop
    """Checks a parameter.
1035 ff6c5e55 Iustin Pop

1036 ff6c5e55 Iustin Pop
    Currently we expect all parameters to be float values.
1037 ff6c5e55 Iustin Pop

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

1068 cfcc5c6d Iustin Pop
    This is a simple wrapper over _ComputeAllNodes.
1069 cfcc5c6d Iustin Pop

1070 cfcc5c6d Iustin Pop
    """
1071 cfcc5c6d Iustin Pop
    all_nodes = set(self._ComputeAllNodes())
1072 cfcc5c6d Iustin Pop
    all_nodes.discard(self.primary_node)
1073 cfcc5c6d Iustin Pop
    return tuple(all_nodes)
1074 cfcc5c6d Iustin Pop
1075 cfcc5c6d Iustin Pop
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1076 05325a35 Bernardo Dal Seno
                             "List of names of secondary nodes")
1077 cfcc5c6d Iustin Pop
1078 cfcc5c6d Iustin Pop
  def _ComputeAllNodes(self):
1079 cfcc5c6d Iustin Pop
    """Compute the list of all nodes.
1080 cfcc5c6d Iustin Pop

1081 a8083063 Iustin Pop
    Since the data is already there (in the drbd disks), keeping it as
1082 a8083063 Iustin Pop
    a separate normal attribute is redundant and if not properly
1083 a8083063 Iustin Pop
    synchronised can cause problems. Thus it's better to compute it
1084 a8083063 Iustin Pop
    dynamically.
1085 a8083063 Iustin Pop

1086 a8083063 Iustin Pop
    """
1087 cfcc5c6d Iustin Pop
    def _Helper(nodes, device):
1088 cfcc5c6d Iustin Pop
      """Recursively computes nodes given a top device."""
1089 a1f445d3 Iustin Pop
      if device.dev_type in constants.LDS_DRBD:
1090 cfcc5c6d Iustin Pop
        nodea, nodeb = device.logical_id[:2]
1091 cfcc5c6d Iustin Pop
        nodes.add(nodea)
1092 cfcc5c6d Iustin Pop
        nodes.add(nodeb)
1093 a8083063 Iustin Pop
      if device.children:
1094 a8083063 Iustin Pop
        for child in device.children:
1095 cfcc5c6d Iustin Pop
          _Helper(nodes, child)
1096 a8083063 Iustin Pop
1097 cfcc5c6d Iustin Pop
    all_nodes = set()
1098 99c7b2a1 Iustin Pop
    all_nodes.add(self.primary_node)
1099 a8083063 Iustin Pop
    for device in self.disks:
1100 cfcc5c6d Iustin Pop
      _Helper(all_nodes, device)
1101 cfcc5c6d Iustin Pop
    return tuple(all_nodes)
1102 a8083063 Iustin Pop
1103 cfcc5c6d Iustin Pop
  all_nodes = property(_ComputeAllNodes, None, None,
1104 05325a35 Bernardo Dal Seno
                       "List of names of all the nodes of the instance")
1105 a8083063 Iustin Pop
1106 843094ad Thomas Thrainer
  def MapLVsByNode(self, lvmap=None, devs=None, node_uuid=None):
1107 a8083063 Iustin Pop
    """Provide a mapping of nodes to LVs this instance owns.
1108 a8083063 Iustin Pop

1109 c41eea6e Iustin Pop
    This function figures out what logical volumes should belong on
1110 c41eea6e Iustin Pop
    which nodes, recursing through a device tree.
1111 a8083063 Iustin Pop

1112 843094ad Thomas Thrainer
    @type lvmap: dict
1113 c41eea6e Iustin Pop
    @param lvmap: optional dictionary to receive the
1114 c41eea6e Iustin Pop
        'node' : ['lv', ...] data.
1115 843094ad Thomas Thrainer
    @type devs: list of L{Disk}
1116 843094ad Thomas Thrainer
    @param devs: disks to get the LV name for. If None, all disk of this
1117 843094ad Thomas Thrainer
        instance are used.
1118 843094ad Thomas Thrainer
    @type node_uuid: string
1119 843094ad Thomas Thrainer
    @param node_uuid: UUID of the node to get the LV names for. If None, the
1120 843094ad Thomas Thrainer
        primary node of this instance is used.
1121 84d7e26b Dmitry Chernyak
    @return: None if lvmap arg is given, otherwise, a dictionary of
1122 1c3231aa Thomas Thrainer
        the form { 'node_uuid' : ['volume1', 'volume2', ...], ... };
1123 84d7e26b Dmitry Chernyak
        volumeN is of the form "vg_name/lv_name", compatible with
1124 84d7e26b Dmitry Chernyak
        GetVolumeList()
1125 a8083063 Iustin Pop

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

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

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

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

1183 ff9c047c Iustin Pop
    This replaces the children lists of objects with lists of standard
1184 ff9c047c Iustin Pop
    python types.
1185 ff9c047c Iustin Pop

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

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

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

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

1243 870dc44c Iustin Pop
  @type VARIANT_DELIM: string
1244 870dc44c Iustin Pop
  @cvar VARIANT_DELIM: the variant delimiter
1245 870dc44c Iustin Pop

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

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

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

1281 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1282 870dc44c Iustin Pop

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

1290 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1291 870dc44c Iustin Pop

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

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

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

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

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

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

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

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

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

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

1455 c60abd62 Guido Trotter
    This discards the members object, which gets recalculated and is only kept
1456 c60abd62 Guido Trotter
    in memory.
1457 24a3707f Guido Trotter

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

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

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

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

1503 095e71aa Renรฉ Nussbaumer
    @type node: L{objects.Node}
1504 095e71aa Renรฉ Nussbaumer
    @param node: A Node object to fill
1505 095e71aa Renรฉ Nussbaumer
    @return a copy of the node's ndparams with defaults filled
1506 095e71aa Renรฉ Nussbaumer

1507 095e71aa Renรฉ Nussbaumer
    """
1508 095e71aa Renรฉ Nussbaumer
    return self.SimpleFillND(node.ndparams)
1509 095e71aa Renรฉ Nussbaumer
1510 095e71aa Renรฉ Nussbaumer
  def SimpleFillND(self, ndparams):
1511 095e71aa Renรฉ Nussbaumer
    """Fill a given ndparams dict with defaults.
1512 095e71aa Renรฉ Nussbaumer

1513 095e71aa Renรฉ Nussbaumer
    @type ndparams: dict
1514 095e71aa Renรฉ Nussbaumer
    @param ndparams: the dict to fill
1515 095e71aa Renรฉ Nussbaumer
    @rtype: dict
1516 095e71aa Renรฉ Nussbaumer
    @return: a copy of the passed in ndparams with missing keys filled
1517 e6e88de6 Adeodato Simo
        from the node group defaults
1518 095e71aa Renรฉ Nussbaumer

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

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

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

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

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

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

1723 8a147bba Renรฉ Nussbaumer
    @param diskparams: The diskparams
1724 8a147bba Renรฉ Nussbaumer
    @return: The defaults dict
1725 8a147bba Renรฉ Nussbaumer

1726 8a147bba Renรฉ Nussbaumer
    """
1727 8a147bba Renรฉ Nussbaumer
    return FillDiskParams(self.diskparams, diskparams)
1728 8a147bba Renรฉ Nussbaumer
1729 d63479b5 Iustin Pop
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1730 d63479b5 Iustin Pop
    """Get the default hypervisor parameters for the cluster.
1731 d63479b5 Iustin Pop

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1851 2da9f556 Renรฉ Nussbaumer
    """
1852 2da9f556 Renรฉ Nussbaumer
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1853 2da9f556 Renรฉ Nussbaumer
1854 2da9f556 Renรฉ Nussbaumer
  @staticmethod
1855 2da9f556 Renรฉ Nussbaumer
  def SimpleFillDiskState(disk_state):
1856 2da9f556 Renรฉ Nussbaumer
    """Fill an disk_state sub dict with cluster defaults.
1857 2da9f556 Renรฉ Nussbaumer

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

1864 095e71aa Renรฉ Nussbaumer
    @type node: L{objects.Node}
1865 095e71aa Renรฉ Nussbaumer
    @param node: A Node object to fill
1866 095e71aa Renรฉ Nussbaumer
    @type nodegroup: L{objects.NodeGroup}
1867 095e71aa Renรฉ Nussbaumer
    @param nodegroup: A Node object to fill
1868 095e71aa Renรฉ Nussbaumer
    @return a copy of the node's ndparams with defaults filled
1869 095e71aa Renรฉ Nussbaumer

1870 095e71aa Renรฉ Nussbaumer
    """
1871 095e71aa Renรฉ Nussbaumer
    return self.SimpleFillND(nodegroup.FillND(node))
1872 095e71aa Renรฉ Nussbaumer
1873 095e71aa Renรฉ Nussbaumer
  def SimpleFillND(self, ndparams):
1874 095e71aa Renรฉ Nussbaumer
    """Fill a given ndparams dict with defaults.
1875 095e71aa Renรฉ Nussbaumer

1876 095e71aa Renรฉ Nussbaumer
    @type ndparams: dict
1877 095e71aa Renรฉ Nussbaumer
    @param ndparams: the dict to fill
1878 095e71aa Renรฉ Nussbaumer
    @rtype: dict
1879 095e71aa Renรฉ Nussbaumer
    @return: a copy of the passed in ndparams with missing keys filled
1880 095e71aa Renรฉ Nussbaumer
        from the cluster defaults
1881 095e71aa Renรฉ Nussbaumer

1882 095e71aa Renรฉ Nussbaumer
    """
1883 095e71aa Renรฉ Nussbaumer
    return FillDict(self.ndparams, ndparams)
1884 095e71aa Renรฉ Nussbaumer
1885 918eb80b Agata Murawska
  def SimpleFillIPolicy(self, ipolicy):
1886 918eb80b Agata Murawska
    """ Fill instance policy dict with defaults.
1887 918eb80b Agata Murawska

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

1894 918eb80b Agata Murawska
    """
1895 2cc673a3 Iustin Pop
    return FillIPolicy(self.ipolicy, ipolicy)
1896 918eb80b Agata Murawska
1897 ebe93784 Helga Velroyen
  def IsDiskTemplateEnabled(self, disk_template):
1898 ebe93784 Helga Velroyen
    """Checks if a particular disk template is enabled.
1899 ebe93784 Helga Velroyen

1900 ebe93784 Helga Velroyen
    """
1901 ebe93784 Helga Velroyen
    return utils.storage.IsDiskTemplateEnabled(
1902 ebe93784 Helga Velroyen
        disk_template, self.enabled_disk_templates)
1903 ebe93784 Helga Velroyen
1904 ebe93784 Helga Velroyen
  def IsFileStorageEnabled(self):
1905 ebe93784 Helga Velroyen
    """Checks if file storage is enabled.
1906 ebe93784 Helga Velroyen

1907 ebe93784 Helga Velroyen
    """
1908 ebe93784 Helga Velroyen
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
1909 ebe93784 Helga Velroyen
1910 ebe93784 Helga Velroyen
  def IsSharedFileStorageEnabled(self):
1911 ebe93784 Helga Velroyen
    """Checks if shared file storage is enabled.
1912 ebe93784 Helga Velroyen

1913 ebe93784 Helga Velroyen
    """
1914 ebe93784 Helga Velroyen
    return utils.storage.IsSharedFileStorageEnabled(
1915 ebe93784 Helga Velroyen
        self.enabled_disk_templates)
1916 ebe93784 Helga Velroyen
1917 5c947f38 Iustin Pop
1918 96acbc09 Michael Hanselmann
class BlockDevStatus(ConfigObject):
1919 96acbc09 Michael Hanselmann
  """Config object representing the status of a block device."""
1920 96acbc09 Michael Hanselmann
  __slots__ = [
1921 96acbc09 Michael Hanselmann
    "dev_path",
1922 96acbc09 Michael Hanselmann
    "major",
1923 96acbc09 Michael Hanselmann
    "minor",
1924 96acbc09 Michael Hanselmann
    "sync_percent",
1925 96acbc09 Michael Hanselmann
    "estimated_time",
1926 96acbc09 Michael Hanselmann
    "is_degraded",
1927 f208978a Michael Hanselmann
    "ldisk_status",
1928 96acbc09 Michael Hanselmann
    ]
1929 96acbc09 Michael Hanselmann
1930 96acbc09 Michael Hanselmann
1931 2d76b580 Michael Hanselmann
class ImportExportStatus(ConfigObject):
1932 2d76b580 Michael Hanselmann
  """Config object representing the status of an import or export."""
1933 2d76b580 Michael Hanselmann
  __slots__ = [
1934 2d76b580 Michael Hanselmann
    "recent_output",
1935 2d76b580 Michael Hanselmann
    "listen_port",
1936 2d76b580 Michael Hanselmann
    "connected",
1937 c08d76f5 Michael Hanselmann
    "progress_mbytes",
1938 c08d76f5 Michael Hanselmann
    "progress_throughput",
1939 c08d76f5 Michael Hanselmann
    "progress_eta",
1940 c08d76f5 Michael Hanselmann
    "progress_percent",
1941 2d76b580 Michael Hanselmann
    "exit_status",
1942 2d76b580 Michael Hanselmann
    "error_message",
1943 2d76b580 Michael Hanselmann
    ] + _TIMESTAMPS
1944 2d76b580 Michael Hanselmann
1945 2d76b580 Michael Hanselmann
1946 eb630f50 Michael Hanselmann
class ImportExportOptions(ConfigObject):
1947 eb630f50 Michael Hanselmann
  """Options for import/export daemon
1948 eb630f50 Michael Hanselmann

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

1956 eb630f50 Michael Hanselmann
  """
1957 eb630f50 Michael Hanselmann
  __slots__ = [
1958 eb630f50 Michael Hanselmann
    "key_name",
1959 eb630f50 Michael Hanselmann
    "ca_pem",
1960 a5310c2a Michael Hanselmann
    "compress",
1961 af1d39b1 Michael Hanselmann
    "magic",
1962 855d2fc7 Michael Hanselmann
    "ipv6",
1963 4478301b Michael Hanselmann
    "connect_timeout",
1964 eb630f50 Michael Hanselmann
    ]
1965 eb630f50 Michael Hanselmann
1966 eb630f50 Michael Hanselmann
1967 18d750b9 Guido Trotter
class ConfdRequest(ConfigObject):
1968 18d750b9 Guido Trotter
  """Object holding a confd request.
1969 18d750b9 Guido Trotter

1970 18d750b9 Guido Trotter
  @ivar protocol: confd protocol version
1971 18d750b9 Guido Trotter
  @ivar type: confd query type
1972 18d750b9 Guido Trotter
  @ivar query: query request
1973 18d750b9 Guido Trotter
  @ivar rsalt: requested reply salt
1974 18d750b9 Guido Trotter

1975 18d750b9 Guido Trotter
  """
1976 18d750b9 Guido Trotter
  __slots__ = [
1977 18d750b9 Guido Trotter
    "protocol",
1978 18d750b9 Guido Trotter
    "type",
1979 18d750b9 Guido Trotter
    "query",
1980 18d750b9 Guido Trotter
    "rsalt",
1981 18d750b9 Guido Trotter
    ]
1982 18d750b9 Guido Trotter
1983 18d750b9 Guido Trotter
1984 18d750b9 Guido Trotter
class ConfdReply(ConfigObject):
1985 18d750b9 Guido Trotter
  """Object holding a confd reply.
1986 18d750b9 Guido Trotter

1987 18d750b9 Guido Trotter
  @ivar protocol: confd protocol version
1988 18d750b9 Guido Trotter
  @ivar status: reply status code (ok, error)
1989 18d750b9 Guido Trotter
  @ivar answer: confd query reply
1990 18d750b9 Guido Trotter
  @ivar serial: configuration serial number
1991 18d750b9 Guido Trotter

1992 18d750b9 Guido Trotter
  """
1993 18d750b9 Guido Trotter
  __slots__ = [
1994 18d750b9 Guido Trotter
    "protocol",
1995 18d750b9 Guido Trotter
    "status",
1996 18d750b9 Guido Trotter
    "answer",
1997 18d750b9 Guido Trotter
    "serial",
1998 18d750b9 Guido Trotter
    ]
1999 18d750b9 Guido Trotter
2000 18d750b9 Guido Trotter
2001 707f23b5 Michael Hanselmann
class QueryFieldDefinition(ConfigObject):
2002 707f23b5 Michael Hanselmann
  """Object holding a query field definition.
2003 707f23b5 Michael Hanselmann

2004 24d6d3e2 Michael Hanselmann
  @ivar name: Field name
2005 707f23b5 Michael Hanselmann
  @ivar title: Human-readable title
2006 707f23b5 Michael Hanselmann
  @ivar kind: Field type
2007 1ae17369 Michael Hanselmann
  @ivar doc: Human-readable description
2008 707f23b5 Michael Hanselmann

2009 707f23b5 Michael Hanselmann
  """
2010 707f23b5 Michael Hanselmann
  __slots__ = [
2011 707f23b5 Michael Hanselmann
    "name",
2012 707f23b5 Michael Hanselmann
    "title",
2013 707f23b5 Michael Hanselmann
    "kind",
2014 1ae17369 Michael Hanselmann
    "doc",
2015 707f23b5 Michael Hanselmann
    ]
2016 707f23b5 Michael Hanselmann
2017 707f23b5 Michael Hanselmann
2018 0538c375 Michael Hanselmann
class _QueryResponseBase(ConfigObject):
2019 0538c375 Michael Hanselmann
  __slots__ = [
2020 0538c375 Michael Hanselmann
    "fields",
2021 0538c375 Michael Hanselmann
    ]
2022 0538c375 Michael Hanselmann
2023 0538c375 Michael Hanselmann
  def ToDict(self):
2024 0538c375 Michael Hanselmann
    """Custom function for serializing.
2025 0538c375 Michael Hanselmann

2026 0538c375 Michael Hanselmann
    """
2027 0538c375 Michael Hanselmann
    mydict = super(_QueryResponseBase, self).ToDict()
2028 fe502d25 Iustin Pop
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2029 0538c375 Michael Hanselmann
    return mydict
2030 0538c375 Michael Hanselmann
2031 0538c375 Michael Hanselmann
  @classmethod
2032 0538c375 Michael Hanselmann
  def FromDict(cls, val):
2033 0538c375 Michael Hanselmann
    """Custom function for de-serializing.
2034 0538c375 Michael Hanselmann

2035 0538c375 Michael Hanselmann
    """
2036 0538c375 Michael Hanselmann
    obj = super(_QueryResponseBase, cls).FromDict(val)
2037 473ab806 Michael Hanselmann
    obj.fields = \
2038 fe502d25 Iustin Pop
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2039 0538c375 Michael Hanselmann
    return obj
2040 0538c375 Michael Hanselmann
2041 0538c375 Michael Hanselmann
2042 0538c375 Michael Hanselmann
class QueryResponse(_QueryResponseBase):
2043 24d6d3e2 Michael Hanselmann
  """Object holding the response to a query.
2044 24d6d3e2 Michael Hanselmann

2045 24d6d3e2 Michael Hanselmann
  @ivar fields: List of L{QueryFieldDefinition} objects
2046 24d6d3e2 Michael Hanselmann
  @ivar data: Requested data
2047 24d6d3e2 Michael Hanselmann

2048 24d6d3e2 Michael Hanselmann
  """
2049 24d6d3e2 Michael Hanselmann
  __slots__ = [
2050 24d6d3e2 Michael Hanselmann
    "data",
2051 24d6d3e2 Michael Hanselmann
    ]
2052 24d6d3e2 Michael Hanselmann
2053 24d6d3e2 Michael Hanselmann
2054 24d6d3e2 Michael Hanselmann
class QueryFieldsRequest(ConfigObject):
2055 24d6d3e2 Michael Hanselmann
  """Object holding a request for querying available fields.
2056 24d6d3e2 Michael Hanselmann

2057 24d6d3e2 Michael Hanselmann
  """
2058 24d6d3e2 Michael Hanselmann
  __slots__ = [
2059 24d6d3e2 Michael Hanselmann
    "what",
2060 24d6d3e2 Michael Hanselmann
    "fields",
2061 24d6d3e2 Michael Hanselmann
    ]
2062 24d6d3e2 Michael Hanselmann
2063 24d6d3e2 Michael Hanselmann
2064 0538c375 Michael Hanselmann
class QueryFieldsResponse(_QueryResponseBase):
2065 24d6d3e2 Michael Hanselmann
  """Object holding the response to a query for fields.
2066 24d6d3e2 Michael Hanselmann

2067 24d6d3e2 Michael Hanselmann
  @ivar fields: List of L{QueryFieldDefinition} objects
2068 24d6d3e2 Michael Hanselmann

2069 24d6d3e2 Michael Hanselmann
  """
2070 5ae4945a Iustin Pop
  __slots__ = []
2071 24d6d3e2 Michael Hanselmann
2072 24d6d3e2 Michael Hanselmann
2073 6a1434d7 Andrea Spadaccini
class MigrationStatus(ConfigObject):
2074 6a1434d7 Andrea Spadaccini
  """Object holding the status of a migration.
2075 6a1434d7 Andrea Spadaccini

2076 6a1434d7 Andrea Spadaccini
  """
2077 6a1434d7 Andrea Spadaccini
  __slots__ = [
2078 6a1434d7 Andrea Spadaccini
    "status",
2079 6a1434d7 Andrea Spadaccini
    "transferred_ram",
2080 6a1434d7 Andrea Spadaccini
    "total_ram",
2081 6a1434d7 Andrea Spadaccini
    ]
2082 6a1434d7 Andrea Spadaccini
2083 6a1434d7 Andrea Spadaccini
2084 25ce3ec4 Michael Hanselmann
class InstanceConsole(ConfigObject):
2085 25ce3ec4 Michael Hanselmann
  """Object describing how to access the console of an instance.
2086 25ce3ec4 Michael Hanselmann

2087 25ce3ec4 Michael Hanselmann
  """
2088 25ce3ec4 Michael Hanselmann
  __slots__ = [
2089 25ce3ec4 Michael Hanselmann
    "instance",
2090 25ce3ec4 Michael Hanselmann
    "kind",
2091 25ce3ec4 Michael Hanselmann
    "message",
2092 25ce3ec4 Michael Hanselmann
    "host",
2093 25ce3ec4 Michael Hanselmann
    "port",
2094 25ce3ec4 Michael Hanselmann
    "user",
2095 25ce3ec4 Michael Hanselmann
    "command",
2096 25ce3ec4 Michael Hanselmann
    "display",
2097 25ce3ec4 Michael Hanselmann
    ]
2098 25ce3ec4 Michael Hanselmann
2099 25ce3ec4 Michael Hanselmann
  def Validate(self):
2100 25ce3ec4 Michael Hanselmann
    """Validates contents of this object.
2101 25ce3ec4 Michael Hanselmann

2102 25ce3ec4 Michael Hanselmann
    """
2103 25ce3ec4 Michael Hanselmann
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2104 25ce3ec4 Michael Hanselmann
    assert self.instance, "Missing instance name"
2105 4d2cdb5a Andrea Spadaccini
    assert self.message or self.kind in [constants.CONS_SSH,
2106 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2107 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_VNC]
2108 25ce3ec4 Michael Hanselmann
    assert self.host or self.kind == constants.CONS_MESSAGE
2109 25ce3ec4 Michael Hanselmann
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2110 25ce3ec4 Michael Hanselmann
                                      constants.CONS_SSH]
2111 25ce3ec4 Michael Hanselmann
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2112 4d2cdb5a Andrea Spadaccini
                                      constants.CONS_SPICE,
2113 25ce3ec4 Michael Hanselmann
                                      constants.CONS_VNC]
2114 25ce3ec4 Michael Hanselmann
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2115 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2116 25ce3ec4 Michael Hanselmann
                                         constants.CONS_VNC]
2117 25ce3ec4 Michael Hanselmann
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2118 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2119 25ce3ec4 Michael Hanselmann
                                         constants.CONS_SSH]
2120 25ce3ec4 Michael Hanselmann
    return True
2121 25ce3ec4 Michael Hanselmann
2122 25ce3ec4 Michael Hanselmann
2123 8140e24f Dimitris Aragiorgis
class Network(TaggableObject):
2124 eaa4c57c Dimitris Aragiorgis
  """Object representing a network definition for ganeti.
2125 eaa4c57c Dimitris Aragiorgis

2126 eaa4c57c Dimitris Aragiorgis
  """
2127 eaa4c57c Dimitris Aragiorgis
  __slots__ = [
2128 eaa4c57c Dimitris Aragiorgis
    "name",
2129 eaa4c57c Dimitris Aragiorgis
    "serial_no",
2130 eaa4c57c Dimitris Aragiorgis
    "mac_prefix",
2131 eaa4c57c Dimitris Aragiorgis
    "network",
2132 eaa4c57c Dimitris Aragiorgis
    "network6",
2133 eaa4c57c Dimitris Aragiorgis
    "gateway",
2134 eaa4c57c Dimitris Aragiorgis
    "gateway6",
2135 eaa4c57c Dimitris Aragiorgis
    "reservations",
2136 eaa4c57c Dimitris Aragiorgis
    "ext_reservations",
2137 eaa4c57c Dimitris Aragiorgis
    ] + _TIMESTAMPS + _UUID
2138 eaa4c57c Dimitris Aragiorgis
2139 7e8f03e3 Dimitris Aragiorgis
  def HooksDict(self, prefix=""):
2140 d89168ff Guido Trotter
    """Export a dictionary used by hooks with a network's information.
2141 d89168ff Guido Trotter

2142 d89168ff Guido Trotter
    @type prefix: String
2143 d89168ff Guido Trotter
    @param prefix: Prefix to prepend to the dict entries
2144 d89168ff Guido Trotter

2145 d89168ff Guido Trotter
    """
2146 d89168ff Guido Trotter
    result = {
2147 7e8f03e3 Dimitris Aragiorgis
      "%sNETWORK_NAME" % prefix: self.name,
2148 d89168ff Guido Trotter
      "%sNETWORK_UUID" % prefix: self.uuid,
2149 5a76adf7 Dimitris Aragiorgis
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2150 d89168ff Guido Trotter
    }
2151 d89168ff Guido Trotter
    if self.network:
2152 d89168ff Guido Trotter
      result["%sNETWORK_SUBNET" % prefix] = self.network
2153 d89168ff Guido Trotter
    if self.gateway:
2154 d89168ff Guido Trotter
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2155 d89168ff Guido Trotter
    if self.network6:
2156 d89168ff Guido Trotter
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2157 d89168ff Guido Trotter
    if self.gateway6:
2158 d89168ff Guido Trotter
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2159 d89168ff Guido Trotter
    if self.mac_prefix:
2160 d89168ff Guido Trotter
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2161 d89168ff Guido Trotter
2162 d89168ff Guido Trotter
    return result
2163 d89168ff Guido Trotter
2164 5cfa6c37 Dimitris Aragiorgis
  @classmethod
2165 5cfa6c37 Dimitris Aragiorgis
  def FromDict(cls, val):
2166 5cfa6c37 Dimitris Aragiorgis
    """Custom function for networks.
2167 5cfa6c37 Dimitris Aragiorgis

2168 48616625 Dimitris Aragiorgis
    Remove deprecated network_type and family.
2169 5cfa6c37 Dimitris Aragiorgis

2170 5cfa6c37 Dimitris Aragiorgis
    """
2171 5cfa6c37 Dimitris Aragiorgis
    if "network_type" in val:
2172 5cfa6c37 Dimitris Aragiorgis
      del val["network_type"]
2173 48616625 Dimitris Aragiorgis
    if "family" in val:
2174 48616625 Dimitris Aragiorgis
      del val["family"]
2175 5cfa6c37 Dimitris Aragiorgis
    obj = super(Network, cls).FromDict(val)
2176 5cfa6c37 Dimitris Aragiorgis
    return obj
2177 5cfa6c37 Dimitris Aragiorgis
2178 eaa4c57c Dimitris Aragiorgis
2179 a8083063 Iustin Pop
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2180 a8083063 Iustin Pop
  """Simple wrapper over ConfigParse that allows serialization.
2181 a8083063 Iustin Pop

2182 a8083063 Iustin Pop
  This class is basically ConfigParser.SafeConfigParser with two
2183 a8083063 Iustin Pop
  additional methods that allow it to serialize/unserialize to/from a
2184 a8083063 Iustin Pop
  buffer.
2185 a8083063 Iustin Pop

2186 a8083063 Iustin Pop
  """
2187 a8083063 Iustin Pop
  def Dumps(self):
2188 a8083063 Iustin Pop
    """Dump this instance and return the string representation."""
2189 a8083063 Iustin Pop
    buf = StringIO()
2190 a8083063 Iustin Pop
    self.write(buf)
2191 a8083063 Iustin Pop
    return buf.getvalue()
2192 a8083063 Iustin Pop
2193 b39bf4bb Guido Trotter
  @classmethod
2194 b39bf4bb Guido Trotter
  def Loads(cls, data):
2195 a8083063 Iustin Pop
    """Load data from a string."""
2196 a8083063 Iustin Pop
    buf = StringIO(data)
2197 b39bf4bb Guido Trotter
    cfp = cls()
2198 a8083063 Iustin Pop
    cfp.readfp(buf)
2199 a8083063 Iustin Pop
    return cfp
2200 59726e15 Bernardo Dal Seno
2201 59726e15 Bernardo Dal Seno
2202 59726e15 Bernardo Dal Seno
class LvmPvInfo(ConfigObject):
2203 59726e15 Bernardo Dal Seno
  """Information about an LVM physical volume (PV).
2204 59726e15 Bernardo Dal Seno

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

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

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