Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ f3aebf6f

History | View | Annotate | Download (70.9 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 8a5d326f Jose A. Lopes
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 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 a5efec93 Santi Raffa
from ganeti import serializer
51 a8083063 Iustin Pop
52 f4c9af7a Guido Trotter
from socket import AF_INET
53 f4c9af7a Guido Trotter
54 a8083063 Iustin Pop
55 a8083063 Iustin Pop
__all__ = ["ConfigObject", "ConfigData", "NIC", "Disk", "Instance",
56 eaa4c57c Dimitris Aragiorgis
           "OS", "Node", "NodeGroup", "Cluster", "FillDict", "Network"]
57 a8083063 Iustin Pop
58 d693c864 Iustin Pop
_TIMESTAMPS = ["ctime", "mtime"]
59 e1dcc53a Iustin Pop
_UUID = ["uuid"]
60 96acbc09 Michael Hanselmann
61 8d8d650c Michael Hanselmann
62 e11ddf13 Iustin Pop
def FillDict(defaults_dict, custom_dict, skip_keys=None):
63 29921401 Iustin Pop
  """Basic function to apply settings on top a default dict.
64 abe609b2 Guido Trotter

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

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

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

101 af9fb4cc Renรฉ Nussbaumer
  @see: L{FillDict} for parameters and return value
102 57987785 Renรฉ Nussbaumer

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

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

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

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

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

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

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

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

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

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

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

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

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

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

215 adf385c7 Iustin Pop
    """
216 415feb2e Renรฉ Nussbaumer
217 a5efec93 Santi Raffa
  def ToDict(self, _with_private=False):
218 ff9c047c Iustin Pop
    """Convert to a dict holding only standard python types.
219 ff9c047c Iustin Pop

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

226 a5efec93 Santi Raffa
    Private fields can be included or not with the _with_private switch.
227 a5efec93 Santi Raffa
    The actual implementation of this switch is left for those subclassses
228 a5efec93 Santi Raffa
    with private fields to implement.
229 a5efec93 Santi Raffa

230 a5efec93 Santi Raffa
    @type _with_private: bool
231 a5efec93 Santi Raffa
    @param _with_private: if True, the object will leak its private fields in
232 a5efec93 Santi Raffa
                          the dictionary representation. If False, the values
233 a5efec93 Santi Raffa
                          will be replaced with None.
234 a5efec93 Santi Raffa

235 ff9c047c Iustin Pop
    """
236 4c14965f Guido Trotter
    result = {}
237 32683096 Renรฉ Nussbaumer
    for name in self.GetAllSlots():
238 4c14965f Guido Trotter
      value = getattr(self, name, None)
239 4c14965f Guido Trotter
      if value is not None:
240 4c14965f Guido Trotter
        result[name] = value
241 4c14965f Guido Trotter
    return result
242 4c14965f Guido Trotter
243 4c14965f Guido Trotter
  __getstate__ = ToDict
244 ff9c047c Iustin Pop
245 ff9c047c Iustin Pop
  @classmethod
246 ff9c047c Iustin Pop
  def FromDict(cls, val):
247 ff9c047c Iustin Pop
    """Create an object from a dictionary.
248 ff9c047c Iustin Pop

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

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

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

268 e8d563f3 Iustin Pop
    """
269 e8d563f3 Iustin Pop
    dict_form = self.ToDict()
270 e8d563f3 Iustin Pop
    clone_obj = self.__class__.FromDict(dict_form)
271 e8d563f3 Iustin Pop
    return clone_obj
272 e8d563f3 Iustin Pop
273 ff9c047c Iustin Pop
  def __repr__(self):
274 ff9c047c Iustin Pop
    """Implement __repr__ for ConfigObjects."""
275 ff9c047c Iustin Pop
    return repr(self.ToDict())
276 ff9c047c Iustin Pop
277 19830e88 Thomas Thrainer
  def __eq__(self, other):
278 19830e88 Thomas Thrainer
    """Implement __eq__ for ConfigObjects."""
279 19830e88 Thomas Thrainer
    return isinstance(other, self.__class__) and self.ToDict() == other.ToDict()
280 19830e88 Thomas Thrainer
281 560428be Guido Trotter
  def UpgradeConfig(self):
282 560428be Guido Trotter
    """Fill defaults for missing configuration values.
283 560428be Guido Trotter

284 90d726a8 Iustin Pop
    This method will be called at configuration load time, and its
285 90d726a8 Iustin Pop
    implementation will be object dependent.
286 560428be Guido Trotter

287 560428be Guido Trotter
    """
288 560428be Guido Trotter
    pass
289 560428be Guido Trotter
290 a8083063 Iustin Pop
291 ec29fe40 Iustin Pop
class TaggableObject(ConfigObject):
292 5c947f38 Iustin Pop
  """An generic class supporting tags.
293 5c947f38 Iustin Pop

294 5c947f38 Iustin Pop
  """
295 154b9580 Balazs Lecz
  __slots__ = ["tags"]
296 78f99abb Michele Tartara
  VALID_TAG_RE = re.compile(r"^[\w.+*/:@-]+$")
297 2057f6c7 Iustin Pop
298 b5e5632e Iustin Pop
  @classmethod
299 b5e5632e Iustin Pop
  def ValidateTag(cls, tag):
300 5c947f38 Iustin Pop
    """Check if a tag is valid.
301 5c947f38 Iustin Pop

302 5c947f38 Iustin Pop
    If the tag is invalid, an errors.TagError will be raised. The
303 5c947f38 Iustin Pop
    function has no return value.
304 5c947f38 Iustin Pop

305 5c947f38 Iustin Pop
    """
306 5c947f38 Iustin Pop
    if not isinstance(tag, basestring):
307 3ecf6786 Iustin Pop
      raise errors.TagError("Invalid tag type (not a string)")
308 5c947f38 Iustin Pop
    if len(tag) > constants.MAX_TAG_LEN:
309 319856a9 Michael Hanselmann
      raise errors.TagError("Tag too long (>%d characters)" %
310 319856a9 Michael Hanselmann
                            constants.MAX_TAG_LEN)
311 5c947f38 Iustin Pop
    if not tag:
312 3ecf6786 Iustin Pop
      raise errors.TagError("Tags cannot be empty")
313 b5e5632e Iustin Pop
    if not cls.VALID_TAG_RE.match(tag):
314 3ecf6786 Iustin Pop
      raise errors.TagError("Tag contains invalid characters")
315 5c947f38 Iustin Pop
316 5c947f38 Iustin Pop
  def GetTags(self):
317 5c947f38 Iustin Pop
    """Return the tags list.
318 5c947f38 Iustin Pop

319 5c947f38 Iustin Pop
    """
320 5c947f38 Iustin Pop
    tags = getattr(self, "tags", None)
321 5c947f38 Iustin Pop
    if tags is None:
322 5c947f38 Iustin Pop
      tags = self.tags = set()
323 5c947f38 Iustin Pop
    return tags
324 5c947f38 Iustin Pop
325 5c947f38 Iustin Pop
  def AddTag(self, tag):
326 5c947f38 Iustin Pop
    """Add a new tag.
327 5c947f38 Iustin Pop

328 5c947f38 Iustin Pop
    """
329 5c947f38 Iustin Pop
    self.ValidateTag(tag)
330 5c947f38 Iustin Pop
    tags = self.GetTags()
331 5c947f38 Iustin Pop
    if len(tags) >= constants.MAX_TAGS_PER_OBJ:
332 3ecf6786 Iustin Pop
      raise errors.TagError("Too many tags")
333 5c947f38 Iustin Pop
    self.GetTags().add(tag)
334 5c947f38 Iustin Pop
335 5c947f38 Iustin Pop
  def RemoveTag(self, tag):
336 5c947f38 Iustin Pop
    """Remove a tag.
337 5c947f38 Iustin Pop

338 5c947f38 Iustin Pop
    """
339 5c947f38 Iustin Pop
    self.ValidateTag(tag)
340 5c947f38 Iustin Pop
    tags = self.GetTags()
341 5c947f38 Iustin Pop
    try:
342 5c947f38 Iustin Pop
      tags.remove(tag)
343 5c947f38 Iustin Pop
    except KeyError:
344 3ecf6786 Iustin Pop
      raise errors.TagError("Tag not found")
345 5c947f38 Iustin Pop
346 a5efec93 Santi Raffa
  def ToDict(self, _with_private=False):
347 ff9c047c Iustin Pop
    """Taggable-object-specific conversion to standard python types.
348 ff9c047c Iustin Pop

349 ff9c047c Iustin Pop
    This replaces the tags set with a list.
350 ff9c047c Iustin Pop

351 ff9c047c Iustin Pop
    """
352 a5efec93 Santi Raffa
    bo = super(TaggableObject, self).ToDict(_with_private=_with_private)
353 ff9c047c Iustin Pop
354 ff9c047c Iustin Pop
    tags = bo.get("tags", None)
355 ff9c047c Iustin Pop
    if isinstance(tags, set):
356 ff9c047c Iustin Pop
      bo["tags"] = list(tags)
357 ff9c047c Iustin Pop
    return bo
358 ff9c047c Iustin Pop
359 ff9c047c Iustin Pop
  @classmethod
360 ff9c047c Iustin Pop
  def FromDict(cls, val):
361 ff9c047c Iustin Pop
    """Custom function for instances.
362 ff9c047c Iustin Pop

363 ff9c047c Iustin Pop
    """
364 ff9c047c Iustin Pop
    obj = super(TaggableObject, cls).FromDict(val)
365 ff9c047c Iustin Pop
    if hasattr(obj, "tags") and isinstance(obj.tags, list):
366 ff9c047c Iustin Pop
      obj.tags = set(obj.tags)
367 ff9c047c Iustin Pop
    return obj
368 ff9c047c Iustin Pop
369 5c947f38 Iustin Pop
370 061af273 Andrea Spadaccini
class MasterNetworkParameters(ConfigObject):
371 061af273 Andrea Spadaccini
  """Network configuration parameters for the master
372 061af273 Andrea Spadaccini

373 1c3231aa Thomas Thrainer
  @ivar uuid: master nodes UUID
374 061af273 Andrea Spadaccini
  @ivar ip: master IP
375 061af273 Andrea Spadaccini
  @ivar netmask: master netmask
376 061af273 Andrea Spadaccini
  @ivar netdev: master network device
377 061af273 Andrea Spadaccini
  @ivar ip_family: master IP family
378 061af273 Andrea Spadaccini

379 061af273 Andrea Spadaccini
  """
380 061af273 Andrea Spadaccini
  __slots__ = [
381 1c3231aa Thomas Thrainer
    "uuid",
382 061af273 Andrea Spadaccini
    "ip",
383 061af273 Andrea Spadaccini
    "netmask",
384 061af273 Andrea Spadaccini
    "netdev",
385 3c286190 Dimitris Aragiorgis
    "ip_family",
386 061af273 Andrea Spadaccini
    ]
387 061af273 Andrea Spadaccini
388 061af273 Andrea Spadaccini
389 a8083063 Iustin Pop
class ConfigData(ConfigObject):
390 a8083063 Iustin Pop
  """Top-level config object."""
391 3df43542 Guido Trotter
  __slots__ = [
392 3df43542 Guido Trotter
    "version",
393 3df43542 Guido Trotter
    "cluster",
394 3df43542 Guido Trotter
    "nodes",
395 3df43542 Guido Trotter
    "nodegroups",
396 3df43542 Guido Trotter
    "instances",
397 eaa4c57c Dimitris Aragiorgis
    "networks",
398 3df43542 Guido Trotter
    "serial_no",
399 3df43542 Guido Trotter
    ] + _TIMESTAMPS
400 a8083063 Iustin Pop
401 a5efec93 Santi Raffa
  def ToDict(self, _with_private=False):
402 ff9c047c Iustin Pop
    """Custom function for top-level config data.
403 ff9c047c Iustin Pop

404 ff9c047c Iustin Pop
    This just replaces the list of instances, nodes and the cluster
405 ff9c047c Iustin Pop
    with standard python types.
406 ff9c047c Iustin Pop

407 ff9c047c Iustin Pop
    """
408 a5efec93 Santi Raffa
    mydict = super(ConfigData, self).ToDict(_with_private=_with_private)
409 ff9c047c Iustin Pop
    mydict["cluster"] = mydict["cluster"].ToDict()
410 eaa4c57c Dimitris Aragiorgis
    for key in "nodes", "instances", "nodegroups", "networks":
411 fe502d25 Iustin Pop
      mydict[key] = outils.ContainerToDicts(mydict[key])
412 ff9c047c Iustin Pop
413 ff9c047c Iustin Pop
    return mydict
414 ff9c047c Iustin Pop
415 ff9c047c Iustin Pop
  @classmethod
416 ff9c047c Iustin Pop
  def FromDict(cls, val):
417 ff9c047c Iustin Pop
    """Custom function for top-level config data
418 ff9c047c Iustin Pop

419 ff9c047c Iustin Pop
    """
420 ff9c047c Iustin Pop
    obj = super(ConfigData, cls).FromDict(val)
421 ff9c047c Iustin Pop
    obj.cluster = Cluster.FromDict(obj.cluster)
422 fe502d25 Iustin Pop
    obj.nodes = outils.ContainerFromDicts(obj.nodes, dict, Node)
423 473ab806 Michael Hanselmann
    obj.instances = \
424 fe502d25 Iustin Pop
      outils.ContainerFromDicts(obj.instances, dict, Instance)
425 473ab806 Michael Hanselmann
    obj.nodegroups = \
426 fe502d25 Iustin Pop
      outils.ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
427 fe502d25 Iustin Pop
    obj.networks = outils.ContainerFromDicts(obj.networks, dict, Network)
428 ff9c047c Iustin Pop
    return obj
429 ff9c047c Iustin Pop
430 51cb1581 Luca Bigliardi
  def HasAnyDiskOfType(self, dev_type):
431 51cb1581 Luca Bigliardi
    """Check if in there is at disk of the given type in the configuration.
432 51cb1581 Luca Bigliardi

433 cd3b4ff4 Helga Velroyen
    @type dev_type: L{constants.DTS_BLOCK}
434 51cb1581 Luca Bigliardi
    @param dev_type: the type to look for
435 51cb1581 Luca Bigliardi
    @rtype: boolean
436 51cb1581 Luca Bigliardi
    @return: boolean indicating if a disk of the given type was found or not
437 51cb1581 Luca Bigliardi

438 51cb1581 Luca Bigliardi
    """
439 51cb1581 Luca Bigliardi
    for instance in self.instances.values():
440 51cb1581 Luca Bigliardi
      for disk in instance.disks:
441 51cb1581 Luca Bigliardi
        if disk.IsBasedOnDiskType(dev_type):
442 51cb1581 Luca Bigliardi
          return True
443 51cb1581 Luca Bigliardi
    return False
444 51cb1581 Luca Bigliardi
445 90d726a8 Iustin Pop
  def UpgradeConfig(self):
446 90d726a8 Iustin Pop
    """Fill defaults for missing configuration values.
447 90d726a8 Iustin Pop

448 90d726a8 Iustin Pop
    """
449 90d726a8 Iustin Pop
    self.cluster.UpgradeConfig()
450 90d726a8 Iustin Pop
    for node in self.nodes.values():
451 90d726a8 Iustin Pop
      node.UpgradeConfig()
452 90d726a8 Iustin Pop
    for instance in self.instances.values():
453 90d726a8 Iustin Pop
      instance.UpgradeConfig()
454 a2112db5 Helga Velroyen
    self._UpgradeEnabledDiskTemplates()
455 3df43542 Guido Trotter
    if self.nodegroups is None:
456 3df43542 Guido Trotter
      self.nodegroups = {}
457 3df43542 Guido Trotter
    for nodegroup in self.nodegroups.values():
458 3df43542 Guido Trotter
      nodegroup.UpgradeConfig()
459 a2112db5 Helga Velroyen
      InstancePolicy.UpgradeDiskTemplates(
460 a2112db5 Helga Velroyen
        nodegroup.ipolicy, self.cluster.enabled_disk_templates)
461 ee2f0ed4 Luca Bigliardi
    if self.cluster.drbd_usermode_helper is None:
462 25e5e785 Helga Velroyen
      if self.cluster.IsDiskTemplateEnabled(constants.DT_DRBD8):
463 ee2f0ed4 Luca Bigliardi
        self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
464 eaa4c57c Dimitris Aragiorgis
    if self.networks is None:
465 eaa4c57c Dimitris Aragiorgis
      self.networks = {}
466 ee9516c8 Guido Trotter
    for network in self.networks.values():
467 ee9516c8 Guido Trotter
      network.UpgradeConfig()
468 c66d8987 Helga Velroyen
469 1b02d7ef Helga Velroyen
  def _UpgradeEnabledDiskTemplates(self):
470 1b02d7ef Helga Velroyen
    """Upgrade the cluster's enabled disk templates by inspecting the currently
471 1b02d7ef Helga Velroyen
       enabled and/or used disk templates.
472 c66d8987 Helga Velroyen

473 c66d8987 Helga Velroyen
    """
474 1b02d7ef Helga Velroyen
    if not self.cluster.enabled_disk_templates:
475 1b02d7ef Helga Velroyen
      template_set = \
476 1b02d7ef Helga Velroyen
        set([inst.disk_template for inst in self.instances.values()])
477 1b02d7ef Helga Velroyen
      # Add drbd and plain, if lvm is enabled (by specifying a volume group)
478 c66d8987 Helga Velroyen
      if self.cluster.volume_group_name:
479 1b02d7ef Helga Velroyen
        template_set.add(constants.DT_DRBD8)
480 1b02d7ef Helga Velroyen
        template_set.add(constants.DT_PLAIN)
481 1b02d7ef Helga Velroyen
      # Set enabled_disk_templates to the inferred disk templates. Order them
482 c66d8987 Helga Velroyen
      # according to a preference list that is based on Ganeti's history of
483 1b02d7ef Helga Velroyen
      # supported disk templates.
484 1b02d7ef Helga Velroyen
      self.cluster.enabled_disk_templates = []
485 1b02d7ef Helga Velroyen
      for preferred_template in constants.DISK_TEMPLATE_PREFERENCE:
486 1b02d7ef Helga Velroyen
        if preferred_template in template_set:
487 1b02d7ef Helga Velroyen
          self.cluster.enabled_disk_templates.append(preferred_template)
488 1b02d7ef Helga Velroyen
          template_set.remove(preferred_template)
489 1b02d7ef Helga Velroyen
      self.cluster.enabled_disk_templates.extend(list(template_set))
490 a2112db5 Helga Velroyen
    InstancePolicy.UpgradeDiskTemplates(
491 a2112db5 Helga Velroyen
      self.cluster.ipolicy, self.cluster.enabled_disk_templates)
492 90d726a8 Iustin Pop
493 a8083063 Iustin Pop
494 a8083063 Iustin Pop
class NIC(ConfigObject):
495 a8083063 Iustin Pop
  """Config object representing a network card."""
496 9569d877 Dimitris Aragiorgis
  __slots__ = ["name", "mac", "ip", "network",
497 9569d877 Dimitris Aragiorgis
               "nicparams", "netinfo", "pci"] + _UUID
498 a8083063 Iustin Pop
499 255e19d4 Guido Trotter
  @classmethod
500 255e19d4 Guido Trotter
  def CheckParameterSyntax(cls, nicparams):
501 255e19d4 Guido Trotter
    """Check the given parameters for validity.
502 255e19d4 Guido Trotter

503 255e19d4 Guido Trotter
    @type nicparams:  dict
504 255e19d4 Guido Trotter
    @param nicparams: dictionary with parameter names/value
505 255e19d4 Guido Trotter
    @raise errors.ConfigurationError: when a parameter is not valid
506 255e19d4 Guido Trotter

507 255e19d4 Guido Trotter
    """
508 53258324 Michael Hanselmann
    mode = nicparams[constants.NIC_MODE]
509 53258324 Michael Hanselmann
    if (mode not in constants.NIC_VALID_MODES and
510 53258324 Michael Hanselmann
        mode != constants.VALUE_AUTO):
511 53258324 Michael Hanselmann
      raise errors.ConfigurationError("Invalid NIC mode '%s'" % mode)
512 255e19d4 Guido Trotter
513 53258324 Michael Hanselmann
    if (mode == constants.NIC_MODE_BRIDGED and
514 255e19d4 Guido Trotter
        not nicparams[constants.NIC_LINK]):
515 53258324 Michael Hanselmann
      raise errors.ConfigurationError("Missing bridged NIC link")
516 255e19d4 Guido Trotter
517 a8083063 Iustin Pop
518 a8083063 Iustin Pop
class Disk(ConfigObject):
519 a8083063 Iustin Pop
  """Config object representing a block device."""
520 a57e502a Thomas Thrainer
  __slots__ = (["name", "dev_type", "logical_id", "children", "iv_name",
521 9569d877 Dimitris Aragiorgis
                "size", "mode", "params", "spindles", "pci"] + _UUID +
522 0c3d9c7c Thomas Thrainer
               # dynamic_params is special. It depends on the node this instance
523 0c3d9c7c Thomas Thrainer
               # is sent to, and should not be persisted.
524 0c3d9c7c Thomas Thrainer
               ["dynamic_params"])
525 a8083063 Iustin Pop
526 a8083063 Iustin Pop
  def CreateOnSecondary(self):
527 a8083063 Iustin Pop
    """Test if this device needs to be created on a secondary node."""
528 cd3b4ff4 Helga Velroyen
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
529 a8083063 Iustin Pop
530 a8083063 Iustin Pop
  def AssembleOnSecondary(self):
531 a8083063 Iustin Pop
    """Test if this device needs to be assembled on a secondary node."""
532 cd3b4ff4 Helga Velroyen
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
533 a8083063 Iustin Pop
534 a8083063 Iustin Pop
  def OpenOnSecondary(self):
535 a8083063 Iustin Pop
    """Test if this device needs to be opened on a secondary node."""
536 cd3b4ff4 Helga Velroyen
    return self.dev_type in (constants.DT_PLAIN,)
537 a8083063 Iustin Pop
538 222f2dd5 Iustin Pop
  def StaticDevPath(self):
539 222f2dd5 Iustin Pop
    """Return the device path if this device type has a static one.
540 222f2dd5 Iustin Pop

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

545 e51db2a6 Iustin Pop
    @warning: The path returned is not a normalized pathname; callers
546 e51db2a6 Iustin Pop
        should check that it is a valid path.
547 e51db2a6 Iustin Pop

548 222f2dd5 Iustin Pop
    """
549 cd3b4ff4 Helga Velroyen
    if self.dev_type == constants.DT_PLAIN:
550 222f2dd5 Iustin Pop
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
551 cd3b4ff4 Helga Velroyen
    elif self.dev_type == constants.DT_BLOCK:
552 b6135bbc Apollon Oikonomopoulos
      return self.logical_id[1]
553 cd3b4ff4 Helga Velroyen
    elif self.dev_type == constants.DT_RBD:
554 7181fba0 Constantinos Venetsanopoulos
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
555 222f2dd5 Iustin Pop
    return None
556 222f2dd5 Iustin Pop
557 fc1dc9d7 Iustin Pop
  def ChildrenNeeded(self):
558 fc1dc9d7 Iustin Pop
    """Compute the needed number of children for activation.
559 fc1dc9d7 Iustin Pop

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

564 fc1dc9d7 Iustin Pop
    Currently, only DRBD8 supports diskless activation (therefore we
565 fc1dc9d7 Iustin Pop
    return 0), for all other we keep the previous semantics and return
566 fc1dc9d7 Iustin Pop
    -1.
567 fc1dc9d7 Iustin Pop

568 fc1dc9d7 Iustin Pop
    """
569 cd3b4ff4 Helga Velroyen
    if self.dev_type == constants.DT_DRBD8:
570 fc1dc9d7 Iustin Pop
      return 0
571 fc1dc9d7 Iustin Pop
    return -1
572 fc1dc9d7 Iustin Pop
573 51cb1581 Luca Bigliardi
  def IsBasedOnDiskType(self, dev_type):
574 51cb1581 Luca Bigliardi
    """Check if the disk or its children are based on the given type.
575 51cb1581 Luca Bigliardi

576 cd3b4ff4 Helga Velroyen
    @type dev_type: L{constants.DTS_BLOCK}
577 51cb1581 Luca Bigliardi
    @param dev_type: the type to look for
578 51cb1581 Luca Bigliardi
    @rtype: boolean
579 51cb1581 Luca Bigliardi
    @return: boolean indicating if a device of the given type was found or not
580 51cb1581 Luca Bigliardi

581 51cb1581 Luca Bigliardi
    """
582 51cb1581 Luca Bigliardi
    if self.children:
583 51cb1581 Luca Bigliardi
      for child in self.children:
584 51cb1581 Luca Bigliardi
        if child.IsBasedOnDiskType(dev_type):
585 51cb1581 Luca Bigliardi
          return True
586 51cb1581 Luca Bigliardi
    return self.dev_type == dev_type
587 51cb1581 Luca Bigliardi
588 1c3231aa Thomas Thrainer
  def GetNodes(self, node_uuid):
589 a8083063 Iustin Pop
    """This function returns the nodes this device lives on.
590 a8083063 Iustin Pop

591 a8083063 Iustin Pop
    Given the node on which the parent of the device lives on (or, in
592 a8083063 Iustin Pop
    case of a top-level device, the primary node of the devices'
593 a8083063 Iustin Pop
    instance), this function will return a list of nodes on which this
594 a8083063 Iustin Pop
    devices needs to (or can) be assembled.
595 a8083063 Iustin Pop

596 a8083063 Iustin Pop
    """
597 cd3b4ff4 Helga Velroyen
    if self.dev_type in [constants.DT_PLAIN, constants.DT_FILE,
598 cd3b4ff4 Helga Velroyen
                         constants.DT_BLOCK, constants.DT_RBD,
599 8106dd64 Santi Raffa
                         constants.DT_EXT, constants.DT_SHARED_FILE,
600 8106dd64 Santi Raffa
                         constants.DT_GLUSTER]:
601 1c3231aa Thomas Thrainer
      result = [node_uuid]
602 66a37e7a Helga Velroyen
    elif self.dev_type in constants.DTS_DRBD:
603 a8083063 Iustin Pop
      result = [self.logical_id[0], self.logical_id[1]]
604 1c3231aa Thomas Thrainer
      if node_uuid not in result:
605 3ecf6786 Iustin Pop
        raise errors.ConfigurationError("DRBD device passed unknown node")
606 a8083063 Iustin Pop
    else:
607 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
608 a8083063 Iustin Pop
    return result
609 a8083063 Iustin Pop
610 1c3231aa Thomas Thrainer
  def ComputeNodeTree(self, parent_node_uuid):
611 a8083063 Iustin Pop
    """Compute the node/disk tree for this disk and its children.
612 a8083063 Iustin Pop

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

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

648 6d33a6eb Iustin Pop
    This only works for VG-based disks.
649 6d33a6eb Iustin Pop

650 6d33a6eb Iustin Pop
    @type amount: integer
651 6d33a6eb Iustin Pop
    @param amount: the desired increase in (user-visible) disk space
652 6d33a6eb Iustin Pop
    @rtype: dict
653 6d33a6eb Iustin Pop
    @return: a dictionary of volume-groups and the required size
654 6d33a6eb Iustin Pop

655 6d33a6eb Iustin Pop
    """
656 cd3b4ff4 Helga Velroyen
    if self.dev_type == constants.DT_PLAIN:
657 6d33a6eb Iustin Pop
      return {self.logical_id[0]: amount}
658 cd3b4ff4 Helga Velroyen
    elif self.dev_type == constants.DT_DRBD8:
659 6d33a6eb Iustin Pop
      if self.children:
660 6d33a6eb Iustin Pop
        return self.children[0].ComputeGrowth(amount)
661 6d33a6eb Iustin Pop
      else:
662 6d33a6eb Iustin Pop
        return {}
663 6d33a6eb Iustin Pop
    else:
664 6d33a6eb Iustin Pop
      # Other disk types do not require VG space
665 6d33a6eb Iustin Pop
      return {}
666 6d33a6eb Iustin Pop
667 acec9d51 Iustin Pop
  def RecordGrow(self, amount):
668 acec9d51 Iustin Pop
    """Update the size of this disk after growth.
669 acec9d51 Iustin Pop

670 acec9d51 Iustin Pop
    This method recurses over the disks's children and updates their
671 acec9d51 Iustin Pop
    size correspondigly. The method needs to be kept in sync with the
672 acec9d51 Iustin Pop
    actual algorithms from bdev.
673 acec9d51 Iustin Pop

674 acec9d51 Iustin Pop
    """
675 cd3b4ff4 Helga Velroyen
    if self.dev_type in (constants.DT_PLAIN, constants.DT_FILE,
676 cd3b4ff4 Helga Velroyen
                         constants.DT_RBD, constants.DT_EXT,
677 8106dd64 Santi Raffa
                         constants.DT_SHARED_FILE, constants.DT_GLUSTER):
678 acec9d51 Iustin Pop
      self.size += amount
679 cd3b4ff4 Helga Velroyen
    elif self.dev_type == constants.DT_DRBD8:
680 acec9d51 Iustin Pop
      if self.children:
681 acec9d51 Iustin Pop
        self.children[0].RecordGrow(amount)
682 acec9d51 Iustin Pop
      self.size += amount
683 acec9d51 Iustin Pop
    else:
684 acec9d51 Iustin Pop
      raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
685 acec9d51 Iustin Pop
                                   " disk type %s" % self.dev_type)
686 acec9d51 Iustin Pop
687 b54ecf12 Bernardo Dal Seno
  def Update(self, size=None, mode=None, spindles=None):
688 b54ecf12 Bernardo Dal Seno
    """Apply changes to size, spindles and mode.
689 735e1318 Michael Hanselmann

690 735e1318 Michael Hanselmann
    """
691 cd3b4ff4 Helga Velroyen
    if self.dev_type == constants.DT_DRBD8:
692 735e1318 Michael Hanselmann
      if self.children:
693 735e1318 Michael Hanselmann
        self.children[0].Update(size=size, mode=mode)
694 735e1318 Michael Hanselmann
    else:
695 735e1318 Michael Hanselmann
      assert not self.children
696 735e1318 Michael Hanselmann
697 735e1318 Michael Hanselmann
    if size is not None:
698 735e1318 Michael Hanselmann
      self.size = size
699 735e1318 Michael Hanselmann
    if mode is not None:
700 735e1318 Michael Hanselmann
      self.mode = mode
701 b54ecf12 Bernardo Dal Seno
    if spindles is not None:
702 b54ecf12 Bernardo Dal Seno
      self.spindles = spindles
703 735e1318 Michael Hanselmann
704 a805ec18 Iustin Pop
  def UnsetSize(self):
705 a805ec18 Iustin Pop
    """Sets recursively the size to zero for the disk and its children.
706 a805ec18 Iustin Pop

707 a805ec18 Iustin Pop
    """
708 a805ec18 Iustin Pop
    if self.children:
709 a805ec18 Iustin Pop
      for child in self.children:
710 a805ec18 Iustin Pop
        child.UnsetSize()
711 a805ec18 Iustin Pop
    self.size = 0
712 a805ec18 Iustin Pop
713 0c3d9c7c Thomas Thrainer
  def UpdateDynamicDiskParams(self, target_node_uuid, nodes_ip):
714 0c3d9c7c Thomas Thrainer
    """Updates the dynamic disk params for the given node.
715 0402302c Iustin Pop

716 0c3d9c7c Thomas Thrainer
    This is mainly used for drbd, which needs ip/port configuration.
717 0402302c Iustin Pop

718 0402302c Iustin Pop
    Arguments:
719 1c3231aa Thomas Thrainer
      - target_node_uuid: the node UUID we wish to configure for
720 0402302c Iustin Pop
      - nodes_ip: a mapping of node name to ip
721 0402302c Iustin Pop

722 0c3d9c7c Thomas Thrainer
    The target_node must exist in nodes_ip, and should be one of the
723 0c3d9c7c Thomas Thrainer
    nodes in the logical ID if this device is a DRBD device.
724 0402302c Iustin Pop

725 0402302c Iustin Pop
    """
726 0402302c Iustin Pop
    if self.children:
727 0402302c Iustin Pop
      for child in self.children:
728 0c3d9c7c Thomas Thrainer
        child.UpdateDynamicDiskParams(target_node_uuid, nodes_ip)
729 0402302c Iustin Pop
730 0c3d9c7c Thomas Thrainer
    dyn_disk_params = {}
731 e8c86ab1 Klaus Aehlig
    if self.logical_id is not None and self.dev_type in constants.DTS_DRBD:
732 0c3d9c7c Thomas Thrainer
      pnode_uuid, snode_uuid, _, pminor, sminor, _ = self.logical_id
733 1c3231aa Thomas Thrainer
      if target_node_uuid not in (pnode_uuid, snode_uuid):
734 0c3d9c7c Thomas Thrainer
        # disk object is being sent to neither the primary nor the secondary
735 0c3d9c7c Thomas Thrainer
        # node. reset the dynamic parameters, the target node is not
736 0c3d9c7c Thomas Thrainer
        # supposed to use them.
737 0c3d9c7c Thomas Thrainer
        self.dynamic_params = dyn_disk_params
738 0c3d9c7c Thomas Thrainer
        return
739 0c3d9c7c Thomas Thrainer
740 1c3231aa Thomas Thrainer
      pnode_ip = nodes_ip.get(pnode_uuid, None)
741 1c3231aa Thomas Thrainer
      snode_ip = nodes_ip.get(snode_uuid, None)
742 0402302c Iustin Pop
      if pnode_ip is None or snode_ip is None:
743 0402302c Iustin Pop
        raise errors.ConfigurationError("Can't find primary or secondary node"
744 0402302c Iustin Pop
                                        " for %s" % str(self))
745 1c3231aa Thomas Thrainer
      if pnode_uuid == target_node_uuid:
746 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_LOCAL_IP] = pnode_ip
747 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_REMOTE_IP] = snode_ip
748 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_LOCAL_MINOR] = pminor
749 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_REMOTE_MINOR] = sminor
750 0402302c Iustin Pop
      else: # it must be secondary, we tested above
751 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_LOCAL_IP] = snode_ip
752 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_REMOTE_IP] = pnode_ip
753 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_LOCAL_MINOR] = sminor
754 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_REMOTE_MINOR] = pminor
755 0c3d9c7c Thomas Thrainer
756 0c3d9c7c Thomas Thrainer
    self.dynamic_params = dyn_disk_params
757 0402302c Iustin Pop
758 a0d2a91e Thomas Thrainer
  # pylint: disable=W0221
759 a5efec93 Santi Raffa
  def ToDict(self, include_dynamic_params=False,
760 a5efec93 Santi Raffa
             _with_private=False):
761 ff9c047c Iustin Pop
    """Disk-specific conversion to standard python types.
762 ff9c047c Iustin Pop

763 ff9c047c Iustin Pop
    This replaces the children lists of objects with lists of
764 ff9c047c Iustin Pop
    standard python types.
765 ff9c047c Iustin Pop

766 ff9c047c Iustin Pop
    """
767 ff9c047c Iustin Pop
    bo = super(Disk, self).ToDict()
768 a0d2a91e Thomas Thrainer
    if not include_dynamic_params and "dynamic_params" in bo:
769 a0d2a91e Thomas Thrainer
      del bo["dynamic_params"]
770 ff9c047c Iustin Pop
771 ff9c047c Iustin Pop
    for attr in ("children",):
772 ff9c047c Iustin Pop
      alist = bo.get(attr, None)
773 ff9c047c Iustin Pop
      if alist:
774 fe502d25 Iustin Pop
        bo[attr] = outils.ContainerToDicts(alist)
775 ff9c047c Iustin Pop
    return bo
776 ff9c047c Iustin Pop
777 ff9c047c Iustin Pop
  @classmethod
778 ff9c047c Iustin Pop
  def FromDict(cls, val):
779 ff9c047c Iustin Pop
    """Custom function for Disks
780 ff9c047c Iustin Pop

781 ff9c047c Iustin Pop
    """
782 ff9c047c Iustin Pop
    obj = super(Disk, cls).FromDict(val)
783 ff9c047c Iustin Pop
    if obj.children:
784 fe502d25 Iustin Pop
      obj.children = outils.ContainerFromDicts(obj.children, list, Disk)
785 ff9c047c Iustin Pop
    if obj.logical_id and isinstance(obj.logical_id, list):
786 ff9c047c Iustin Pop
      obj.logical_id = tuple(obj.logical_id)
787 66a37e7a Helga Velroyen
    if obj.dev_type in constants.DTS_DRBD:
788 f9518d38 Iustin Pop
      # we need a tuple of length six here
789 f9518d38 Iustin Pop
      if len(obj.logical_id) < 6:
790 f9518d38 Iustin Pop
        obj.logical_id += (None,) * (6 - len(obj.logical_id))
791 ff9c047c Iustin Pop
    return obj
792 ff9c047c Iustin Pop
793 65a15336 Iustin Pop
  def __str__(self):
794 65a15336 Iustin Pop
    """Custom str() formatter for disks.
795 65a15336 Iustin Pop

796 65a15336 Iustin Pop
    """
797 cd3b4ff4 Helga Velroyen
    if self.dev_type == constants.DT_PLAIN:
798 e687ec01 Michael Hanselmann
      val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
799 66a37e7a Helga Velroyen
    elif self.dev_type in constants.DTS_DRBD:
800 89f28b76 Iustin Pop
      node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
801 00fb8246 Michael Hanselmann
      val = "<DRBD8("
802 073ca59e Iustin Pop
803 a57e502a Thomas Thrainer
      val += ("hosts=%s/%d-%s/%d, port=%s, " %
804 a57e502a Thomas Thrainer
              (node_a, minor_a, node_b, minor_b, port))
805 65a15336 Iustin Pop
      if self.children and self.children.count(None) == 0:
806 65a15336 Iustin Pop
        val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
807 65a15336 Iustin Pop
      else:
808 65a15336 Iustin Pop
        val += "no local storage"
809 65a15336 Iustin Pop
    else:
810 a57e502a Thomas Thrainer
      val = ("<Disk(type=%s, logical_id=%s, children=%s" %
811 a57e502a Thomas Thrainer
             (self.dev_type, self.logical_id, self.children))
812 65a15336 Iustin Pop
    if self.iv_name is None:
813 65a15336 Iustin Pop
      val += ", not visible"
814 65a15336 Iustin Pop
    else:
815 65a15336 Iustin Pop
      val += ", visible as /dev/%s" % self.iv_name
816 b54ecf12 Bernardo Dal Seno
    if self.spindles is not None:
817 b54ecf12 Bernardo Dal Seno
      val += ", spindles=%s" % self.spindles
818 fd965830 Iustin Pop
    if isinstance(self.size, int):
819 fd965830 Iustin Pop
      val += ", size=%dm)>" % self.size
820 fd965830 Iustin Pop
    else:
821 fd965830 Iustin Pop
      val += ", size='%s')>" % (self.size,)
822 65a15336 Iustin Pop
    return val
823 65a15336 Iustin Pop
824 332d0e37 Iustin Pop
  def Verify(self):
825 332d0e37 Iustin Pop
    """Checks that this disk is correctly configured.
826 332d0e37 Iustin Pop

827 332d0e37 Iustin Pop
    """
828 7c4d6c7b Michael Hanselmann
    all_errors = []
829 332d0e37 Iustin Pop
    if self.mode not in constants.DISK_ACCESS_SET:
830 7c4d6c7b Michael Hanselmann
      all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
831 7c4d6c7b Michael Hanselmann
    return all_errors
832 332d0e37 Iustin Pop
833 90d726a8 Iustin Pop
  def UpgradeConfig(self):
834 90d726a8 Iustin Pop
    """Fill defaults for missing configuration values.
835 90d726a8 Iustin Pop

836 90d726a8 Iustin Pop
    """
837 90d726a8 Iustin Pop
    if self.children:
838 90d726a8 Iustin Pop
      for child in self.children:
839 90d726a8 Iustin Pop
        child.UpgradeConfig()
840 bc5d0215 Andrea Spadaccini
841 cce46164 Renรฉ Nussbaumer
    # FIXME: Make this configurable in Ganeti 2.7
842 54666867 Dimitris Aragiorgis
    # Params should be an empty dict that gets filled any time needed
843 54666867 Dimitris Aragiorgis
    # In case of ext template we allow arbitrary params that should not
844 54666867 Dimitris Aragiorgis
    # be overrided during a config reload/upgrade.
845 54666867 Dimitris Aragiorgis
    if not self.params or not isinstance(self.params, dict):
846 54666867 Dimitris Aragiorgis
      self.params = {}
847 54666867 Dimitris Aragiorgis
848 90d726a8 Iustin Pop
    # add here config upgrade for this disk
849 90d726a8 Iustin Pop
850 73d6b4a7 Helga Velroyen
    # map of legacy device types (mapping differing LD constants to new
851 73d6b4a7 Helga Velroyen
    # DT constants)
852 73d6b4a7 Helga Velroyen
    LEG_DEV_TYPE_MAP = {"lvm": constants.DT_PLAIN, "drbd8": constants.DT_DRBD8}
853 73d6b4a7 Helga Velroyen
    if self.dev_type in LEG_DEV_TYPE_MAP:
854 73d6b4a7 Helga Velroyen
      self.dev_type = LEG_DEV_TYPE_MAP[self.dev_type]
855 73d6b4a7 Helga Velroyen
856 cd46491f Renรฉ Nussbaumer
  @staticmethod
857 cd46491f Renรฉ Nussbaumer
  def ComputeLDParams(disk_template, disk_params):
858 cd46491f Renรฉ Nussbaumer
    """Computes Logical Disk parameters from Disk Template parameters.
859 cd46491f Renรฉ Nussbaumer

860 cd46491f Renรฉ Nussbaumer
    @type disk_template: string
861 cd46491f Renรฉ Nussbaumer
    @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
862 cd46491f Renรฉ Nussbaumer
    @type disk_params: dict
863 cd46491f Renรฉ Nussbaumer
    @param disk_params: disk template parameters;
864 cd46491f Renรฉ Nussbaumer
                        dict(template_name -> parameters
865 cd46491f Renรฉ Nussbaumer
    @rtype: list(dict)
866 cd46491f Renรฉ Nussbaumer
    @return: a list of dicts, one for each node of the disk hierarchy. Each dict
867 cd46491f Renรฉ Nussbaumer
      contains the LD parameters of the node. The tree is flattened in-order.
868 cd46491f Renรฉ Nussbaumer

869 cd46491f Renรฉ Nussbaumer
    """
870 cd46491f Renรฉ Nussbaumer
    if disk_template not in constants.DISK_TEMPLATES:
871 cd46491f Renรฉ Nussbaumer
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
872 cd46491f Renรฉ Nussbaumer
873 cd46491f Renรฉ Nussbaumer
    assert disk_template in disk_params
874 cd46491f Renรฉ Nussbaumer
875 cd46491f Renรฉ Nussbaumer
    result = list()
876 cd46491f Renรฉ Nussbaumer
    dt_params = disk_params[disk_template]
877 3fffa0c6 Santi Raffa
878 cd46491f Renรฉ Nussbaumer
    if disk_template == constants.DT_DRBD8:
879 6da90c0a Helga Velroyen
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_DRBD8], {
880 cd46491f Renรฉ Nussbaumer
        constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
881 cd46491f Renรฉ Nussbaumer
        constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
882 cd46491f Renรฉ Nussbaumer
        constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
883 cd46491f Renรฉ Nussbaumer
        constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
884 cd46491f Renรฉ Nussbaumer
        constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
885 cd46491f Renรฉ Nussbaumer
        constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
886 65fc2388 Thomas Thrainer
        constants.LDP_PROTOCOL: dt_params[constants.DRBD_PROTOCOL],
887 cd46491f Renรฉ Nussbaumer
        constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
888 cd46491f Renรฉ Nussbaumer
        constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
889 cd46491f Renรฉ Nussbaumer
        constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
890 cd46491f Renรฉ Nussbaumer
        constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
891 cd46491f Renรฉ Nussbaumer
        constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
892 cd46491f Renรฉ Nussbaumer
        constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
893 52f93ffd Michael Hanselmann
        }))
894 cd46491f Renรฉ Nussbaumer
895 cd46491f Renรฉ Nussbaumer
      # data LV
896 6da90c0a Helga Velroyen
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
897 cd46491f Renรฉ Nussbaumer
        constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
898 52f93ffd Michael Hanselmann
        }))
899 cd46491f Renรฉ Nussbaumer
900 cd46491f Renรฉ Nussbaumer
      # metadata LV
901 6da90c0a Helga Velroyen
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
902 cd46491f Renรฉ Nussbaumer
        constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
903 52f93ffd Michael Hanselmann
        }))
904 52f93ffd Michael Hanselmann
905 3fffa0c6 Santi Raffa
    else:
906 3fffa0c6 Santi Raffa
      defaults = constants.DISK_LD_DEFAULTS[disk_template]
907 3fffa0c6 Santi Raffa
      values = {}
908 3fffa0c6 Santi Raffa
      for field in defaults:
909 3fffa0c6 Santi Raffa
        values[field] = dt_params[field]
910 3fffa0c6 Santi Raffa
      result.append(FillDict(defaults, values))
911 938adc87 Constantinos Venetsanopoulos
912 cd46491f Renรฉ Nussbaumer
    return result
913 cd46491f Renรฉ Nussbaumer
914 a8083063 Iustin Pop
915 918eb80b Agata Murawska
class InstancePolicy(ConfigObject):
916 ffa339ca Iustin Pop
  """Config object representing instance policy limits dictionary.
917 918eb80b Agata Murawska

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

921 ffa339ca Iustin Pop
  """
922 918eb80b Agata Murawska
  @classmethod
923 a2112db5 Helga Velroyen
  def UpgradeDiskTemplates(cls, ipolicy, enabled_disk_templates):
924 a2112db5 Helga Velroyen
    """Upgrades the ipolicy configuration."""
925 a2112db5 Helga Velroyen
    if constants.IPOLICY_DTS in ipolicy:
926 a2112db5 Helga Velroyen
      if not set(ipolicy[constants.IPOLICY_DTS]).issubset(
927 a2112db5 Helga Velroyen
        set(enabled_disk_templates)):
928 a2112db5 Helga Velroyen
        ipolicy[constants.IPOLICY_DTS] = list(
929 a2112db5 Helga Velroyen
          set(ipolicy[constants.IPOLICY_DTS]) & set(enabled_disk_templates))
930 a2112db5 Helga Velroyen
931 a2112db5 Helga Velroyen
  @classmethod
932 8b057218 Renรฉ Nussbaumer
  def CheckParameterSyntax(cls, ipolicy, check_std):
933 918eb80b Agata Murawska
    """ Check the instance policy for validity.
934 918eb80b Agata Murawska

935 da5f09ef Bernardo Dal Seno
    @type ipolicy: dict
936 da5f09ef Bernardo Dal Seno
    @param ipolicy: dictionary with min/max/std specs and policies
937 da5f09ef Bernardo Dal Seno
    @type check_std: bool
938 da5f09ef Bernardo Dal Seno
    @param check_std: Whether to check std value or just assume compliance
939 da5f09ef Bernardo Dal Seno
    @raise errors.ConfigurationError: when the policy is not legal
940 da5f09ef Bernardo Dal Seno

941 918eb80b Agata Murawska
    """
942 62fed51b Bernardo Dal Seno
    InstancePolicy.CheckISpecSyntax(ipolicy, check_std)
943 d04c9d45 Iustin Pop
    if constants.IPOLICY_DTS in ipolicy:
944 d04c9d45 Iustin Pop
      InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
945 ff6c5e55 Iustin Pop
    for key in constants.IPOLICY_PARAMETERS:
946 ff6c5e55 Iustin Pop
      if key in ipolicy:
947 ff6c5e55 Iustin Pop
        InstancePolicy.CheckParameter(key, ipolicy[key])
948 57dc299a Iustin Pop
    wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
949 57dc299a Iustin Pop
    if wrong_keys:
950 57dc299a Iustin Pop
      raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
951 57dc299a Iustin Pop
                                      utils.CommaJoin(wrong_keys))
952 918eb80b Agata Murawska
953 918eb80b Agata Murawska
  @classmethod
954 0f511c8a Bernardo Dal Seno
  def _CheckIncompleteSpec(cls, spec, keyname):
955 0f511c8a Bernardo Dal Seno
    missing_params = constants.ISPECS_PARAMETERS - frozenset(spec.keys())
956 0f511c8a Bernardo Dal Seno
    if missing_params:
957 0f511c8a Bernardo Dal Seno
      msg = ("Missing instance specs parameters for %s: %s" %
958 0f511c8a Bernardo Dal Seno
             (keyname, utils.CommaJoin(missing_params)))
959 0f511c8a Bernardo Dal Seno
      raise errors.ConfigurationError(msg)
960 0f511c8a Bernardo Dal Seno
961 0f511c8a Bernardo Dal Seno
  @classmethod
962 62fed51b Bernardo Dal Seno
  def CheckISpecSyntax(cls, ipolicy, check_std):
963 62fed51b Bernardo Dal Seno
    """Check the instance policy specs for validity.
964 62fed51b Bernardo Dal Seno

965 62fed51b Bernardo Dal Seno
    @type ipolicy: dict
966 62fed51b Bernardo Dal Seno
    @param ipolicy: dictionary with min/max/std specs
967 62fed51b Bernardo Dal Seno
    @type check_std: bool
968 62fed51b Bernardo Dal Seno
    @param check_std: Whether to check std value or just assume compliance
969 62fed51b Bernardo Dal Seno
    @raise errors.ConfigurationError: when specs are not valid
970 62fed51b Bernardo Dal Seno

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

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

1010 da5f09ef Bernardo Dal Seno
    @type minmaxspecs: dict
1011 da5f09ef Bernardo Dal Seno
    @param minmaxspecs: dictionary with min and max instance spec
1012 da5f09ef Bernardo Dal Seno
    @type stdspec: dict
1013 da5f09ef Bernardo Dal Seno
    @param stdspec: dictionary with standard instance spec
1014 918eb80b Agata Murawska
    @type name: string
1015 918eb80b Agata Murawska
    @param name: what are the limits for
1016 8b057218 Renรฉ Nussbaumer
    @type check_std: bool
1017 8b057218 Renรฉ Nussbaumer
    @param check_std: Whether to check std value or just assume compliance
1018 b342c9dd Bernardo Dal Seno
    @rtype: bool
1019 b342c9dd Bernardo Dal Seno
    @return: C{True} when specs are valid, C{False} when standard spec for the
1020 b342c9dd Bernardo Dal Seno
        given name is not valid
1021 b342c9dd Bernardo Dal Seno
    @raise errors.ConfigurationError: when min/max specs for the given name
1022 b342c9dd Bernardo Dal Seno
        are not valid
1023 918eb80b Agata Murawska

1024 918eb80b Agata Murawska
    """
1025 da5f09ef Bernardo Dal Seno
    minspec = minmaxspecs[constants.ISPECS_MIN]
1026 da5f09ef Bernardo Dal Seno
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1027 0f511c8a Bernardo Dal Seno
    min_v = minspec[name]
1028 b342c9dd Bernardo Dal Seno
    max_v = maxspec[name]
1029 8b057218 Renรฉ Nussbaumer
1030 b342c9dd Bernardo Dal Seno
    if min_v > max_v:
1031 b342c9dd Bernardo Dal Seno
      err = ("Invalid specification of min/max values for %s: %s/%s" %
1032 b342c9dd Bernardo Dal Seno
             (name, min_v, max_v))
1033 b342c9dd Bernardo Dal Seno
      raise errors.ConfigurationError(err)
1034 b342c9dd Bernardo Dal Seno
    elif check_std:
1035 da5f09ef Bernardo Dal Seno
      std_v = stdspec.get(name, min_v)
1036 b342c9dd Bernardo Dal Seno
      return std_v >= min_v and std_v <= max_v
1037 8b057218 Renรฉ Nussbaumer
    else:
1038 b342c9dd Bernardo Dal Seno
      return True
1039 918eb80b Agata Murawska
1040 2cc673a3 Iustin Pop
  @classmethod
1041 2cc673a3 Iustin Pop
  def CheckDiskTemplates(cls, disk_templates):
1042 2cc673a3 Iustin Pop
    """Checks the disk templates for validity.
1043 2cc673a3 Iustin Pop

1044 2cc673a3 Iustin Pop
    """
1045 ba5c6c6b Bernardo Dal Seno
    if not disk_templates:
1046 ba5c6c6b Bernardo Dal Seno
      raise errors.ConfigurationError("Instance policy must contain" +
1047 ba5c6c6b Bernardo Dal Seno
                                      " at least one disk template")
1048 2cc673a3 Iustin Pop
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1049 2cc673a3 Iustin Pop
    if wrong:
1050 2cc673a3 Iustin Pop
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1051 2cc673a3 Iustin Pop
                                      utils.CommaJoin(wrong))
1052 2cc673a3 Iustin Pop
1053 ff6c5e55 Iustin Pop
  @classmethod
1054 ff6c5e55 Iustin Pop
  def CheckParameter(cls, key, value):
1055 ff6c5e55 Iustin Pop
    """Checks a parameter.
1056 ff6c5e55 Iustin Pop

1057 ff6c5e55 Iustin Pop
    Currently we expect all parameters to be float values.
1058 ff6c5e55 Iustin Pop

1059 ff6c5e55 Iustin Pop
    """
1060 ff6c5e55 Iustin Pop
    try:
1061 ff6c5e55 Iustin Pop
      float(value)
1062 ff6c5e55 Iustin Pop
    except (TypeError, ValueError), err:
1063 ff6c5e55 Iustin Pop
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1064 ff6c5e55 Iustin Pop
                                      " '%s', error: %s" % (key, value, err))
1065 ff6c5e55 Iustin Pop
1066 918eb80b Agata Murawska
1067 ec29fe40 Iustin Pop
class Instance(TaggableObject):
1068 a8083063 Iustin Pop
  """Config object representing an instance."""
1069 154b9580 Balazs Lecz
  __slots__ = [
1070 a8083063 Iustin Pop
    "name",
1071 a8083063 Iustin Pop
    "primary_node",
1072 a8083063 Iustin Pop
    "os",
1073 e69d05fd Iustin Pop
    "hypervisor",
1074 5bf7b5cf Iustin Pop
    "hvparams",
1075 5bf7b5cf Iustin Pop
    "beparams",
1076 1bdcbbab Iustin Pop
    "osparams",
1077 a5efec93 Santi Raffa
    "osparams_private",
1078 9ca8a7c5 Agata Murawska
    "admin_state",
1079 a8083063 Iustin Pop
    "nics",
1080 a8083063 Iustin Pop
    "disks",
1081 a8083063 Iustin Pop
    "disk_template",
1082 1d4a4b26 Thomas Thrainer
    "disks_active",
1083 58acb49d Alexander Schreiber
    "network_port",
1084 be1fa613 Iustin Pop
    "serial_no",
1085 e1dcc53a Iustin Pop
    ] + _TIMESTAMPS + _UUID
1086 a8083063 Iustin Pop
1087 a8083063 Iustin Pop
  def _ComputeSecondaryNodes(self):
1088 a8083063 Iustin Pop
    """Compute the list of secondary nodes.
1089 a8083063 Iustin Pop

1090 cfcc5c6d Iustin Pop
    This is a simple wrapper over _ComputeAllNodes.
1091 cfcc5c6d Iustin Pop

1092 cfcc5c6d Iustin Pop
    """
1093 cfcc5c6d Iustin Pop
    all_nodes = set(self._ComputeAllNodes())
1094 cfcc5c6d Iustin Pop
    all_nodes.discard(self.primary_node)
1095 cfcc5c6d Iustin Pop
    return tuple(all_nodes)
1096 cfcc5c6d Iustin Pop
1097 cfcc5c6d Iustin Pop
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1098 05325a35 Bernardo Dal Seno
                             "List of names of secondary nodes")
1099 cfcc5c6d Iustin Pop
1100 cfcc5c6d Iustin Pop
  def _ComputeAllNodes(self):
1101 cfcc5c6d Iustin Pop
    """Compute the list of all nodes.
1102 cfcc5c6d Iustin Pop

1103 a8083063 Iustin Pop
    Since the data is already there (in the drbd disks), keeping it as
1104 a8083063 Iustin Pop
    a separate normal attribute is redundant and if not properly
1105 a8083063 Iustin Pop
    synchronised can cause problems. Thus it's better to compute it
1106 a8083063 Iustin Pop
    dynamically.
1107 a8083063 Iustin Pop

1108 a8083063 Iustin Pop
    """
1109 cfcc5c6d Iustin Pop
    def _Helper(nodes, device):
1110 cfcc5c6d Iustin Pop
      """Recursively computes nodes given a top device."""
1111 66a37e7a Helga Velroyen
      if device.dev_type in constants.DTS_DRBD:
1112 cfcc5c6d Iustin Pop
        nodea, nodeb = device.logical_id[:2]
1113 cfcc5c6d Iustin Pop
        nodes.add(nodea)
1114 cfcc5c6d Iustin Pop
        nodes.add(nodeb)
1115 a8083063 Iustin Pop
      if device.children:
1116 a8083063 Iustin Pop
        for child in device.children:
1117 cfcc5c6d Iustin Pop
          _Helper(nodes, child)
1118 a8083063 Iustin Pop
1119 cfcc5c6d Iustin Pop
    all_nodes = set()
1120 a8083063 Iustin Pop
    for device in self.disks:
1121 cfcc5c6d Iustin Pop
      _Helper(all_nodes, device)
1122 f2a3c4f0 Petr Pudlak
    # ensure that the primary node is always the first
1123 f2a3c4f0 Petr Pudlak
    all_nodes.discard(self.primary_node)
1124 f2a3c4f0 Petr Pudlak
    return (self.primary_node, ) + tuple(all_nodes)
1125 a8083063 Iustin Pop
1126 cfcc5c6d Iustin Pop
  all_nodes = property(_ComputeAllNodes, None, None,
1127 05325a35 Bernardo Dal Seno
                       "List of names of all the nodes of the instance")
1128 a8083063 Iustin Pop
1129 843094ad Thomas Thrainer
  def MapLVsByNode(self, lvmap=None, devs=None, node_uuid=None):
1130 a8083063 Iustin Pop
    """Provide a mapping of nodes to LVs this instance owns.
1131 a8083063 Iustin Pop

1132 c41eea6e Iustin Pop
    This function figures out what logical volumes should belong on
1133 c41eea6e Iustin Pop
    which nodes, recursing through a device tree.
1134 a8083063 Iustin Pop

1135 843094ad Thomas Thrainer
    @type lvmap: dict
1136 c41eea6e Iustin Pop
    @param lvmap: optional dictionary to receive the
1137 c41eea6e Iustin Pop
        'node' : ['lv', ...] data.
1138 843094ad Thomas Thrainer
    @type devs: list of L{Disk}
1139 843094ad Thomas Thrainer
    @param devs: disks to get the LV name for. If None, all disk of this
1140 843094ad Thomas Thrainer
        instance are used.
1141 843094ad Thomas Thrainer
    @type node_uuid: string
1142 843094ad Thomas Thrainer
    @param node_uuid: UUID of the node to get the LV names for. If None, the
1143 843094ad Thomas Thrainer
        primary node of this instance is used.
1144 84d7e26b Dmitry Chernyak
    @return: None if lvmap arg is given, otherwise, a dictionary of
1145 1c3231aa Thomas Thrainer
        the form { 'node_uuid' : ['volume1', 'volume2', ...], ... };
1146 84d7e26b Dmitry Chernyak
        volumeN is of the form "vg_name/lv_name", compatible with
1147 84d7e26b Dmitry Chernyak
        GetVolumeList()
1148 a8083063 Iustin Pop

1149 a8083063 Iustin Pop
    """
1150 843094ad Thomas Thrainer
    if node_uuid is None:
1151 843094ad Thomas Thrainer
      node_uuid = self.primary_node
1152 a8083063 Iustin Pop
1153 a8083063 Iustin Pop
    if lvmap is None:
1154 e687ec01 Michael Hanselmann
      lvmap = {
1155 843094ad Thomas Thrainer
        node_uuid: [],
1156 e687ec01 Michael Hanselmann
        }
1157 a8083063 Iustin Pop
      ret = lvmap
1158 a8083063 Iustin Pop
    else:
1159 843094ad Thomas Thrainer
      if not node_uuid in lvmap:
1160 843094ad Thomas Thrainer
        lvmap[node_uuid] = []
1161 a8083063 Iustin Pop
      ret = None
1162 a8083063 Iustin Pop
1163 a8083063 Iustin Pop
    if not devs:
1164 a8083063 Iustin Pop
      devs = self.disks
1165 a8083063 Iustin Pop
1166 a8083063 Iustin Pop
    for dev in devs:
1167 cd3b4ff4 Helga Velroyen
      if dev.dev_type == constants.DT_PLAIN:
1168 843094ad Thomas Thrainer
        lvmap[node_uuid].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1169 a8083063 Iustin Pop
1170 66a37e7a Helga Velroyen
      elif dev.dev_type in constants.DTS_DRBD:
1171 a8083063 Iustin Pop
        if dev.children:
1172 a8083063 Iustin Pop
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1173 a8083063 Iustin Pop
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1174 a8083063 Iustin Pop
1175 a8083063 Iustin Pop
      elif dev.children:
1176 843094ad Thomas Thrainer
        self.MapLVsByNode(lvmap, dev.children, node_uuid)
1177 a8083063 Iustin Pop
1178 a8083063 Iustin Pop
    return ret
1179 a8083063 Iustin Pop
1180 ad24e046 Iustin Pop
  def FindDisk(self, idx):
1181 ad24e046 Iustin Pop
    """Find a disk given having a specified index.
1182 644eeef9 Iustin Pop

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

1185 ad24e046 Iustin Pop
    @type idx: int
1186 ad24e046 Iustin Pop
    @param idx: the disk index
1187 ad24e046 Iustin Pop
    @rtype: L{Disk}
1188 ad24e046 Iustin Pop
    @return: the corresponding disk
1189 ad24e046 Iustin Pop
    @raise errors.OpPrereqError: when the given index is not valid
1190 644eeef9 Iustin Pop

1191 ad24e046 Iustin Pop
    """
1192 ad24e046 Iustin Pop
    try:
1193 ad24e046 Iustin Pop
      idx = int(idx)
1194 ad24e046 Iustin Pop
      return self.disks[idx]
1195 691744c4 Iustin Pop
    except (TypeError, ValueError), err:
1196 debac808 Iustin Pop
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1197 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
1198 ad24e046 Iustin Pop
    except IndexError:
1199 ad24e046 Iustin Pop
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1200 daa55b04 Michael Hanselmann
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1201 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
1202 644eeef9 Iustin Pop
1203 a5efec93 Santi Raffa
  def ToDict(self, _with_private=False):
1204 ff9c047c Iustin Pop
    """Instance-specific conversion to standard python types.
1205 ff9c047c Iustin Pop

1206 ff9c047c Iustin Pop
    This replaces the children lists of objects with lists of standard
1207 ff9c047c Iustin Pop
    python types.
1208 ff9c047c Iustin Pop

1209 ff9c047c Iustin Pop
    """
1210 a5efec93 Santi Raffa
    bo = super(Instance, self).ToDict(_with_private=_with_private)
1211 a5efec93 Santi Raffa
1212 a5efec93 Santi Raffa
    if _with_private:
1213 a5efec93 Santi Raffa
      bo["osparams_private"] = self.osparams_private.Unprivate()
1214 ff9c047c Iustin Pop
1215 ff9c047c Iustin Pop
    for attr in "nics", "disks":
1216 ff9c047c Iustin Pop
      alist = bo.get(attr, None)
1217 ff9c047c Iustin Pop
      if alist:
1218 fe502d25 Iustin Pop
        nlist = outils.ContainerToDicts(alist)
1219 ff9c047c Iustin Pop
      else:
1220 ff9c047c Iustin Pop
        nlist = []
1221 ff9c047c Iustin Pop
      bo[attr] = nlist
1222 ff9c047c Iustin Pop
    return bo
1223 ff9c047c Iustin Pop
1224 ff9c047c Iustin Pop
  @classmethod
1225 ff9c047c Iustin Pop
  def FromDict(cls, val):
1226 ff9c047c Iustin Pop
    """Custom function for instances.
1227 ff9c047c Iustin Pop

1228 ff9c047c Iustin Pop
    """
1229 9ca8a7c5 Agata Murawska
    if "admin_state" not in val:
1230 9ca8a7c5 Agata Murawska
      if val.get("admin_up", False):
1231 9ca8a7c5 Agata Murawska
        val["admin_state"] = constants.ADMINST_UP
1232 9ca8a7c5 Agata Murawska
      else:
1233 9ca8a7c5 Agata Murawska
        val["admin_state"] = constants.ADMINST_DOWN
1234 9ca8a7c5 Agata Murawska
    if "admin_up" in val:
1235 9ca8a7c5 Agata Murawska
      del val["admin_up"]
1236 ff9c047c Iustin Pop
    obj = super(Instance, cls).FromDict(val)
1237 fe502d25 Iustin Pop
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1238 fe502d25 Iustin Pop
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1239 ff9c047c Iustin Pop
    return obj
1240 ff9c047c Iustin Pop
1241 90d726a8 Iustin Pop
  def UpgradeConfig(self):
1242 90d726a8 Iustin Pop
    """Fill defaults for missing configuration values.
1243 90d726a8 Iustin Pop

1244 90d726a8 Iustin Pop
    """
1245 90d726a8 Iustin Pop
    for nic in self.nics:
1246 90d726a8 Iustin Pop
      nic.UpgradeConfig()
1247 90d726a8 Iustin Pop
    for disk in self.disks:
1248 90d726a8 Iustin Pop
      disk.UpgradeConfig()
1249 7736a5f2 Iustin Pop
    if self.hvparams:
1250 7736a5f2 Iustin Pop
      for key in constants.HVC_GLOBALS:
1251 7736a5f2 Iustin Pop
        try:
1252 7736a5f2 Iustin Pop
          del self.hvparams[key]
1253 7736a5f2 Iustin Pop
        except KeyError:
1254 7736a5f2 Iustin Pop
          pass
1255 1bdcbbab Iustin Pop
    if self.osparams is None:
1256 1bdcbbab Iustin Pop
      self.osparams = {}
1257 a5efec93 Santi Raffa
    if self.osparams_private is None:
1258 a5efec93 Santi Raffa
      self.osparams_private = serializer.PrivateDict()
1259 8c72ab2b Guido Trotter
    UpgradeBeParams(self.beparams)
1260 a8e07057 Thomas Thrainer
    if self.disks_active is None:
1261 a8e07057 Thomas Thrainer
      self.disks_active = self.admin_state == constants.ADMINST_UP
1262 90d726a8 Iustin Pop
1263 a8083063 Iustin Pop
1264 a8083063 Iustin Pop
class OS(ConfigObject):
1265 b41b3516 Iustin Pop
  """Config object representing an operating system.
1266 b41b3516 Iustin Pop

1267 b41b3516 Iustin Pop
  @type supported_parameters: list
1268 b41b3516 Iustin Pop
  @ivar supported_parameters: a list of tuples, name and description,
1269 b41b3516 Iustin Pop
      containing the supported parameters by this OS
1270 b41b3516 Iustin Pop

1271 870dc44c Iustin Pop
  @type VARIANT_DELIM: string
1272 870dc44c Iustin Pop
  @cvar VARIANT_DELIM: the variant delimiter
1273 870dc44c Iustin Pop

1274 b41b3516 Iustin Pop
  """
1275 a8083063 Iustin Pop
  __slots__ = [
1276 a8083063 Iustin Pop
    "name",
1277 a8083063 Iustin Pop
    "path",
1278 082a7f91 Guido Trotter
    "api_versions",
1279 a8083063 Iustin Pop
    "create_script",
1280 a8083063 Iustin Pop
    "export_script",
1281 386b57af Iustin Pop
    "import_script",
1282 386b57af Iustin Pop
    "rename_script",
1283 b41b3516 Iustin Pop
    "verify_script",
1284 6d79896b Guido Trotter
    "supported_variants",
1285 b41b3516 Iustin Pop
    "supported_parameters",
1286 a8083063 Iustin Pop
    ]
1287 a8083063 Iustin Pop
1288 870dc44c Iustin Pop
  VARIANT_DELIM = "+"
1289 870dc44c Iustin Pop
1290 870dc44c Iustin Pop
  @classmethod
1291 870dc44c Iustin Pop
  def SplitNameVariant(cls, name):
1292 870dc44c Iustin Pop
    """Splits the name into the proper name and variant.
1293 870dc44c Iustin Pop

1294 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1295 870dc44c Iustin Pop
    @rtype: list
1296 870dc44c Iustin Pop
    @return: a list of two elements; if the original name didn't
1297 870dc44c Iustin Pop
        contain a variant, it's returned as an empty string
1298 870dc44c Iustin Pop

1299 870dc44c Iustin Pop
    """
1300 870dc44c Iustin Pop
    nv = name.split(cls.VARIANT_DELIM, 1)
1301 870dc44c Iustin Pop
    if len(nv) == 1:
1302 870dc44c Iustin Pop
      nv.append("")
1303 870dc44c Iustin Pop
    return nv
1304 870dc44c Iustin Pop
1305 870dc44c Iustin Pop
  @classmethod
1306 870dc44c Iustin Pop
  def GetName(cls, name):
1307 870dc44c Iustin Pop
    """Returns the proper name of the os (without the variant).
1308 870dc44c Iustin Pop

1309 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1310 870dc44c Iustin Pop

1311 870dc44c Iustin Pop
    """
1312 870dc44c Iustin Pop
    return cls.SplitNameVariant(name)[0]
1313 870dc44c Iustin Pop
1314 870dc44c Iustin Pop
  @classmethod
1315 870dc44c Iustin Pop
  def GetVariant(cls, name):
1316 870dc44c Iustin Pop
    """Returns the variant the os (without the base name).
1317 870dc44c Iustin Pop

1318 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1319 870dc44c Iustin Pop

1320 870dc44c Iustin Pop
    """
1321 870dc44c Iustin Pop
    return cls.SplitNameVariant(name)[1]
1322 870dc44c Iustin Pop
1323 7c0d6283 Michael Hanselmann
1324 376631d1 Constantinos Venetsanopoulos
class ExtStorage(ConfigObject):
1325 376631d1 Constantinos Venetsanopoulos
  """Config object representing an External Storage Provider.
1326 376631d1 Constantinos Venetsanopoulos

1327 376631d1 Constantinos Venetsanopoulos
  """
1328 376631d1 Constantinos Venetsanopoulos
  __slots__ = [
1329 376631d1 Constantinos Venetsanopoulos
    "name",
1330 376631d1 Constantinos Venetsanopoulos
    "path",
1331 376631d1 Constantinos Venetsanopoulos
    "create_script",
1332 376631d1 Constantinos Venetsanopoulos
    "remove_script",
1333 376631d1 Constantinos Venetsanopoulos
    "grow_script",
1334 376631d1 Constantinos Venetsanopoulos
    "attach_script",
1335 376631d1 Constantinos Venetsanopoulos
    "detach_script",
1336 376631d1 Constantinos Venetsanopoulos
    "setinfo_script",
1337 938adc87 Constantinos Venetsanopoulos
    "verify_script",
1338 938adc87 Constantinos Venetsanopoulos
    "supported_parameters",
1339 376631d1 Constantinos Venetsanopoulos
    ]
1340 376631d1 Constantinos Venetsanopoulos
1341 376631d1 Constantinos Venetsanopoulos
1342 5f06ce5e Michael Hanselmann
class NodeHvState(ConfigObject):
1343 5f06ce5e Michael Hanselmann
  """Hypvervisor state on a node.
1344 5f06ce5e Michael Hanselmann

1345 5f06ce5e Michael Hanselmann
  @ivar mem_total: Total amount of memory
1346 5f06ce5e Michael Hanselmann
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1347 5f06ce5e Michael Hanselmann
    available)
1348 5f06ce5e Michael Hanselmann
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1349 5f06ce5e Michael Hanselmann
    rounding
1350 5f06ce5e Michael Hanselmann
  @ivar mem_inst: Memory used by instances living on node
1351 5f06ce5e Michael Hanselmann
  @ivar cpu_total: Total node CPU core count
1352 5f06ce5e Michael Hanselmann
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1353 5f06ce5e Michael Hanselmann

1354 5f06ce5e Michael Hanselmann
  """
1355 5f06ce5e Michael Hanselmann
  __slots__ = [
1356 5f06ce5e Michael Hanselmann
    "mem_total",
1357 5f06ce5e Michael Hanselmann
    "mem_node",
1358 5f06ce5e Michael Hanselmann
    "mem_hv",
1359 5f06ce5e Michael Hanselmann
    "mem_inst",
1360 5f06ce5e Michael Hanselmann
    "cpu_total",
1361 5f06ce5e Michael Hanselmann
    "cpu_node",
1362 5f06ce5e Michael Hanselmann
    ] + _TIMESTAMPS
1363 5f06ce5e Michael Hanselmann
1364 5f06ce5e Michael Hanselmann
1365 5f06ce5e Michael Hanselmann
class NodeDiskState(ConfigObject):
1366 5f06ce5e Michael Hanselmann
  """Disk state on a node.
1367 5f06ce5e Michael Hanselmann

1368 5f06ce5e Michael Hanselmann
  """
1369 5f06ce5e Michael Hanselmann
  __slots__ = [
1370 5f06ce5e Michael Hanselmann
    "total",
1371 5f06ce5e Michael Hanselmann
    "reserved",
1372 5f06ce5e Michael Hanselmann
    "overhead",
1373 5f06ce5e Michael Hanselmann
    ] + _TIMESTAMPS
1374 5f06ce5e Michael Hanselmann
1375 5f06ce5e Michael Hanselmann
1376 ec29fe40 Iustin Pop
class Node(TaggableObject):
1377 634d30f4 Michael Hanselmann
  """Config object representing a node.
1378 634d30f4 Michael Hanselmann

1379 634d30f4 Michael Hanselmann
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1380 634d30f4 Michael Hanselmann
  @ivar hv_state_static: Hypervisor state overriden by user
1381 634d30f4 Michael Hanselmann
  @ivar disk_state: Disk state (e.g. free space)
1382 634d30f4 Michael Hanselmann
  @ivar disk_state_static: Disk state overriden by user
1383 634d30f4 Michael Hanselmann

1384 634d30f4 Michael Hanselmann
  """
1385 154b9580 Balazs Lecz
  __slots__ = [
1386 ec29fe40 Iustin Pop
    "name",
1387 ec29fe40 Iustin Pop
    "primary_ip",
1388 ec29fe40 Iustin Pop
    "secondary_ip",
1389 be1fa613 Iustin Pop
    "serial_no",
1390 8b8b8b81 Iustin Pop
    "master_candidate",
1391 fc0fe88c Iustin Pop
    "offline",
1392 af64c0ea Iustin Pop
    "drained",
1393 f936c153 Iustin Pop
    "group",
1394 490acd18 Iustin Pop
    "master_capable",
1395 490acd18 Iustin Pop
    "vm_capable",
1396 095e71aa Renรฉ Nussbaumer
    "ndparams",
1397 25124d4a Renรฉ Nussbaumer
    "powered",
1398 5b49ed09 Renรฉ Nussbaumer
    "hv_state",
1399 634d30f4 Michael Hanselmann
    "hv_state_static",
1400 5b49ed09 Renรฉ Nussbaumer
    "disk_state",
1401 634d30f4 Michael Hanselmann
    "disk_state_static",
1402 e1dcc53a Iustin Pop
    ] + _TIMESTAMPS + _UUID
1403 a8083063 Iustin Pop
1404 490acd18 Iustin Pop
  def UpgradeConfig(self):
1405 490acd18 Iustin Pop
    """Fill defaults for missing configuration values.
1406 490acd18 Iustin Pop

1407 490acd18 Iustin Pop
    """
1408 b459a848 Andrea Spadaccini
    # pylint: disable=E0203
1409 490acd18 Iustin Pop
    # because these are "defined" via slots, not manually
1410 490acd18 Iustin Pop
    if self.master_capable is None:
1411 490acd18 Iustin Pop
      self.master_capable = True
1412 490acd18 Iustin Pop
1413 490acd18 Iustin Pop
    if self.vm_capable is None:
1414 490acd18 Iustin Pop
      self.vm_capable = True
1415 490acd18 Iustin Pop
1416 095e71aa Renรฉ Nussbaumer
    if self.ndparams is None:
1417 095e71aa Renรฉ Nussbaumer
      self.ndparams = {}
1418 250a9404 Bernardo Dal Seno
    # And remove any global parameter
1419 250a9404 Bernardo Dal Seno
    for key in constants.NDC_GLOBALS:
1420 250a9404 Bernardo Dal Seno
      if key in self.ndparams:
1421 250a9404 Bernardo Dal Seno
        logging.warning("Ignoring %s node parameter for node %s",
1422 250a9404 Bernardo Dal Seno
                        key, self.name)
1423 250a9404 Bernardo Dal Seno
        del self.ndparams[key]
1424 095e71aa Renรฉ Nussbaumer
1425 25124d4a Renรฉ Nussbaumer
    if self.powered is None:
1426 25124d4a Renรฉ Nussbaumer
      self.powered = True
1427 25124d4a Renรฉ Nussbaumer
1428 a5efec93 Santi Raffa
  def ToDict(self, _with_private=False):
1429 5f06ce5e Michael Hanselmann
    """Custom function for serializing.
1430 5f06ce5e Michael Hanselmann

1431 5f06ce5e Michael Hanselmann
    """
1432 a5efec93 Santi Raffa
    data = super(Node, self).ToDict(_with_private=_with_private)
1433 5f06ce5e Michael Hanselmann
1434 5f06ce5e Michael Hanselmann
    hv_state = data.get("hv_state", None)
1435 5f06ce5e Michael Hanselmann
    if hv_state is not None:
1436 fe502d25 Iustin Pop
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1437 5f06ce5e Michael Hanselmann
1438 5f06ce5e Michael Hanselmann
    disk_state = data.get("disk_state", None)
1439 5f06ce5e Michael Hanselmann
    if disk_state is not None:
1440 5f06ce5e Michael Hanselmann
      data["disk_state"] = \
1441 fe502d25 Iustin Pop
        dict((key, outils.ContainerToDicts(value))
1442 5f06ce5e Michael Hanselmann
             for (key, value) in disk_state.items())
1443 5f06ce5e Michael Hanselmann
1444 5f06ce5e Michael Hanselmann
    return data
1445 5f06ce5e Michael Hanselmann
1446 5f06ce5e Michael Hanselmann
  @classmethod
1447 5f06ce5e Michael Hanselmann
  def FromDict(cls, val):
1448 5f06ce5e Michael Hanselmann
    """Custom function for deserializing.
1449 5f06ce5e Michael Hanselmann

1450 5f06ce5e Michael Hanselmann
    """
1451 5f06ce5e Michael Hanselmann
    obj = super(Node, cls).FromDict(val)
1452 5f06ce5e Michael Hanselmann
1453 5f06ce5e Michael Hanselmann
    if obj.hv_state is not None:
1454 473ab806 Michael Hanselmann
      obj.hv_state = \
1455 fe502d25 Iustin Pop
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1456 5f06ce5e Michael Hanselmann
1457 5f06ce5e Michael Hanselmann
    if obj.disk_state is not None:
1458 5f06ce5e Michael Hanselmann
      obj.disk_state = \
1459 fe502d25 Iustin Pop
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1460 5f06ce5e Michael Hanselmann
             for (key, value) in obj.disk_state.items())
1461 5f06ce5e Michael Hanselmann
1462 5f06ce5e Michael Hanselmann
    return obj
1463 5f06ce5e Michael Hanselmann
1464 a8083063 Iustin Pop
1465 1ffd2673 Michael Hanselmann
class NodeGroup(TaggableObject):
1466 24a3707f Guido Trotter
  """Config object representing a node group."""
1467 24a3707f Guido Trotter
  __slots__ = [
1468 24a3707f Guido Trotter
    "name",
1469 24a3707f Guido Trotter
    "members",
1470 095e71aa Renรฉ Nussbaumer
    "ndparams",
1471 bc5d0215 Andrea Spadaccini
    "diskparams",
1472 81e3ab4f Agata Murawska
    "ipolicy",
1473 e11a1b77 Adeodato Simo
    "serial_no",
1474 a8282327 Renรฉ Nussbaumer
    "hv_state_static",
1475 a8282327 Renรฉ Nussbaumer
    "disk_state_static",
1476 90e99856 Adeodato Simo
    "alloc_policy",
1477 eaa4c57c Dimitris Aragiorgis
    "networks",
1478 24a3707f Guido Trotter
    ] + _TIMESTAMPS + _UUID
1479 24a3707f Guido Trotter
1480 a5efec93 Santi Raffa
  def ToDict(self, _with_private=False):
1481 24a3707f Guido Trotter
    """Custom function for nodegroup.
1482 24a3707f Guido Trotter

1483 c60abd62 Guido Trotter
    This discards the members object, which gets recalculated and is only kept
1484 c60abd62 Guido Trotter
    in memory.
1485 24a3707f Guido Trotter

1486 24a3707f Guido Trotter
    """
1487 a5efec93 Santi Raffa
    mydict = super(NodeGroup, self).ToDict(_with_private=_with_private)
1488 24a3707f Guido Trotter
    del mydict["members"]
1489 24a3707f Guido Trotter
    return mydict
1490 24a3707f Guido Trotter
1491 24a3707f Guido Trotter
  @classmethod
1492 24a3707f Guido Trotter
  def FromDict(cls, val):
1493 24a3707f Guido Trotter
    """Custom function for nodegroup.
1494 24a3707f Guido Trotter

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

1497 24a3707f Guido Trotter
    """
1498 24a3707f Guido Trotter
    obj = super(NodeGroup, cls).FromDict(val)
1499 24a3707f Guido Trotter
    obj.members = []
1500 24a3707f Guido Trotter
    return obj
1501 24a3707f Guido Trotter
1502 095e71aa Renรฉ Nussbaumer
  def UpgradeConfig(self):
1503 095e71aa Renรฉ Nussbaumer
    """Fill defaults for missing configuration values.
1504 095e71aa Renรฉ Nussbaumer

1505 095e71aa Renรฉ Nussbaumer
    """
1506 095e71aa Renรฉ Nussbaumer
    if self.ndparams is None:
1507 095e71aa Renรฉ Nussbaumer
      self.ndparams = {}
1508 095e71aa Renรฉ Nussbaumer
1509 e11a1b77 Adeodato Simo
    if self.serial_no is None:
1510 e11a1b77 Adeodato Simo
      self.serial_no = 1
1511 e11a1b77 Adeodato Simo
1512 90e99856 Adeodato Simo
    if self.alloc_policy is None:
1513 90e99856 Adeodato Simo
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1514 90e99856 Adeodato Simo
1515 4b97458c Iustin Pop
    # We only update mtime, and not ctime, since we would not be able
1516 4b97458c Iustin Pop
    # to provide a correct value for creation time.
1517 e11a1b77 Adeodato Simo
    if self.mtime is None:
1518 e11a1b77 Adeodato Simo
      self.mtime = time.time()
1519 e11a1b77 Adeodato Simo
1520 7228ca91 Renรฉ Nussbaumer
    if self.diskparams is None:
1521 7228ca91 Renรฉ Nussbaumer
      self.diskparams = {}
1522 81e3ab4f Agata Murawska
    if self.ipolicy is None:
1523 81e3ab4f Agata Murawska
      self.ipolicy = MakeEmptyIPolicy()
1524 bc5d0215 Andrea Spadaccini
1525 eaa4c57c Dimitris Aragiorgis
    if self.networks is None:
1526 eaa4c57c Dimitris Aragiorgis
      self.networks = {}
1527 eaa4c57c Dimitris Aragiorgis
1528 095e71aa Renรฉ Nussbaumer
  def FillND(self, node):
1529 ce523de1 Michael Hanselmann
    """Return filled out ndparams for L{objects.Node}
1530 095e71aa Renรฉ Nussbaumer

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

1535 095e71aa Renรฉ Nussbaumer
    """
1536 095e71aa Renรฉ Nussbaumer
    return self.SimpleFillND(node.ndparams)
1537 095e71aa Renรฉ Nussbaumer
1538 095e71aa Renรฉ Nussbaumer
  def SimpleFillND(self, ndparams):
1539 095e71aa Renรฉ Nussbaumer
    """Fill a given ndparams dict with defaults.
1540 095e71aa Renรฉ Nussbaumer

1541 095e71aa Renรฉ Nussbaumer
    @type ndparams: dict
1542 095e71aa Renรฉ Nussbaumer
    @param ndparams: the dict to fill
1543 095e71aa Renรฉ Nussbaumer
    @rtype: dict
1544 095e71aa Renรฉ Nussbaumer
    @return: a copy of the passed in ndparams with missing keys filled
1545 e6e88de6 Adeodato Simo
        from the node group defaults
1546 095e71aa Renรฉ Nussbaumer

1547 095e71aa Renรฉ Nussbaumer
    """
1548 095e71aa Renรฉ Nussbaumer
    return FillDict(self.ndparams, ndparams)
1549 095e71aa Renรฉ Nussbaumer
1550 24a3707f Guido Trotter
1551 ec29fe40 Iustin Pop
class Cluster(TaggableObject):
1552 a8083063 Iustin Pop
  """Config object representing the cluster."""
1553 154b9580 Balazs Lecz
  __slots__ = [
1554 a8083063 Iustin Pop
    "serial_no",
1555 a8083063 Iustin Pop
    "rsahostkeypub",
1556 a9542a4f Thomas Thrainer
    "dsahostkeypub",
1557 a8083063 Iustin Pop
    "highest_used_port",
1558 b2fddf63 Iustin Pop
    "tcpudp_port_pool",
1559 a8083063 Iustin Pop
    "mac_prefix",
1560 a8083063 Iustin Pop
    "volume_group_name",
1561 999b183c Iustin Pop
    "reserved_lvs",
1562 9e33896b Luca Bigliardi
    "drbd_usermode_helper",
1563 a8083063 Iustin Pop
    "default_bridge",
1564 02691904 Alexander Schreiber
    "default_hypervisor",
1565 f6bd6e98 Michael Hanselmann
    "master_node",
1566 f6bd6e98 Michael Hanselmann
    "master_ip",
1567 f6bd6e98 Michael Hanselmann
    "master_netdev",
1568 5a8648eb Andrea Spadaccini
    "master_netmask",
1569 33be7576 Andrea Spadaccini
    "use_external_mip_script",
1570 f6bd6e98 Michael Hanselmann
    "cluster_name",
1571 f6bd6e98 Michael Hanselmann
    "file_storage_dir",
1572 4b97f902 Apollon Oikonomopoulos
    "shared_file_storage_dir",
1573 d3e6fd0e Santi Raffa
    "gluster_storage_dir",
1574 e69d05fd Iustin Pop
    "enabled_hypervisors",
1575 5bf7b5cf Iustin Pop
    "hvparams",
1576 918eb80b Agata Murawska
    "ipolicy",
1577 17463d22 Renรฉ Nussbaumer
    "os_hvp",
1578 5bf7b5cf Iustin Pop
    "beparams",
1579 1bdcbbab Iustin Pop
    "osparams",
1580 a5efec93 Santi Raffa
    "osparams_private_cluster",
1581 c8fcde47 Guido Trotter
    "nicparams",
1582 095e71aa Renรฉ Nussbaumer
    "ndparams",
1583 bc5d0215 Andrea Spadaccini
    "diskparams",
1584 4b7735f9 Iustin Pop
    "candidate_pool_size",
1585 b86a6bcd Guido Trotter
    "modify_etc_hosts",
1586 b989b9d9 Ken Wehr
    "modify_ssh_setup",
1587 3953242f Iustin Pop
    "maintain_node_health",
1588 4437d889 Balazs Lecz
    "uid_pool",
1589 bf4af505 Apollon Oikonomopoulos
    "default_iallocator",
1590 0359e5d0 Spyros Trigazis
    "default_iallocator_params",
1591 87b2cd45 Iustin Pop
    "hidden_os",
1592 87b2cd45 Iustin Pop
    "blacklisted_os",
1593 2f20d07b Manuel Franceschini
    "primary_ip_family",
1594 3d914585 Renรฉ Nussbaumer
    "prealloc_wipe_disks",
1595 2da9f556 Renรฉ Nussbaumer
    "hv_state_static",
1596 2da9f556 Renรฉ Nussbaumer
    "disk_state_static",
1597 1b02d7ef Helga Velroyen
    "enabled_disk_templates",
1598 3bcf2140 Helga Velroyen
    "candidate_certs",
1599 cf048aea Klaus Aehlig
    "max_running_jobs",
1600 8a5d326f Jose A. Lopes
    "instance_communication_network",
1601 e1dcc53a Iustin Pop
    ] + _TIMESTAMPS + _UUID
1602 a8083063 Iustin Pop
1603 b86a6bcd Guido Trotter
  def UpgradeConfig(self):
1604 b86a6bcd Guido Trotter
    """Fill defaults for missing configuration values.
1605 b86a6bcd Guido Trotter

1606 b86a6bcd Guido Trotter
    """
1607 b459a848 Andrea Spadaccini
    # pylint: disable=E0203
1608 fe267188 Iustin Pop
    # because these are "defined" via slots, not manually
1609 c1b42c18 Guido Trotter
    if self.hvparams is None:
1610 c1b42c18 Guido Trotter
      self.hvparams = constants.HVC_DEFAULTS
1611 c1b42c18 Guido Trotter
    else:
1612 6ee8fdd3 Michele Tartara
      for hypervisor in constants.HYPER_TYPES:
1613 6ee8fdd3 Michele Tartara
        try:
1614 6ee8fdd3 Michele Tartara
          existing_params = self.hvparams[hypervisor]
1615 6ee8fdd3 Michele Tartara
        except KeyError:
1616 6ee8fdd3 Michele Tartara
          existing_params = {}
1617 abe609b2 Guido Trotter
        self.hvparams[hypervisor] = FillDict(
1618 6ee8fdd3 Michele Tartara
            constants.HVC_DEFAULTS[hypervisor], existing_params)
1619 c1b42c18 Guido Trotter
1620 17463d22 Renรฉ Nussbaumer
    if self.os_hvp is None:
1621 17463d22 Renรฉ Nussbaumer
      self.os_hvp = {}
1622 17463d22 Renรฉ Nussbaumer
1623 1bdcbbab Iustin Pop
    if self.osparams is None:
1624 1bdcbbab Iustin Pop
      self.osparams = {}
1625 a5efec93 Santi Raffa
    # osparams_private_cluster added in 2.12
1626 a5efec93 Santi Raffa
    if self.osparams_private_cluster is None:
1627 a5efec93 Santi Raffa
      self.osparams_private_cluster = {}
1628 1bdcbbab Iustin Pop
1629 2a27dac3 Iustin Pop
    self.ndparams = UpgradeNDParams(self.ndparams)
1630 095e71aa Renรฉ Nussbaumer
1631 6e34b628 Guido Trotter
    self.beparams = UpgradeGroupedParams(self.beparams,
1632 6e34b628 Guido Trotter
                                         constants.BEC_DEFAULTS)
1633 8c72ab2b Guido Trotter
    for beparams_group in self.beparams:
1634 8c72ab2b Guido Trotter
      UpgradeBeParams(self.beparams[beparams_group])
1635 8c72ab2b Guido Trotter
1636 c8fcde47 Guido Trotter
    migrate_default_bridge = not self.nicparams
1637 c8fcde47 Guido Trotter
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1638 c8fcde47 Guido Trotter
                                          constants.NICC_DEFAULTS)
1639 c8fcde47 Guido Trotter
    if migrate_default_bridge:
1640 c8fcde47 Guido Trotter
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1641 c8fcde47 Guido Trotter
        self.default_bridge
1642 c1b42c18 Guido Trotter
1643 b86a6bcd Guido Trotter
    if self.modify_etc_hosts is None:
1644 b86a6bcd Guido Trotter
      self.modify_etc_hosts = True
1645 b86a6bcd Guido Trotter
1646 b989b9d9 Ken Wehr
    if self.modify_ssh_setup is None:
1647 b989b9d9 Ken Wehr
      self.modify_ssh_setup = True
1648 b989b9d9 Ken Wehr
1649 73f1d185 Stephen Shirley
    # default_bridge is no longer used in 2.1. The slot is left there to
1650 90d118fd Guido Trotter
    # support auto-upgrading. It can be removed once we decide to deprecate
1651 90d118fd Guido Trotter
    # upgrading straight from 2.0.
1652 9b31ca85 Guido Trotter
    if self.default_bridge is not None:
1653 9b31ca85 Guido Trotter
      self.default_bridge = None
1654 9b31ca85 Guido Trotter
1655 90d118fd Guido Trotter
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1656 90d118fd Guido Trotter
    # code can be removed once upgrading straight from 2.0 is deprecated.
1657 066f465d Guido Trotter
    if self.default_hypervisor is not None:
1658 016d04b3 Michael Hanselmann
      self.enabled_hypervisors = ([self.default_hypervisor] +
1659 5ae4945a Iustin Pop
                                  [hvname for hvname in self.enabled_hypervisors
1660 5ae4945a Iustin Pop
                                   if hvname != self.default_hypervisor])
1661 066f465d Guido Trotter
      self.default_hypervisor = None
1662 066f465d Guido Trotter
1663 3953242f Iustin Pop
    # maintain_node_health added after 2.1.1
1664 3953242f Iustin Pop
    if self.maintain_node_health is None:
1665 3953242f Iustin Pop
      self.maintain_node_health = False
1666 3953242f Iustin Pop
1667 4437d889 Balazs Lecz
    if self.uid_pool is None:
1668 4437d889 Balazs Lecz
      self.uid_pool = []
1669 4437d889 Balazs Lecz
1670 bf4af505 Apollon Oikonomopoulos
    if self.default_iallocator is None:
1671 bf4af505 Apollon Oikonomopoulos
      self.default_iallocator = ""
1672 bf4af505 Apollon Oikonomopoulos
1673 0359e5d0 Spyros Trigazis
    if self.default_iallocator_params is None:
1674 0359e5d0 Spyros Trigazis
      self.default_iallocator_params = {}
1675 0359e5d0 Spyros Trigazis
1676 999b183c Iustin Pop
    # reserved_lvs added before 2.2
1677 999b183c Iustin Pop
    if self.reserved_lvs is None:
1678 999b183c Iustin Pop
      self.reserved_lvs = []
1679 999b183c Iustin Pop
1680 546b1111 Iustin Pop
    # hidden and blacklisted operating systems added before 2.2.1
1681 87b2cd45 Iustin Pop
    if self.hidden_os is None:
1682 87b2cd45 Iustin Pop
      self.hidden_os = []
1683 546b1111 Iustin Pop
1684 87b2cd45 Iustin Pop
    if self.blacklisted_os is None:
1685 87b2cd45 Iustin Pop
      self.blacklisted_os = []
1686 546b1111 Iustin Pop
1687 f4c9af7a Guido Trotter
    # primary_ip_family added before 2.3
1688 f4c9af7a Guido Trotter
    if self.primary_ip_family is None:
1689 f4c9af7a Guido Trotter
      self.primary_ip_family = AF_INET
1690 f4c9af7a Guido Trotter
1691 0007f3ab Andrea Spadaccini
    if self.master_netmask is None:
1692 0007f3ab Andrea Spadaccini
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1693 0007f3ab Andrea Spadaccini
      self.master_netmask = ipcls.iplen
1694 0007f3ab Andrea Spadaccini
1695 3d914585 Renรฉ Nussbaumer
    if self.prealloc_wipe_disks is None:
1696 3d914585 Renรฉ Nussbaumer
      self.prealloc_wipe_disks = False
1697 3d914585 Renรฉ Nussbaumer
1698 e8f472d1 Iustin Pop
    # shared_file_storage_dir added before 2.5
1699 e8f472d1 Iustin Pop
    if self.shared_file_storage_dir is None:
1700 e8f472d1 Iustin Pop
      self.shared_file_storage_dir = ""
1701 e8f472d1 Iustin Pop
1702 d3e6fd0e Santi Raffa
    # gluster_storage_dir added in 2.11
1703 d3e6fd0e Santi Raffa
    if self.gluster_storage_dir is None:
1704 d3e6fd0e Santi Raffa
      self.gluster_storage_dir = ""
1705 d3e6fd0e Santi Raffa
1706 33be7576 Andrea Spadaccini
    if self.use_external_mip_script is None:
1707 33be7576 Andrea Spadaccini
      self.use_external_mip_script = False
1708 33be7576 Andrea Spadaccini
1709 99ccf8b9 Renรฉ Nussbaumer
    if self.diskparams:
1710 99ccf8b9 Renรฉ Nussbaumer
      self.diskparams = UpgradeDiskParams(self.diskparams)
1711 99ccf8b9 Renรฉ Nussbaumer
    else:
1712 99ccf8b9 Renรฉ Nussbaumer
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1713 bc5d0215 Andrea Spadaccini
1714 918eb80b Agata Murawska
    # instance policy added before 2.6
1715 918eb80b Agata Murawska
    if self.ipolicy is None:
1716 2cc673a3 Iustin Pop
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1717 38a6e2e1 Iustin Pop
    else:
1718 38a6e2e1 Iustin Pop
      # we can either make sure to upgrade the ipolicy always, or only
1719 38a6e2e1 Iustin Pop
      # do it in some corner cases (e.g. missing keys); note that this
1720 38a6e2e1 Iustin Pop
      # will break any removal of keys from the ipolicy dict
1721 4f7e5a1d Bernardo Dal Seno
      wrongkeys = frozenset(self.ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1722 4f7e5a1d Bernardo Dal Seno
      if wrongkeys:
1723 4f7e5a1d Bernardo Dal Seno
        # These keys would be silently removed by FillIPolicy()
1724 7fb852bd Michele Tartara
        msg = ("Cluster instance policy contains spurious keys: %s" %
1725 4f7e5a1d Bernardo Dal Seno
               utils.CommaJoin(wrongkeys))
1726 4f7e5a1d Bernardo Dal Seno
        raise errors.ConfigurationError(msg)
1727 38a6e2e1 Iustin Pop
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1728 918eb80b Agata Murawska
1729 3bcf2140 Helga Velroyen
    if self.candidate_certs is None:
1730 3bcf2140 Helga Velroyen
      self.candidate_certs = {}
1731 3bcf2140 Helga Velroyen
1732 cf048aea Klaus Aehlig
    if self.max_running_jobs is None:
1733 cf048aea Klaus Aehlig
      self.max_running_jobs = constants.LUXID_MAXIMAL_RUNNING_JOBS_DEFAULT
1734 cf048aea Klaus Aehlig
1735 8a5d326f Jose A. Lopes
    if self.instance_communication_network is None:
1736 8a5d326f Jose A. Lopes
      self.instance_communication_network = ""
1737 8a5d326f Jose A. Lopes
1738 0fbedb7a Michael Hanselmann
  @property
1739 0fbedb7a Michael Hanselmann
  def primary_hypervisor(self):
1740 0fbedb7a Michael Hanselmann
    """The first hypervisor is the primary.
1741 0fbedb7a Michael Hanselmann

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

1744 0fbedb7a Michael Hanselmann
    """
1745 0fbedb7a Michael Hanselmann
    return self.enabled_hypervisors[0]
1746 0fbedb7a Michael Hanselmann
1747 a5efec93 Santi Raffa
  def ToDict(self, _with_private=False):
1748 319856a9 Michael Hanselmann
    """Custom function for cluster.
1749 319856a9 Michael Hanselmann

1750 319856a9 Michael Hanselmann
    """
1751 a5efec93 Santi Raffa
    mydict = super(Cluster, self).ToDict(_with_private=_with_private)
1752 a5efec93 Santi Raffa
1753 a5efec93 Santi Raffa
    # Explicitly save private parameters.
1754 a5efec93 Santi Raffa
    if _with_private:
1755 a5efec93 Santi Raffa
      for os in mydict["osparams_private_cluster"]:
1756 a5efec93 Santi Raffa
        mydict["osparams_private_cluster"][os] = \
1757 a5efec93 Santi Raffa
          self.osparams_private_cluster[os].Unprivate()
1758 4d36fbf4 Michael Hanselmann
1759 4d36fbf4 Michael Hanselmann
    if self.tcpudp_port_pool is None:
1760 4d36fbf4 Michael Hanselmann
      tcpudp_port_pool = []
1761 4d36fbf4 Michael Hanselmann
    else:
1762 4d36fbf4 Michael Hanselmann
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1763 4d36fbf4 Michael Hanselmann
1764 4d36fbf4 Michael Hanselmann
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1765 4d36fbf4 Michael Hanselmann
1766 319856a9 Michael Hanselmann
    return mydict
1767 319856a9 Michael Hanselmann
1768 319856a9 Michael Hanselmann
  @classmethod
1769 319856a9 Michael Hanselmann
  def FromDict(cls, val):
1770 319856a9 Michael Hanselmann
    """Custom function for cluster.
1771 319856a9 Michael Hanselmann

1772 319856a9 Michael Hanselmann
    """
1773 b60ae2ca Iustin Pop
    obj = super(Cluster, cls).FromDict(val)
1774 4d36fbf4 Michael Hanselmann
1775 4d36fbf4 Michael Hanselmann
    if obj.tcpudp_port_pool is None:
1776 4d36fbf4 Michael Hanselmann
      obj.tcpudp_port_pool = set()
1777 4d36fbf4 Michael Hanselmann
    elif not isinstance(obj.tcpudp_port_pool, set):
1778 319856a9 Michael Hanselmann
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1779 4d36fbf4 Michael Hanselmann
1780 319856a9 Michael Hanselmann
    return obj
1781 319856a9 Michael Hanselmann
1782 8a147bba Renรฉ Nussbaumer
  def SimpleFillDP(self, diskparams):
1783 8a147bba Renรฉ Nussbaumer
    """Fill a given diskparams dict with cluster defaults.
1784 8a147bba Renรฉ Nussbaumer

1785 8a147bba Renรฉ Nussbaumer
    @param diskparams: The diskparams
1786 8a147bba Renรฉ Nussbaumer
    @return: The defaults dict
1787 8a147bba Renรฉ Nussbaumer

1788 8a147bba Renรฉ Nussbaumer
    """
1789 8a147bba Renรฉ Nussbaumer
    return FillDiskParams(self.diskparams, diskparams)
1790 8a147bba Renรฉ Nussbaumer
1791 d63479b5 Iustin Pop
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1792 d63479b5 Iustin Pop
    """Get the default hypervisor parameters for the cluster.
1793 d63479b5 Iustin Pop

1794 d63479b5 Iustin Pop
    @param hypervisor: the hypervisor name
1795 d63479b5 Iustin Pop
    @param os_name: if specified, we'll also update the defaults for this OS
1796 d63479b5 Iustin Pop
    @param skip_keys: if passed, list of keys not to use
1797 d63479b5 Iustin Pop
    @return: the defaults dict
1798 d63479b5 Iustin Pop

1799 d63479b5 Iustin Pop
    """
1800 d63479b5 Iustin Pop
    if skip_keys is None:
1801 d63479b5 Iustin Pop
      skip_keys = []
1802 d63479b5 Iustin Pop
1803 d63479b5 Iustin Pop
    fill_stack = [self.hvparams.get(hypervisor, {})]
1804 d63479b5 Iustin Pop
    if os_name is not None:
1805 d63479b5 Iustin Pop
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1806 d63479b5 Iustin Pop
      fill_stack.append(os_hvp)
1807 d63479b5 Iustin Pop
1808 d63479b5 Iustin Pop
    ret_dict = {}
1809 d63479b5 Iustin Pop
    for o_dict in fill_stack:
1810 d63479b5 Iustin Pop
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1811 d63479b5 Iustin Pop
1812 d63479b5 Iustin Pop
    return ret_dict
1813 d63479b5 Iustin Pop
1814 73e0328b Iustin Pop
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1815 73e0328b Iustin Pop
    """Fill a given hvparams dict with cluster defaults.
1816 73e0328b Iustin Pop

1817 73e0328b Iustin Pop
    @type hv_name: string
1818 73e0328b Iustin Pop
    @param hv_name: the hypervisor to use
1819 73e0328b Iustin Pop
    @type os_name: string
1820 73e0328b Iustin Pop
    @param os_name: the OS to use for overriding the hypervisor defaults
1821 73e0328b Iustin Pop
    @type skip_globals: boolean
1822 73e0328b Iustin Pop
    @param skip_globals: if True, the global hypervisor parameters will
1823 73e0328b Iustin Pop
        not be filled
1824 73e0328b Iustin Pop
    @rtype: dict
1825 73e0328b Iustin Pop
    @return: a copy of the given hvparams with missing keys filled from
1826 73e0328b Iustin Pop
        the cluster defaults
1827 73e0328b Iustin Pop

1828 73e0328b Iustin Pop
    """
1829 73e0328b Iustin Pop
    if skip_globals:
1830 73e0328b Iustin Pop
      skip_keys = constants.HVC_GLOBALS
1831 73e0328b Iustin Pop
    else:
1832 73e0328b Iustin Pop
      skip_keys = []
1833 73e0328b Iustin Pop
1834 73e0328b Iustin Pop
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1835 73e0328b Iustin Pop
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1836 d63479b5 Iustin Pop
1837 7736a5f2 Iustin Pop
  def FillHV(self, instance, skip_globals=False):
1838 73e0328b Iustin Pop
    """Fill an instance's hvparams dict with cluster defaults.
1839 5bf7b5cf Iustin Pop

1840 a2a24f4c Guido Trotter
    @type instance: L{objects.Instance}
1841 5bf7b5cf Iustin Pop
    @param instance: the instance parameter to fill
1842 7736a5f2 Iustin Pop
    @type skip_globals: boolean
1843 7736a5f2 Iustin Pop
    @param skip_globals: if True, the global hypervisor parameters will
1844 7736a5f2 Iustin Pop
        not be filled
1845 5bf7b5cf Iustin Pop
    @rtype: dict
1846 5bf7b5cf Iustin Pop
    @return: a copy of the instance's hvparams with missing keys filled from
1847 5bf7b5cf Iustin Pop
        the cluster defaults
1848 5bf7b5cf Iustin Pop

1849 5bf7b5cf Iustin Pop
    """
1850 73e0328b Iustin Pop
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1851 73e0328b Iustin Pop
                             instance.hvparams, skip_globals)
1852 17463d22 Renรฉ Nussbaumer
1853 73e0328b Iustin Pop
  def SimpleFillBE(self, beparams):
1854 73e0328b Iustin Pop
    """Fill a given beparams dict with cluster defaults.
1855 73e0328b Iustin Pop

1856 06596a60 Guido Trotter
    @type beparams: dict
1857 06596a60 Guido Trotter
    @param beparams: the dict to fill
1858 73e0328b Iustin Pop
    @rtype: dict
1859 73e0328b Iustin Pop
    @return: a copy of the passed in beparams with missing keys filled
1860 73e0328b Iustin Pop
        from the cluster defaults
1861 73e0328b Iustin Pop

1862 73e0328b Iustin Pop
    """
1863 73e0328b Iustin Pop
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1864 5bf7b5cf Iustin Pop
1865 5bf7b5cf Iustin Pop
  def FillBE(self, instance):
1866 73e0328b Iustin Pop
    """Fill an instance's beparams dict with cluster defaults.
1867 5bf7b5cf Iustin Pop

1868 a2a24f4c Guido Trotter
    @type instance: L{objects.Instance}
1869 5bf7b5cf Iustin Pop
    @param instance: the instance parameter to fill
1870 5bf7b5cf Iustin Pop
    @rtype: dict
1871 5bf7b5cf Iustin Pop
    @return: a copy of the instance's beparams with missing keys filled from
1872 5bf7b5cf Iustin Pop
        the cluster defaults
1873 5bf7b5cf Iustin Pop

1874 5bf7b5cf Iustin Pop
    """
1875 73e0328b Iustin Pop
    return self.SimpleFillBE(instance.beparams)
1876 73e0328b Iustin Pop
1877 73e0328b Iustin Pop
  def SimpleFillNIC(self, nicparams):
1878 73e0328b Iustin Pop
    """Fill a given nicparams dict with cluster defaults.
1879 73e0328b Iustin Pop

1880 06596a60 Guido Trotter
    @type nicparams: dict
1881 06596a60 Guido Trotter
    @param nicparams: the dict to fill
1882 73e0328b Iustin Pop
    @rtype: dict
1883 73e0328b Iustin Pop
    @return: a copy of the passed in nicparams with missing keys filled
1884 73e0328b Iustin Pop
        from the cluster defaults
1885 73e0328b Iustin Pop

1886 73e0328b Iustin Pop
    """
1887 73e0328b Iustin Pop
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1888 5bf7b5cf Iustin Pop
1889 a5efec93 Santi Raffa
  def SimpleFillOS(self, os_name,
1890 a5efec93 Santi Raffa
                    os_params_public,
1891 a5efec93 Santi Raffa
                    os_params_private=None,
1892 a5efec93 Santi Raffa
                    os_params_secret=None):
1893 1bdcbbab Iustin Pop
    """Fill an instance's osparams dict with cluster defaults.
1894 1bdcbbab Iustin Pop

1895 1bdcbbab Iustin Pop
    @type os_name: string
1896 1bdcbbab Iustin Pop
    @param os_name: the OS name to use
1897 a5efec93 Santi Raffa
    @type os_params_public: dict
1898 a5efec93 Santi Raffa
    @param os_params_public: the dict to fill with default values
1899 a5efec93 Santi Raffa
    @type os_params_private: dict
1900 a5efec93 Santi Raffa
    @param os_params_private: the dict with private fields to fill
1901 a5efec93 Santi Raffa
                              with default values. Not passing this field
1902 a5efec93 Santi Raffa
                              results in no private fields being added to the
1903 a5efec93 Santi Raffa
                              return value. Private fields will be wrapped in
1904 a5efec93 Santi Raffa
                              L{Private} objects.
1905 a5efec93 Santi Raffa
    @type os_params_secret: dict
1906 a5efec93 Santi Raffa
    @param os_params_secret: the dict with secret fields to fill
1907 a5efec93 Santi Raffa
                             with default values. Not passing this field
1908 a5efec93 Santi Raffa
                             results in no secret fields being added to the
1909 a5efec93 Santi Raffa
                             return value. Private fields will be wrapped in
1910 a5efec93 Santi Raffa
                             L{Private} objects.
1911 1bdcbbab Iustin Pop
    @rtype: dict
1912 1bdcbbab Iustin Pop
    @return: a copy of the instance's osparams with missing keys filled from
1913 a5efec93 Santi Raffa
        the cluster defaults. Private and secret parameters are not included
1914 a5efec93 Santi Raffa
        unless the respective optional parameters are supplied.
1915 1bdcbbab Iustin Pop

1916 1bdcbbab Iustin Pop
    """
1917 1bdcbbab Iustin Pop
    name_only = os_name.split("+", 1)[0]
1918 a5efec93 Santi Raffa
1919 a5efec93 Santi Raffa
    defaults_base_public = self.osparams.get(name_only, {})
1920 a5efec93 Santi Raffa
    defaults_public = FillDict(defaults_base_public,
1921 a5efec93 Santi Raffa
                               self.osparams.get(os_name, {}))
1922 a5efec93 Santi Raffa
    params_public = FillDict(defaults_public, os_params_public)
1923 a5efec93 Santi Raffa
1924 a5efec93 Santi Raffa
    if os_params_private is not None:
1925 a5efec93 Santi Raffa
      defaults_base_private = self.osparams_private_cluster.get(name_only, {})
1926 a5efec93 Santi Raffa
      defaults_private = FillDict(defaults_base_private,
1927 a5efec93 Santi Raffa
                                  self.osparams_private_cluster.get(os_name,
1928 a5efec93 Santi Raffa
                                                                    {}))
1929 a5efec93 Santi Raffa
      params_private = FillDict(defaults_private, os_params_private)
1930 a5efec93 Santi Raffa
    else:
1931 a5efec93 Santi Raffa
      params_private = {}
1932 a5efec93 Santi Raffa
1933 a5efec93 Santi Raffa
    if os_params_secret is not None:
1934 a5efec93 Santi Raffa
      # There can't be default secret settings, so there's nothing to be done.
1935 a5efec93 Santi Raffa
      params_secret = os_params_secret
1936 a5efec93 Santi Raffa
    else:
1937 a5efec93 Santi Raffa
      params_secret = {}
1938 a5efec93 Santi Raffa
1939 a5efec93 Santi Raffa
    # Enforce that the set of keys be distinct:
1940 a5efec93 Santi Raffa
    duplicate_keys = utils.GetRepeatedKeys(params_public,
1941 a5efec93 Santi Raffa
                                           params_private,
1942 a5efec93 Santi Raffa
                                           params_secret)
1943 a5efec93 Santi Raffa
    if not duplicate_keys:
1944 a5efec93 Santi Raffa
1945 a5efec93 Santi Raffa
      # Actually update them:
1946 a5efec93 Santi Raffa
      params_public.update(params_private)
1947 a5efec93 Santi Raffa
      params_public.update(params_secret)
1948 a5efec93 Santi Raffa
1949 a5efec93 Santi Raffa
      return params_public
1950 a5efec93 Santi Raffa
1951 a5efec93 Santi Raffa
    else:
1952 a5efec93 Santi Raffa
1953 a5efec93 Santi Raffa
      def formatter(keys):
1954 a5efec93 Santi Raffa
        return utils.CommaJoin(sorted(map(repr, keys))) if keys else "(none)"
1955 a5efec93 Santi Raffa
1956 a5efec93 Santi Raffa
      #Lose the values.
1957 a5efec93 Santi Raffa
      params_public = set(params_public)
1958 a5efec93 Santi Raffa
      params_private = set(params_private)
1959 a5efec93 Santi Raffa
      params_secret = set(params_secret)
1960 a5efec93 Santi Raffa
1961 a5efec93 Santi Raffa
      msg = """Cannot assign multiple values to OS parameters.
1962 a5efec93 Santi Raffa

1963 a5efec93 Santi Raffa
      Conflicting OS parameters that would have been set by this operation:
1964 a5efec93 Santi Raffa
      - at public visibility:  {public}
1965 a5efec93 Santi Raffa
      - at private visibility: {private}
1966 a5efec93 Santi Raffa
      - at secret visibility:  {secret}
1967 a5efec93 Santi Raffa
      """.format(dupes=formatter(duplicate_keys),
1968 a5efec93 Santi Raffa
                 public=formatter(params_public & duplicate_keys),
1969 a5efec93 Santi Raffa
                 private=formatter(params_private & duplicate_keys),
1970 a5efec93 Santi Raffa
                 secret=formatter(params_secret & duplicate_keys))
1971 a5efec93 Santi Raffa
      raise errors.OpPrereqError(msg)
1972 1bdcbbab Iustin Pop
1973 2da9f556 Renรฉ Nussbaumer
  @staticmethod
1974 2da9f556 Renรฉ Nussbaumer
  def SimpleFillHvState(hv_state):
1975 2da9f556 Renรฉ Nussbaumer
    """Fill an hv_state sub dict with cluster defaults.
1976 2da9f556 Renรฉ Nussbaumer

1977 2da9f556 Renรฉ Nussbaumer
    """
1978 2da9f556 Renรฉ Nussbaumer
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1979 2da9f556 Renรฉ Nussbaumer
1980 2da9f556 Renรฉ Nussbaumer
  @staticmethod
1981 2da9f556 Renรฉ Nussbaumer
  def SimpleFillDiskState(disk_state):
1982 2da9f556 Renรฉ Nussbaumer
    """Fill an disk_state sub dict with cluster defaults.
1983 2da9f556 Renรฉ Nussbaumer

1984 2da9f556 Renรฉ Nussbaumer
    """
1985 2da9f556 Renรฉ Nussbaumer
    return FillDict(constants.DS_DEFAULTS, disk_state)
1986 2da9f556 Renรฉ Nussbaumer
1987 095e71aa Renรฉ Nussbaumer
  def FillND(self, node, nodegroup):
1988 ce523de1 Michael Hanselmann
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1989 095e71aa Renรฉ Nussbaumer

1990 095e71aa Renรฉ Nussbaumer
    @type node: L{objects.Node}
1991 095e71aa Renรฉ Nussbaumer
    @param node: A Node object to fill
1992 095e71aa Renรฉ Nussbaumer
    @type nodegroup: L{objects.NodeGroup}
1993 095e71aa Renรฉ Nussbaumer
    @param nodegroup: A Node object to fill
1994 095e71aa Renรฉ Nussbaumer
    @return a copy of the node's ndparams with defaults filled
1995 095e71aa Renรฉ Nussbaumer

1996 095e71aa Renรฉ Nussbaumer
    """
1997 095e71aa Renรฉ Nussbaumer
    return self.SimpleFillND(nodegroup.FillND(node))
1998 095e71aa Renรฉ Nussbaumer
1999 6b2a2942 Petr Pudlak
  def FillNDGroup(self, nodegroup):
2000 6b2a2942 Petr Pudlak
    """Return filled out ndparams for just L{objects.NodeGroup}
2001 6b2a2942 Petr Pudlak

2002 6b2a2942 Petr Pudlak
    @type nodegroup: L{objects.NodeGroup}
2003 6b2a2942 Petr Pudlak
    @param nodegroup: A Node object to fill
2004 6b2a2942 Petr Pudlak
    @return a copy of the node group's ndparams with defaults filled
2005 6b2a2942 Petr Pudlak

2006 6b2a2942 Petr Pudlak
    """
2007 6b2a2942 Petr Pudlak
    return self.SimpleFillND(nodegroup.SimpleFillND({}))
2008 6b2a2942 Petr Pudlak
2009 095e71aa Renรฉ Nussbaumer
  def SimpleFillND(self, ndparams):
2010 095e71aa Renรฉ Nussbaumer
    """Fill a given ndparams dict with defaults.
2011 095e71aa Renรฉ Nussbaumer

2012 095e71aa Renรฉ Nussbaumer
    @type ndparams: dict
2013 095e71aa Renรฉ Nussbaumer
    @param ndparams: the dict to fill
2014 095e71aa Renรฉ Nussbaumer
    @rtype: dict
2015 095e71aa Renรฉ Nussbaumer
    @return: a copy of the passed in ndparams with missing keys filled
2016 095e71aa Renรฉ Nussbaumer
        from the cluster defaults
2017 095e71aa Renรฉ Nussbaumer

2018 095e71aa Renรฉ Nussbaumer
    """
2019 095e71aa Renรฉ Nussbaumer
    return FillDict(self.ndparams, ndparams)
2020 095e71aa Renรฉ Nussbaumer
2021 918eb80b Agata Murawska
  def SimpleFillIPolicy(self, ipolicy):
2022 918eb80b Agata Murawska
    """ Fill instance policy dict with defaults.
2023 918eb80b Agata Murawska

2024 918eb80b Agata Murawska
    @type ipolicy: dict
2025 918eb80b Agata Murawska
    @param ipolicy: the dict to fill
2026 918eb80b Agata Murawska
    @rtype: dict
2027 918eb80b Agata Murawska
    @return: a copy of passed ipolicy with missing keys filled from
2028 918eb80b Agata Murawska
      the cluster defaults
2029 918eb80b Agata Murawska

2030 918eb80b Agata Murawska
    """
2031 2cc673a3 Iustin Pop
    return FillIPolicy(self.ipolicy, ipolicy)
2032 918eb80b Agata Murawska
2033 ebe93784 Helga Velroyen
  def IsDiskTemplateEnabled(self, disk_template):
2034 ebe93784 Helga Velroyen
    """Checks if a particular disk template is enabled.
2035 ebe93784 Helga Velroyen

2036 ebe93784 Helga Velroyen
    """
2037 ebe93784 Helga Velroyen
    return utils.storage.IsDiskTemplateEnabled(
2038 ebe93784 Helga Velroyen
        disk_template, self.enabled_disk_templates)
2039 ebe93784 Helga Velroyen
2040 ebe93784 Helga Velroyen
  def IsFileStorageEnabled(self):
2041 ebe93784 Helga Velroyen
    """Checks if file storage is enabled.
2042 ebe93784 Helga Velroyen

2043 ebe93784 Helga Velroyen
    """
2044 ebe93784 Helga Velroyen
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
2045 ebe93784 Helga Velroyen
2046 ebe93784 Helga Velroyen
  def IsSharedFileStorageEnabled(self):
2047 ebe93784 Helga Velroyen
    """Checks if shared file storage is enabled.
2048 ebe93784 Helga Velroyen

2049 ebe93784 Helga Velroyen
    """
2050 ebe93784 Helga Velroyen
    return utils.storage.IsSharedFileStorageEnabled(
2051 ebe93784 Helga Velroyen
        self.enabled_disk_templates)
2052 ebe93784 Helga Velroyen
2053 5c947f38 Iustin Pop
2054 96acbc09 Michael Hanselmann
class BlockDevStatus(ConfigObject):
2055 96acbc09 Michael Hanselmann
  """Config object representing the status of a block device."""
2056 96acbc09 Michael Hanselmann
  __slots__ = [
2057 96acbc09 Michael Hanselmann
    "dev_path",
2058 96acbc09 Michael Hanselmann
    "major",
2059 96acbc09 Michael Hanselmann
    "minor",
2060 96acbc09 Michael Hanselmann
    "sync_percent",
2061 96acbc09 Michael Hanselmann
    "estimated_time",
2062 96acbc09 Michael Hanselmann
    "is_degraded",
2063 f208978a Michael Hanselmann
    "ldisk_status",
2064 96acbc09 Michael Hanselmann
    ]
2065 96acbc09 Michael Hanselmann
2066 96acbc09 Michael Hanselmann
2067 2d76b580 Michael Hanselmann
class ImportExportStatus(ConfigObject):
2068 2d76b580 Michael Hanselmann
  """Config object representing the status of an import or export."""
2069 2d76b580 Michael Hanselmann
  __slots__ = [
2070 2d76b580 Michael Hanselmann
    "recent_output",
2071 2d76b580 Michael Hanselmann
    "listen_port",
2072 2d76b580 Michael Hanselmann
    "connected",
2073 c08d76f5 Michael Hanselmann
    "progress_mbytes",
2074 c08d76f5 Michael Hanselmann
    "progress_throughput",
2075 c08d76f5 Michael Hanselmann
    "progress_eta",
2076 c08d76f5 Michael Hanselmann
    "progress_percent",
2077 2d76b580 Michael Hanselmann
    "exit_status",
2078 2d76b580 Michael Hanselmann
    "error_message",
2079 2d76b580 Michael Hanselmann
    ] + _TIMESTAMPS
2080 2d76b580 Michael Hanselmann
2081 2d76b580 Michael Hanselmann
2082 eb630f50 Michael Hanselmann
class ImportExportOptions(ConfigObject):
2083 eb630f50 Michael Hanselmann
  """Options for import/export daemon
2084 eb630f50 Michael Hanselmann

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

2092 eb630f50 Michael Hanselmann
  """
2093 eb630f50 Michael Hanselmann
  __slots__ = [
2094 eb630f50 Michael Hanselmann
    "key_name",
2095 eb630f50 Michael Hanselmann
    "ca_pem",
2096 a5310c2a Michael Hanselmann
    "compress",
2097 af1d39b1 Michael Hanselmann
    "magic",
2098 855d2fc7 Michael Hanselmann
    "ipv6",
2099 4478301b Michael Hanselmann
    "connect_timeout",
2100 eb630f50 Michael Hanselmann
    ]
2101 eb630f50 Michael Hanselmann
2102 eb630f50 Michael Hanselmann
2103 18d750b9 Guido Trotter
class ConfdRequest(ConfigObject):
2104 18d750b9 Guido Trotter
  """Object holding a confd request.
2105 18d750b9 Guido Trotter

2106 18d750b9 Guido Trotter
  @ivar protocol: confd protocol version
2107 18d750b9 Guido Trotter
  @ivar type: confd query type
2108 18d750b9 Guido Trotter
  @ivar query: query request
2109 18d750b9 Guido Trotter
  @ivar rsalt: requested reply salt
2110 18d750b9 Guido Trotter

2111 18d750b9 Guido Trotter
  """
2112 18d750b9 Guido Trotter
  __slots__ = [
2113 18d750b9 Guido Trotter
    "protocol",
2114 18d750b9 Guido Trotter
    "type",
2115 18d750b9 Guido Trotter
    "query",
2116 18d750b9 Guido Trotter
    "rsalt",
2117 18d750b9 Guido Trotter
    ]
2118 18d750b9 Guido Trotter
2119 18d750b9 Guido Trotter
2120 18d750b9 Guido Trotter
class ConfdReply(ConfigObject):
2121 18d750b9 Guido Trotter
  """Object holding a confd reply.
2122 18d750b9 Guido Trotter

2123 18d750b9 Guido Trotter
  @ivar protocol: confd protocol version
2124 18d750b9 Guido Trotter
  @ivar status: reply status code (ok, error)
2125 18d750b9 Guido Trotter
  @ivar answer: confd query reply
2126 18d750b9 Guido Trotter
  @ivar serial: configuration serial number
2127 18d750b9 Guido Trotter

2128 18d750b9 Guido Trotter
  """
2129 18d750b9 Guido Trotter
  __slots__ = [
2130 18d750b9 Guido Trotter
    "protocol",
2131 18d750b9 Guido Trotter
    "status",
2132 18d750b9 Guido Trotter
    "answer",
2133 18d750b9 Guido Trotter
    "serial",
2134 18d750b9 Guido Trotter
    ]
2135 18d750b9 Guido Trotter
2136 18d750b9 Guido Trotter
2137 707f23b5 Michael Hanselmann
class QueryFieldDefinition(ConfigObject):
2138 707f23b5 Michael Hanselmann
  """Object holding a query field definition.
2139 707f23b5 Michael Hanselmann

2140 24d6d3e2 Michael Hanselmann
  @ivar name: Field name
2141 707f23b5 Michael Hanselmann
  @ivar title: Human-readable title
2142 707f23b5 Michael Hanselmann
  @ivar kind: Field type
2143 1ae17369 Michael Hanselmann
  @ivar doc: Human-readable description
2144 707f23b5 Michael Hanselmann

2145 707f23b5 Michael Hanselmann
  """
2146 707f23b5 Michael Hanselmann
  __slots__ = [
2147 707f23b5 Michael Hanselmann
    "name",
2148 707f23b5 Michael Hanselmann
    "title",
2149 707f23b5 Michael Hanselmann
    "kind",
2150 1ae17369 Michael Hanselmann
    "doc",
2151 707f23b5 Michael Hanselmann
    ]
2152 707f23b5 Michael Hanselmann
2153 707f23b5 Michael Hanselmann
2154 0538c375 Michael Hanselmann
class _QueryResponseBase(ConfigObject):
2155 0538c375 Michael Hanselmann
  __slots__ = [
2156 0538c375 Michael Hanselmann
    "fields",
2157 0538c375 Michael Hanselmann
    ]
2158 0538c375 Michael Hanselmann
2159 a5efec93 Santi Raffa
  def ToDict(self, _with_private=False):
2160 0538c375 Michael Hanselmann
    """Custom function for serializing.
2161 0538c375 Michael Hanselmann

2162 0538c375 Michael Hanselmann
    """
2163 0538c375 Michael Hanselmann
    mydict = super(_QueryResponseBase, self).ToDict()
2164 fe502d25 Iustin Pop
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2165 0538c375 Michael Hanselmann
    return mydict
2166 0538c375 Michael Hanselmann
2167 0538c375 Michael Hanselmann
  @classmethod
2168 0538c375 Michael Hanselmann
  def FromDict(cls, val):
2169 0538c375 Michael Hanselmann
    """Custom function for de-serializing.
2170 0538c375 Michael Hanselmann

2171 0538c375 Michael Hanselmann
    """
2172 0538c375 Michael Hanselmann
    obj = super(_QueryResponseBase, cls).FromDict(val)
2173 473ab806 Michael Hanselmann
    obj.fields = \
2174 fe502d25 Iustin Pop
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2175 0538c375 Michael Hanselmann
    return obj
2176 0538c375 Michael Hanselmann
2177 0538c375 Michael Hanselmann
2178 0538c375 Michael Hanselmann
class QueryResponse(_QueryResponseBase):
2179 24d6d3e2 Michael Hanselmann
  """Object holding the response to a query.
2180 24d6d3e2 Michael Hanselmann

2181 24d6d3e2 Michael Hanselmann
  @ivar fields: List of L{QueryFieldDefinition} objects
2182 24d6d3e2 Michael Hanselmann
  @ivar data: Requested data
2183 24d6d3e2 Michael Hanselmann

2184 24d6d3e2 Michael Hanselmann
  """
2185 24d6d3e2 Michael Hanselmann
  __slots__ = [
2186 24d6d3e2 Michael Hanselmann
    "data",
2187 24d6d3e2 Michael Hanselmann
    ]
2188 24d6d3e2 Michael Hanselmann
2189 24d6d3e2 Michael Hanselmann
2190 24d6d3e2 Michael Hanselmann
class QueryFieldsRequest(ConfigObject):
2191 24d6d3e2 Michael Hanselmann
  """Object holding a request for querying available fields.
2192 24d6d3e2 Michael Hanselmann

2193 24d6d3e2 Michael Hanselmann
  """
2194 24d6d3e2 Michael Hanselmann
  __slots__ = [
2195 24d6d3e2 Michael Hanselmann
    "what",
2196 24d6d3e2 Michael Hanselmann
    "fields",
2197 24d6d3e2 Michael Hanselmann
    ]
2198 24d6d3e2 Michael Hanselmann
2199 24d6d3e2 Michael Hanselmann
2200 0538c375 Michael Hanselmann
class QueryFieldsResponse(_QueryResponseBase):
2201 24d6d3e2 Michael Hanselmann
  """Object holding the response to a query for fields.
2202 24d6d3e2 Michael Hanselmann

2203 24d6d3e2 Michael Hanselmann
  @ivar fields: List of L{QueryFieldDefinition} objects
2204 24d6d3e2 Michael Hanselmann

2205 24d6d3e2 Michael Hanselmann
  """
2206 5ae4945a Iustin Pop
  __slots__ = []
2207 24d6d3e2 Michael Hanselmann
2208 24d6d3e2 Michael Hanselmann
2209 6a1434d7 Andrea Spadaccini
class MigrationStatus(ConfigObject):
2210 6a1434d7 Andrea Spadaccini
  """Object holding the status of a migration.
2211 6a1434d7 Andrea Spadaccini

2212 6a1434d7 Andrea Spadaccini
  """
2213 6a1434d7 Andrea Spadaccini
  __slots__ = [
2214 6a1434d7 Andrea Spadaccini
    "status",
2215 6a1434d7 Andrea Spadaccini
    "transferred_ram",
2216 6a1434d7 Andrea Spadaccini
    "total_ram",
2217 6a1434d7 Andrea Spadaccini
    ]
2218 6a1434d7 Andrea Spadaccini
2219 6a1434d7 Andrea Spadaccini
2220 25ce3ec4 Michael Hanselmann
class InstanceConsole(ConfigObject):
2221 25ce3ec4 Michael Hanselmann
  """Object describing how to access the console of an instance.
2222 25ce3ec4 Michael Hanselmann

2223 25ce3ec4 Michael Hanselmann
  """
2224 25ce3ec4 Michael Hanselmann
  __slots__ = [
2225 25ce3ec4 Michael Hanselmann
    "instance",
2226 25ce3ec4 Michael Hanselmann
    "kind",
2227 25ce3ec4 Michael Hanselmann
    "message",
2228 25ce3ec4 Michael Hanselmann
    "host",
2229 25ce3ec4 Michael Hanselmann
    "port",
2230 25ce3ec4 Michael Hanselmann
    "user",
2231 25ce3ec4 Michael Hanselmann
    "command",
2232 25ce3ec4 Michael Hanselmann
    "display",
2233 25ce3ec4 Michael Hanselmann
    ]
2234 25ce3ec4 Michael Hanselmann
2235 25ce3ec4 Michael Hanselmann
  def Validate(self):
2236 25ce3ec4 Michael Hanselmann
    """Validates contents of this object.
2237 25ce3ec4 Michael Hanselmann

2238 25ce3ec4 Michael Hanselmann
    """
2239 25ce3ec4 Michael Hanselmann
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2240 25ce3ec4 Michael Hanselmann
    assert self.instance, "Missing instance name"
2241 4d2cdb5a Andrea Spadaccini
    assert self.message or self.kind in [constants.CONS_SSH,
2242 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2243 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_VNC]
2244 25ce3ec4 Michael Hanselmann
    assert self.host or self.kind == constants.CONS_MESSAGE
2245 25ce3ec4 Michael Hanselmann
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2246 25ce3ec4 Michael Hanselmann
                                      constants.CONS_SSH]
2247 25ce3ec4 Michael Hanselmann
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2248 4d2cdb5a Andrea Spadaccini
                                      constants.CONS_SPICE,
2249 25ce3ec4 Michael Hanselmann
                                      constants.CONS_VNC]
2250 25ce3ec4 Michael Hanselmann
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2251 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2252 25ce3ec4 Michael Hanselmann
                                         constants.CONS_VNC]
2253 25ce3ec4 Michael Hanselmann
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2254 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2255 25ce3ec4 Michael Hanselmann
                                         constants.CONS_SSH]
2256 25ce3ec4 Michael Hanselmann
    return True
2257 25ce3ec4 Michael Hanselmann
2258 25ce3ec4 Michael Hanselmann
2259 8140e24f Dimitris Aragiorgis
class Network(TaggableObject):
2260 eaa4c57c Dimitris Aragiorgis
  """Object representing a network definition for ganeti.
2261 eaa4c57c Dimitris Aragiorgis

2262 eaa4c57c Dimitris Aragiorgis
  """
2263 eaa4c57c Dimitris Aragiorgis
  __slots__ = [
2264 eaa4c57c Dimitris Aragiorgis
    "name",
2265 eaa4c57c Dimitris Aragiorgis
    "serial_no",
2266 eaa4c57c Dimitris Aragiorgis
    "mac_prefix",
2267 eaa4c57c Dimitris Aragiorgis
    "network",
2268 eaa4c57c Dimitris Aragiorgis
    "network6",
2269 eaa4c57c Dimitris Aragiorgis
    "gateway",
2270 eaa4c57c Dimitris Aragiorgis
    "gateway6",
2271 eaa4c57c Dimitris Aragiorgis
    "reservations",
2272 eaa4c57c Dimitris Aragiorgis
    "ext_reservations",
2273 eaa4c57c Dimitris Aragiorgis
    ] + _TIMESTAMPS + _UUID
2274 eaa4c57c Dimitris Aragiorgis
2275 7e8f03e3 Dimitris Aragiorgis
  def HooksDict(self, prefix=""):
2276 d89168ff Guido Trotter
    """Export a dictionary used by hooks with a network's information.
2277 d89168ff Guido Trotter

2278 d89168ff Guido Trotter
    @type prefix: String
2279 d89168ff Guido Trotter
    @param prefix: Prefix to prepend to the dict entries
2280 d89168ff Guido Trotter

2281 d89168ff Guido Trotter
    """
2282 d89168ff Guido Trotter
    result = {
2283 7e8f03e3 Dimitris Aragiorgis
      "%sNETWORK_NAME" % prefix: self.name,
2284 d89168ff Guido Trotter
      "%sNETWORK_UUID" % prefix: self.uuid,
2285 5a76adf7 Dimitris Aragiorgis
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2286 d89168ff Guido Trotter
    }
2287 d89168ff Guido Trotter
    if self.network:
2288 d89168ff Guido Trotter
      result["%sNETWORK_SUBNET" % prefix] = self.network
2289 d89168ff Guido Trotter
    if self.gateway:
2290 d89168ff Guido Trotter
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2291 d89168ff Guido Trotter
    if self.network6:
2292 d89168ff Guido Trotter
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2293 d89168ff Guido Trotter
    if self.gateway6:
2294 d89168ff Guido Trotter
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2295 d89168ff Guido Trotter
    if self.mac_prefix:
2296 d89168ff Guido Trotter
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2297 d89168ff Guido Trotter
2298 d89168ff Guido Trotter
    return result
2299 d89168ff Guido Trotter
2300 5cfa6c37 Dimitris Aragiorgis
  @classmethod
2301 5cfa6c37 Dimitris Aragiorgis
  def FromDict(cls, val):
2302 5cfa6c37 Dimitris Aragiorgis
    """Custom function for networks.
2303 5cfa6c37 Dimitris Aragiorgis

2304 48616625 Dimitris Aragiorgis
    Remove deprecated network_type and family.
2305 5cfa6c37 Dimitris Aragiorgis

2306 5cfa6c37 Dimitris Aragiorgis
    """
2307 5cfa6c37 Dimitris Aragiorgis
    if "network_type" in val:
2308 5cfa6c37 Dimitris Aragiorgis
      del val["network_type"]
2309 48616625 Dimitris Aragiorgis
    if "family" in val:
2310 48616625 Dimitris Aragiorgis
      del val["family"]
2311 5cfa6c37 Dimitris Aragiorgis
    obj = super(Network, cls).FromDict(val)
2312 5cfa6c37 Dimitris Aragiorgis
    return obj
2313 5cfa6c37 Dimitris Aragiorgis
2314 eaa4c57c Dimitris Aragiorgis
2315 523170de Dimitris Aragiorgis
# need to inherit object in order to use super()
2316 523170de Dimitris Aragiorgis
class SerializableConfigParser(ConfigParser.SafeConfigParser, object):
2317 a8083063 Iustin Pop
  """Simple wrapper over ConfigParse that allows serialization.
2318 a8083063 Iustin Pop

2319 a8083063 Iustin Pop
  This class is basically ConfigParser.SafeConfigParser with two
2320 a8083063 Iustin Pop
  additional methods that allow it to serialize/unserialize to/from a
2321 a8083063 Iustin Pop
  buffer.
2322 a8083063 Iustin Pop

2323 a8083063 Iustin Pop
  """
2324 a8083063 Iustin Pop
  def Dumps(self):
2325 a8083063 Iustin Pop
    """Dump this instance and return the string representation."""
2326 a8083063 Iustin Pop
    buf = StringIO()
2327 a8083063 Iustin Pop
    self.write(buf)
2328 a8083063 Iustin Pop
    return buf.getvalue()
2329 a8083063 Iustin Pop
2330 b39bf4bb Guido Trotter
  @classmethod
2331 b39bf4bb Guido Trotter
  def Loads(cls, data):
2332 a8083063 Iustin Pop
    """Load data from a string."""
2333 a8083063 Iustin Pop
    buf = StringIO(data)
2334 b39bf4bb Guido Trotter
    cfp = cls()
2335 a8083063 Iustin Pop
    cfp.readfp(buf)
2336 a8083063 Iustin Pop
    return cfp
2337 59726e15 Bernardo Dal Seno
2338 523170de Dimitris Aragiorgis
  def get(self, section, option, **kwargs):
2339 523170de Dimitris Aragiorgis
    value = None
2340 523170de Dimitris Aragiorgis
    try:
2341 523170de Dimitris Aragiorgis
      value = super(SerializableConfigParser, self).get(section, option,
2342 523170de Dimitris Aragiorgis
                                                        **kwargs)
2343 523170de Dimitris Aragiorgis
      if value.lower() == constants.VALUE_NONE:
2344 523170de Dimitris Aragiorgis
        value = None
2345 523170de Dimitris Aragiorgis
    except ConfigParser.NoOptionError:
2346 ad55b2d4 Klaus Aehlig
      r = re.compile(r"(disk|nic)\d+_name|nic\d+_(network|vlan)")
2347 523170de Dimitris Aragiorgis
      match = r.match(option)
2348 523170de Dimitris Aragiorgis
      if match:
2349 523170de Dimitris Aragiorgis
        pass
2350 523170de Dimitris Aragiorgis
      else:
2351 523170de Dimitris Aragiorgis
        raise
2352 523170de Dimitris Aragiorgis
2353 523170de Dimitris Aragiorgis
    return value
2354 523170de Dimitris Aragiorgis
2355 59726e15 Bernardo Dal Seno
2356 59726e15 Bernardo Dal Seno
class LvmPvInfo(ConfigObject):
2357 59726e15 Bernardo Dal Seno
  """Information about an LVM physical volume (PV).
2358 59726e15 Bernardo Dal Seno

2359 59726e15 Bernardo Dal Seno
  @type name: string
2360 59726e15 Bernardo Dal Seno
  @ivar name: name of the PV
2361 59726e15 Bernardo Dal Seno
  @type vg_name: string
2362 59726e15 Bernardo Dal Seno
  @ivar vg_name: name of the volume group containing the PV
2363 59726e15 Bernardo Dal Seno
  @type size: float
2364 59726e15 Bernardo Dal Seno
  @ivar size: size of the PV in MiB
2365 59726e15 Bernardo Dal Seno
  @type free: float
2366 59726e15 Bernardo Dal Seno
  @ivar free: free space in the PV, in MiB
2367 59726e15 Bernardo Dal Seno
  @type attributes: string
2368 59726e15 Bernardo Dal Seno
  @ivar attributes: PV attributes
2369 b496abdb Bernardo Dal Seno
  @type lv_list: list of strings
2370 b496abdb Bernardo Dal Seno
  @ivar lv_list: names of the LVs hosted on the PV
2371 59726e15 Bernardo Dal Seno
  """
2372 59726e15 Bernardo Dal Seno
  __slots__ = [
2373 59726e15 Bernardo Dal Seno
    "name",
2374 59726e15 Bernardo Dal Seno
    "vg_name",
2375 59726e15 Bernardo Dal Seno
    "size",
2376 59726e15 Bernardo Dal Seno
    "free",
2377 59726e15 Bernardo Dal Seno
    "attributes",
2378 b496abdb Bernardo Dal Seno
    "lv_list"
2379 59726e15 Bernardo Dal Seno
    ]
2380 59726e15 Bernardo Dal Seno
2381 59726e15 Bernardo Dal Seno
  def IsEmpty(self):
2382 59726e15 Bernardo Dal Seno
    """Is this PV empty?
2383 59726e15 Bernardo Dal Seno

2384 59726e15 Bernardo Dal Seno
    """
2385 59726e15 Bernardo Dal Seno
    return self.size <= (self.free + 1)
2386 59726e15 Bernardo Dal Seno
2387 59726e15 Bernardo Dal Seno
  def IsAllocatable(self):
2388 59726e15 Bernardo Dal Seno
    """Is this PV allocatable?
2389 59726e15 Bernardo Dal Seno

2390 59726e15 Bernardo Dal Seno
    """
2391 59726e15 Bernardo Dal Seno
    return ("a" in self.attributes)