Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 8e8cf324

History | View | Annotate | Download (68.3 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 8d4c25f2 Ilias Tsitsimpis
    "disks",
399 3df43542 Guido Trotter
    "serial_no",
400 3df43542 Guido Trotter
    ] + _TIMESTAMPS
401 a8083063 Iustin Pop
402 a5efec93 Santi Raffa
  def ToDict(self, _with_private=False):
403 ff9c047c Iustin Pop
    """Custom function for top-level config data.
404 ff9c047c Iustin Pop

405 8d4c25f2 Ilias Tsitsimpis
    This just replaces the list of nodes, instances, nodegroups,
406 8d4c25f2 Ilias Tsitsimpis
    networks, disks and the cluster with standard python types.
407 ff9c047c Iustin Pop

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

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

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

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

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

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

507 255e19d4 Guido Trotter
    @type nicparams:  dict
508 255e19d4 Guido Trotter
    @param nicparams: dictionary with parameter names/value
509 255e19d4 Guido Trotter
    @raise errors.ConfigurationError: when a parameter is not valid
510 255e19d4 Guido Trotter

511 255e19d4 Guido Trotter
    """
512 53258324 Michael Hanselmann
    mode = nicparams[constants.NIC_MODE]
513 53258324 Michael Hanselmann
    if (mode not in constants.NIC_VALID_MODES and
514 53258324 Michael Hanselmann
        mode != constants.VALUE_AUTO):
515 53258324 Michael Hanselmann
      raise errors.ConfigurationError("Invalid NIC mode '%s'" % mode)
516 255e19d4 Guido Trotter
517 53258324 Michael Hanselmann
    if (mode == constants.NIC_MODE_BRIDGED and
518 255e19d4 Guido Trotter
        not nicparams[constants.NIC_LINK]):
519 53258324 Michael Hanselmann
      raise errors.ConfigurationError("Missing bridged NIC link")
520 255e19d4 Guido Trotter
521 a8083063 Iustin Pop
522 a8083063 Iustin Pop
class Disk(ConfigObject):
523 a8083063 Iustin Pop
  """Config object representing a block device."""
524 a57e502a Thomas Thrainer
  __slots__ = (["name", "dev_type", "logical_id", "children", "iv_name",
525 dd2ddda2 Ilias Tsitsimpis
                "size", "mode", "params", "spindles", "pci", "instance",
526 dd2ddda2 Ilias Tsitsimpis
                "serial_no"]
527 dd2ddda2 Ilias Tsitsimpis
               + _UUID + _TIMESTAMPS +
528 0c3d9c7c Thomas Thrainer
               # dynamic_params is special. It depends on the node this instance
529 0c3d9c7c Thomas Thrainer
               # is sent to, and should not be persisted.
530 0c3d9c7c Thomas Thrainer
               ["dynamic_params"])
531 a8083063 Iustin Pop
532 9e8ff434 Ilias Tsitsimpis
  def _ComputeAllNodes(self):
533 9e8ff434 Ilias Tsitsimpis
    """Compute the list of all nodes covered by a device and its children."""
534 9e8ff434 Ilias Tsitsimpis
    nodes = list()
535 9e8ff434 Ilias Tsitsimpis
536 9e8ff434 Ilias Tsitsimpis
    if self.dev_type in constants.DTS_DRBD:
537 9e8ff434 Ilias Tsitsimpis
      nodea, nodeb = self.logical_id[:2]
538 9e8ff434 Ilias Tsitsimpis
      nodes.append(nodea)
539 9e8ff434 Ilias Tsitsimpis
      nodes.append(nodeb)
540 9e8ff434 Ilias Tsitsimpis
    if self.children:
541 9e8ff434 Ilias Tsitsimpis
      for child in self.children:
542 9e8ff434 Ilias Tsitsimpis
        nodes.extend(child.all_nodes)
543 9e8ff434 Ilias Tsitsimpis
544 9e8ff434 Ilias Tsitsimpis
    return tuple(set(nodes))
545 9e8ff434 Ilias Tsitsimpis
546 9e8ff434 Ilias Tsitsimpis
  all_nodes = property(_ComputeAllNodes, None, None,
547 9e8ff434 Ilias Tsitsimpis
                       "List of names of all the nodes of a disk")
548 9e8ff434 Ilias Tsitsimpis
549 a8083063 Iustin Pop
  def CreateOnSecondary(self):
550 a8083063 Iustin Pop
    """Test if this device needs to be created on a secondary node."""
551 cd3b4ff4 Helga Velroyen
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
552 a8083063 Iustin Pop
553 a8083063 Iustin Pop
  def AssembleOnSecondary(self):
554 a8083063 Iustin Pop
    """Test if this device needs to be assembled on a secondary node."""
555 cd3b4ff4 Helga Velroyen
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
556 a8083063 Iustin Pop
557 a8083063 Iustin Pop
  def OpenOnSecondary(self):
558 a8083063 Iustin Pop
    """Test if this device needs to be opened on a secondary node."""
559 cd3b4ff4 Helga Velroyen
    return self.dev_type in (constants.DT_PLAIN,)
560 a8083063 Iustin Pop
561 222f2dd5 Iustin Pop
  def StaticDevPath(self):
562 222f2dd5 Iustin Pop
    """Return the device path if this device type has a static one.
563 222f2dd5 Iustin Pop

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

568 e51db2a6 Iustin Pop
    @warning: The path returned is not a normalized pathname; callers
569 e51db2a6 Iustin Pop
        should check that it is a valid path.
570 e51db2a6 Iustin Pop

571 222f2dd5 Iustin Pop
    """
572 cd3b4ff4 Helga Velroyen
    if self.dev_type == constants.DT_PLAIN:
573 222f2dd5 Iustin Pop
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
574 cd3b4ff4 Helga Velroyen
    elif self.dev_type == constants.DT_BLOCK:
575 b6135bbc Apollon Oikonomopoulos
      return self.logical_id[1]
576 cd3b4ff4 Helga Velroyen
    elif self.dev_type == constants.DT_RBD:
577 7181fba0 Constantinos Venetsanopoulos
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
578 222f2dd5 Iustin Pop
    return None
579 222f2dd5 Iustin Pop
580 fc1dc9d7 Iustin Pop
  def ChildrenNeeded(self):
581 fc1dc9d7 Iustin Pop
    """Compute the needed number of children for activation.
582 fc1dc9d7 Iustin Pop

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

587 fc1dc9d7 Iustin Pop
    Currently, only DRBD8 supports diskless activation (therefore we
588 fc1dc9d7 Iustin Pop
    return 0), for all other we keep the previous semantics and return
589 fc1dc9d7 Iustin Pop
    -1.
590 fc1dc9d7 Iustin Pop

591 fc1dc9d7 Iustin Pop
    """
592 cd3b4ff4 Helga Velroyen
    if self.dev_type == constants.DT_DRBD8:
593 fc1dc9d7 Iustin Pop
      return 0
594 fc1dc9d7 Iustin Pop
    return -1
595 fc1dc9d7 Iustin Pop
596 51cb1581 Luca Bigliardi
  def IsBasedOnDiskType(self, dev_type):
597 51cb1581 Luca Bigliardi
    """Check if the disk or its children are based on the given type.
598 51cb1581 Luca Bigliardi

599 cd3b4ff4 Helga Velroyen
    @type dev_type: L{constants.DTS_BLOCK}
600 51cb1581 Luca Bigliardi
    @param dev_type: the type to look for
601 51cb1581 Luca Bigliardi
    @rtype: boolean
602 51cb1581 Luca Bigliardi
    @return: boolean indicating if a device of the given type was found or not
603 51cb1581 Luca Bigliardi

604 51cb1581 Luca Bigliardi
    """
605 51cb1581 Luca Bigliardi
    if self.children:
606 51cb1581 Luca Bigliardi
      for child in self.children:
607 51cb1581 Luca Bigliardi
        if child.IsBasedOnDiskType(dev_type):
608 51cb1581 Luca Bigliardi
          return True
609 51cb1581 Luca Bigliardi
    return self.dev_type == dev_type
610 51cb1581 Luca Bigliardi
611 1c3231aa Thomas Thrainer
  def GetNodes(self, node_uuid):
612 a8083063 Iustin Pop
    """This function returns the nodes this device lives on.
613 a8083063 Iustin Pop

614 a8083063 Iustin Pop
    Given the node on which the parent of the device lives on (or, in
615 a8083063 Iustin Pop
    case of a top-level device, the primary node of the devices'
616 a8083063 Iustin Pop
    instance), this function will return a list of nodes on which this
617 a8083063 Iustin Pop
    devices needs to (or can) be assembled.
618 a8083063 Iustin Pop

619 a8083063 Iustin Pop
    """
620 cd3b4ff4 Helga Velroyen
    if self.dev_type in [constants.DT_PLAIN, constants.DT_FILE,
621 cd3b4ff4 Helga Velroyen
                         constants.DT_BLOCK, constants.DT_RBD,
622 8106dd64 Santi Raffa
                         constants.DT_EXT, constants.DT_SHARED_FILE,
623 8106dd64 Santi Raffa
                         constants.DT_GLUSTER]:
624 1c3231aa Thomas Thrainer
      result = [node_uuid]
625 66a37e7a Helga Velroyen
    elif self.dev_type in constants.DTS_DRBD:
626 a8083063 Iustin Pop
      result = [self.logical_id[0], self.logical_id[1]]
627 1c3231aa Thomas Thrainer
      if node_uuid not in result:
628 3ecf6786 Iustin Pop
        raise errors.ConfigurationError("DRBD device passed unknown node")
629 a8083063 Iustin Pop
    else:
630 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
631 a8083063 Iustin Pop
    return result
632 a8083063 Iustin Pop
633 1c3231aa Thomas Thrainer
  def ComputeNodeTree(self, parent_node_uuid):
634 a8083063 Iustin Pop
    """Compute the node/disk tree for this disk and its children.
635 a8083063 Iustin Pop

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

642 a8083063 Iustin Pop
    """
643 1c3231aa Thomas Thrainer
    my_nodes = self.GetNodes(parent_node_uuid)
644 a8083063 Iustin Pop
    result = [(node, self) for node in my_nodes]
645 a8083063 Iustin Pop
    if not self.children:
646 a8083063 Iustin Pop
      # leaf device
647 a8083063 Iustin Pop
      return result
648 a8083063 Iustin Pop
    for node in my_nodes:
649 a8083063 Iustin Pop
      for child in self.children:
650 a8083063 Iustin Pop
        child_result = child.ComputeNodeTree(node)
651 a8083063 Iustin Pop
        if len(child_result) == 1:
652 a8083063 Iustin Pop
          # child (and all its descendants) is simple, doesn't split
653 a8083063 Iustin Pop
          # over multiple hosts, so we don't need to describe it, our
654 a8083063 Iustin Pop
          # own entry for this node describes it completely
655 a8083063 Iustin Pop
          continue
656 a8083063 Iustin Pop
        else:
657 a8083063 Iustin Pop
          # check if child nodes differ from my nodes; note that
658 a8083063 Iustin Pop
          # subdisk can differ from the child itself, and be instead
659 a8083063 Iustin Pop
          # one of its descendants
660 a8083063 Iustin Pop
          for subnode, subdisk in child_result:
661 a8083063 Iustin Pop
            if subnode not in my_nodes:
662 a8083063 Iustin Pop
              result.append((subnode, subdisk))
663 a8083063 Iustin Pop
            # otherwise child is under our own node, so we ignore this
664 a8083063 Iustin Pop
            # entry (but probably the other results in the list will
665 a8083063 Iustin Pop
            # be different)
666 a8083063 Iustin Pop
    return result
667 a8083063 Iustin Pop
668 6d33a6eb Iustin Pop
  def ComputeGrowth(self, amount):
669 6d33a6eb Iustin Pop
    """Compute the per-VG growth requirements.
670 6d33a6eb Iustin Pop

671 6d33a6eb Iustin Pop
    This only works for VG-based disks.
672 6d33a6eb Iustin Pop

673 6d33a6eb Iustin Pop
    @type amount: integer
674 6d33a6eb Iustin Pop
    @param amount: the desired increase in (user-visible) disk space
675 6d33a6eb Iustin Pop
    @rtype: dict
676 6d33a6eb Iustin Pop
    @return: a dictionary of volume-groups and the required size
677 6d33a6eb Iustin Pop

678 6d33a6eb Iustin Pop
    """
679 cd3b4ff4 Helga Velroyen
    if self.dev_type == constants.DT_PLAIN:
680 6d33a6eb Iustin Pop
      return {self.logical_id[0]: amount}
681 cd3b4ff4 Helga Velroyen
    elif self.dev_type == constants.DT_DRBD8:
682 6d33a6eb Iustin Pop
      if self.children:
683 6d33a6eb Iustin Pop
        return self.children[0].ComputeGrowth(amount)
684 6d33a6eb Iustin Pop
      else:
685 6d33a6eb Iustin Pop
        return {}
686 6d33a6eb Iustin Pop
    else:
687 6d33a6eb Iustin Pop
      # Other disk types do not require VG space
688 6d33a6eb Iustin Pop
      return {}
689 6d33a6eb Iustin Pop
690 acec9d51 Iustin Pop
  def RecordGrow(self, amount):
691 acec9d51 Iustin Pop
    """Update the size of this disk after growth.
692 acec9d51 Iustin Pop

693 acec9d51 Iustin Pop
    This method recurses over the disks's children and updates their
694 acec9d51 Iustin Pop
    size correspondigly. The method needs to be kept in sync with the
695 acec9d51 Iustin Pop
    actual algorithms from bdev.
696 acec9d51 Iustin Pop

697 acec9d51 Iustin Pop
    """
698 cd3b4ff4 Helga Velroyen
    if self.dev_type in (constants.DT_PLAIN, constants.DT_FILE,
699 cd3b4ff4 Helga Velroyen
                         constants.DT_RBD, constants.DT_EXT,
700 8106dd64 Santi Raffa
                         constants.DT_SHARED_FILE, constants.DT_GLUSTER):
701 acec9d51 Iustin Pop
      self.size += amount
702 cd3b4ff4 Helga Velroyen
    elif self.dev_type == constants.DT_DRBD8:
703 acec9d51 Iustin Pop
      if self.children:
704 acec9d51 Iustin Pop
        self.children[0].RecordGrow(amount)
705 acec9d51 Iustin Pop
      self.size += amount
706 acec9d51 Iustin Pop
    else:
707 acec9d51 Iustin Pop
      raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
708 acec9d51 Iustin Pop
                                   " disk type %s" % self.dev_type)
709 acec9d51 Iustin Pop
710 b54ecf12 Bernardo Dal Seno
  def Update(self, size=None, mode=None, spindles=None):
711 b54ecf12 Bernardo Dal Seno
    """Apply changes to size, spindles and mode.
712 735e1318 Michael Hanselmann

713 735e1318 Michael Hanselmann
    """
714 cd3b4ff4 Helga Velroyen
    if self.dev_type == constants.DT_DRBD8:
715 735e1318 Michael Hanselmann
      if self.children:
716 735e1318 Michael Hanselmann
        self.children[0].Update(size=size, mode=mode)
717 735e1318 Michael Hanselmann
    else:
718 735e1318 Michael Hanselmann
      assert not self.children
719 735e1318 Michael Hanselmann
720 735e1318 Michael Hanselmann
    if size is not None:
721 735e1318 Michael Hanselmann
      self.size = size
722 735e1318 Michael Hanselmann
    if mode is not None:
723 735e1318 Michael Hanselmann
      self.mode = mode
724 b54ecf12 Bernardo Dal Seno
    if spindles is not None:
725 b54ecf12 Bernardo Dal Seno
      self.spindles = spindles
726 735e1318 Michael Hanselmann
727 a805ec18 Iustin Pop
  def UnsetSize(self):
728 a805ec18 Iustin Pop
    """Sets recursively the size to zero for the disk and its children.
729 a805ec18 Iustin Pop

730 a805ec18 Iustin Pop
    """
731 a805ec18 Iustin Pop
    if self.children:
732 a805ec18 Iustin Pop
      for child in self.children:
733 a805ec18 Iustin Pop
        child.UnsetSize()
734 a805ec18 Iustin Pop
    self.size = 0
735 a805ec18 Iustin Pop
736 0c3d9c7c Thomas Thrainer
  def UpdateDynamicDiskParams(self, target_node_uuid, nodes_ip):
737 0c3d9c7c Thomas Thrainer
    """Updates the dynamic disk params for the given node.
738 0402302c Iustin Pop

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

741 0402302c Iustin Pop
    Arguments:
742 1c3231aa Thomas Thrainer
      - target_node_uuid: the node UUID we wish to configure for
743 0402302c Iustin Pop
      - nodes_ip: a mapping of node name to ip
744 0402302c Iustin Pop

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

748 0402302c Iustin Pop
    """
749 0402302c Iustin Pop
    if self.children:
750 0402302c Iustin Pop
      for child in self.children:
751 0c3d9c7c Thomas Thrainer
        child.UpdateDynamicDiskParams(target_node_uuid, nodes_ip)
752 0402302c Iustin Pop
753 0c3d9c7c Thomas Thrainer
    dyn_disk_params = {}
754 e8c86ab1 Klaus Aehlig
    if self.logical_id is not None and self.dev_type in constants.DTS_DRBD:
755 0c3d9c7c Thomas Thrainer
      pnode_uuid, snode_uuid, _, pminor, sminor, _ = self.logical_id
756 1c3231aa Thomas Thrainer
      if target_node_uuid not in (pnode_uuid, snode_uuid):
757 0c3d9c7c Thomas Thrainer
        # disk object is being sent to neither the primary nor the secondary
758 0c3d9c7c Thomas Thrainer
        # node. reset the dynamic parameters, the target node is not
759 0c3d9c7c Thomas Thrainer
        # supposed to use them.
760 0c3d9c7c Thomas Thrainer
        self.dynamic_params = dyn_disk_params
761 0c3d9c7c Thomas Thrainer
        return
762 0c3d9c7c Thomas Thrainer
763 1c3231aa Thomas Thrainer
      pnode_ip = nodes_ip.get(pnode_uuid, None)
764 1c3231aa Thomas Thrainer
      snode_ip = nodes_ip.get(snode_uuid, None)
765 0402302c Iustin Pop
      if pnode_ip is None or snode_ip is None:
766 0402302c Iustin Pop
        raise errors.ConfigurationError("Can't find primary or secondary node"
767 0402302c Iustin Pop
                                        " for %s" % str(self))
768 1c3231aa Thomas Thrainer
      if pnode_uuid == target_node_uuid:
769 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_LOCAL_IP] = pnode_ip
770 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_REMOTE_IP] = snode_ip
771 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_LOCAL_MINOR] = pminor
772 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_REMOTE_MINOR] = sminor
773 0402302c Iustin Pop
      else: # it must be secondary, we tested above
774 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_LOCAL_IP] = snode_ip
775 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_REMOTE_IP] = pnode_ip
776 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_LOCAL_MINOR] = sminor
777 0c3d9c7c Thomas Thrainer
        dyn_disk_params[constants.DDP_REMOTE_MINOR] = pminor
778 0c3d9c7c Thomas Thrainer
779 0c3d9c7c Thomas Thrainer
    self.dynamic_params = dyn_disk_params
780 0402302c Iustin Pop
781 a0d2a91e Thomas Thrainer
  # pylint: disable=W0221
782 a5efec93 Santi Raffa
  def ToDict(self, include_dynamic_params=False,
783 a5efec93 Santi Raffa
             _with_private=False):
784 ff9c047c Iustin Pop
    """Disk-specific conversion to standard python types.
785 ff9c047c Iustin Pop

786 ff9c047c Iustin Pop
    This replaces the children lists of objects with lists of
787 ff9c047c Iustin Pop
    standard python types.
788 ff9c047c Iustin Pop

789 ff9c047c Iustin Pop
    """
790 ff9c047c Iustin Pop
    bo = super(Disk, self).ToDict()
791 a0d2a91e Thomas Thrainer
    if not include_dynamic_params and "dynamic_params" in bo:
792 a0d2a91e Thomas Thrainer
      del bo["dynamic_params"]
793 ff9c047c Iustin Pop
794 ff9c047c Iustin Pop
    for attr in ("children",):
795 ff9c047c Iustin Pop
      alist = bo.get(attr, None)
796 ff9c047c Iustin Pop
      if alist:
797 fe502d25 Iustin Pop
        bo[attr] = outils.ContainerToDicts(alist)
798 ff9c047c Iustin Pop
    return bo
799 ff9c047c Iustin Pop
800 ff9c047c Iustin Pop
  @classmethod
801 ff9c047c Iustin Pop
  def FromDict(cls, val):
802 ff9c047c Iustin Pop
    """Custom function for Disks
803 ff9c047c Iustin Pop

804 ff9c047c Iustin Pop
    """
805 ff9c047c Iustin Pop
    obj = super(Disk, cls).FromDict(val)
806 ff9c047c Iustin Pop
    if obj.children:
807 fe502d25 Iustin Pop
      obj.children = outils.ContainerFromDicts(obj.children, list, Disk)
808 ff9c047c Iustin Pop
    if obj.logical_id and isinstance(obj.logical_id, list):
809 ff9c047c Iustin Pop
      obj.logical_id = tuple(obj.logical_id)
810 66a37e7a Helga Velroyen
    if obj.dev_type in constants.DTS_DRBD:
811 f9518d38 Iustin Pop
      # we need a tuple of length six here
812 f9518d38 Iustin Pop
      if len(obj.logical_id) < 6:
813 f9518d38 Iustin Pop
        obj.logical_id += (None,) * (6 - len(obj.logical_id))
814 ff9c047c Iustin Pop
    return obj
815 ff9c047c Iustin Pop
816 65a15336 Iustin Pop
  def __str__(self):
817 65a15336 Iustin Pop
    """Custom str() formatter for disks.
818 65a15336 Iustin Pop

819 65a15336 Iustin Pop
    """
820 cd3b4ff4 Helga Velroyen
    if self.dev_type == constants.DT_PLAIN:
821 e687ec01 Michael Hanselmann
      val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
822 66a37e7a Helga Velroyen
    elif self.dev_type in constants.DTS_DRBD:
823 89f28b76 Iustin Pop
      node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
824 00fb8246 Michael Hanselmann
      val = "<DRBD8("
825 073ca59e Iustin Pop
826 a57e502a Thomas Thrainer
      val += ("hosts=%s/%d-%s/%d, port=%s, " %
827 a57e502a Thomas Thrainer
              (node_a, minor_a, node_b, minor_b, port))
828 65a15336 Iustin Pop
      if self.children and self.children.count(None) == 0:
829 65a15336 Iustin Pop
        val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
830 65a15336 Iustin Pop
      else:
831 65a15336 Iustin Pop
        val += "no local storage"
832 65a15336 Iustin Pop
    else:
833 a57e502a Thomas Thrainer
      val = ("<Disk(type=%s, logical_id=%s, children=%s" %
834 a57e502a Thomas Thrainer
             (self.dev_type, self.logical_id, self.children))
835 65a15336 Iustin Pop
    if self.iv_name is None:
836 65a15336 Iustin Pop
      val += ", not visible"
837 65a15336 Iustin Pop
    else:
838 65a15336 Iustin Pop
      val += ", visible as /dev/%s" % self.iv_name
839 b54ecf12 Bernardo Dal Seno
    if self.spindles is not None:
840 b54ecf12 Bernardo Dal Seno
      val += ", spindles=%s" % self.spindles
841 fd965830 Iustin Pop
    if isinstance(self.size, int):
842 fd965830 Iustin Pop
      val += ", size=%dm)>" % self.size
843 fd965830 Iustin Pop
    else:
844 fd965830 Iustin Pop
      val += ", size='%s')>" % (self.size,)
845 65a15336 Iustin Pop
    return val
846 65a15336 Iustin Pop
847 332d0e37 Iustin Pop
  def Verify(self):
848 332d0e37 Iustin Pop
    """Checks that this disk is correctly configured.
849 332d0e37 Iustin Pop

850 332d0e37 Iustin Pop
    """
851 7c4d6c7b Michael Hanselmann
    all_errors = []
852 332d0e37 Iustin Pop
    if self.mode not in constants.DISK_ACCESS_SET:
853 7c4d6c7b Michael Hanselmann
      all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
854 7c4d6c7b Michael Hanselmann
    return all_errors
855 332d0e37 Iustin Pop
856 90d726a8 Iustin Pop
  def UpgradeConfig(self):
857 90d726a8 Iustin Pop
    """Fill defaults for missing configuration values.
858 90d726a8 Iustin Pop

859 90d726a8 Iustin Pop
    """
860 90d726a8 Iustin Pop
    if self.children:
861 90d726a8 Iustin Pop
      for child in self.children:
862 90d726a8 Iustin Pop
        child.UpgradeConfig()
863 bc5d0215 Andrea Spadaccini
864 cce46164 Renรฉ Nussbaumer
    # FIXME: Make this configurable in Ganeti 2.7
865 54666867 Dimitris Aragiorgis
    # Params should be an empty dict that gets filled any time needed
866 54666867 Dimitris Aragiorgis
    # In case of ext template we allow arbitrary params that should not
867 54666867 Dimitris Aragiorgis
    # be overrided during a config reload/upgrade.
868 54666867 Dimitris Aragiorgis
    if not self.params or not isinstance(self.params, dict):
869 54666867 Dimitris Aragiorgis
      self.params = {}
870 54666867 Dimitris Aragiorgis
871 90d726a8 Iustin Pop
    # add here config upgrade for this disk
872 90d726a8 Iustin Pop
873 73d6b4a7 Helga Velroyen
    # map of legacy device types (mapping differing LD constants to new
874 73d6b4a7 Helga Velroyen
    # DT constants)
875 73d6b4a7 Helga Velroyen
    LEG_DEV_TYPE_MAP = {"lvm": constants.DT_PLAIN, "drbd8": constants.DT_DRBD8}
876 73d6b4a7 Helga Velroyen
    if self.dev_type in LEG_DEV_TYPE_MAP:
877 73d6b4a7 Helga Velroyen
      self.dev_type = LEG_DEV_TYPE_MAP[self.dev_type]
878 73d6b4a7 Helga Velroyen
879 cd46491f Renรฉ Nussbaumer
  @staticmethod
880 cd46491f Renรฉ Nussbaumer
  def ComputeLDParams(disk_template, disk_params):
881 cd46491f Renรฉ Nussbaumer
    """Computes Logical Disk parameters from Disk Template parameters.
882 cd46491f Renรฉ Nussbaumer

883 cd46491f Renรฉ Nussbaumer
    @type disk_template: string
884 cd46491f Renรฉ Nussbaumer
    @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
885 cd46491f Renรฉ Nussbaumer
    @type disk_params: dict
886 cd46491f Renรฉ Nussbaumer
    @param disk_params: disk template parameters;
887 cd46491f Renรฉ Nussbaumer
                        dict(template_name -> parameters
888 cd46491f Renรฉ Nussbaumer
    @rtype: list(dict)
889 cd46491f Renรฉ Nussbaumer
    @return: a list of dicts, one for each node of the disk hierarchy. Each dict
890 cd46491f Renรฉ Nussbaumer
      contains the LD parameters of the node. The tree is flattened in-order.
891 cd46491f Renรฉ Nussbaumer

892 cd46491f Renรฉ Nussbaumer
    """
893 cd46491f Renรฉ Nussbaumer
    if disk_template not in constants.DISK_TEMPLATES:
894 cd46491f Renรฉ Nussbaumer
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
895 cd46491f Renรฉ Nussbaumer
896 cd46491f Renรฉ Nussbaumer
    assert disk_template in disk_params
897 cd46491f Renรฉ Nussbaumer
898 cd46491f Renรฉ Nussbaumer
    result = list()
899 cd46491f Renรฉ Nussbaumer
    dt_params = disk_params[disk_template]
900 3fffa0c6 Santi Raffa
901 cd46491f Renรฉ Nussbaumer
    if disk_template == constants.DT_DRBD8:
902 6da90c0a Helga Velroyen
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_DRBD8], {
903 cd46491f Renรฉ Nussbaumer
        constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
904 cd46491f Renรฉ Nussbaumer
        constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
905 cd46491f Renรฉ Nussbaumer
        constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
906 cd46491f Renรฉ Nussbaumer
        constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
907 cd46491f Renรฉ Nussbaumer
        constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
908 cd46491f Renรฉ Nussbaumer
        constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
909 65fc2388 Thomas Thrainer
        constants.LDP_PROTOCOL: dt_params[constants.DRBD_PROTOCOL],
910 cd46491f Renรฉ Nussbaumer
        constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
911 cd46491f Renรฉ Nussbaumer
        constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
912 cd46491f Renรฉ Nussbaumer
        constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
913 cd46491f Renรฉ Nussbaumer
        constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
914 cd46491f Renรฉ Nussbaumer
        constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
915 cd46491f Renรฉ Nussbaumer
        constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
916 52f93ffd Michael Hanselmann
        }))
917 cd46491f Renรฉ Nussbaumer
918 cd46491f Renรฉ Nussbaumer
      # data LV
919 6da90c0a Helga Velroyen
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
920 cd46491f Renรฉ Nussbaumer
        constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
921 52f93ffd Michael Hanselmann
        }))
922 cd46491f Renรฉ Nussbaumer
923 cd46491f Renรฉ Nussbaumer
      # metadata LV
924 6da90c0a Helga Velroyen
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
925 cd46491f Renรฉ Nussbaumer
        constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
926 52f93ffd Michael Hanselmann
        }))
927 52f93ffd Michael Hanselmann
928 3fffa0c6 Santi Raffa
    else:
929 3fffa0c6 Santi Raffa
      defaults = constants.DISK_LD_DEFAULTS[disk_template]
930 3fffa0c6 Santi Raffa
      values = {}
931 3fffa0c6 Santi Raffa
      for field in defaults:
932 3fffa0c6 Santi Raffa
        values[field] = dt_params[field]
933 3fffa0c6 Santi Raffa
      result.append(FillDict(defaults, values))
934 938adc87 Constantinos Venetsanopoulos
935 cd46491f Renรฉ Nussbaumer
    return result
936 cd46491f Renรฉ Nussbaumer
937 a8083063 Iustin Pop
938 918eb80b Agata Murawska
class InstancePolicy(ConfigObject):
939 ffa339ca Iustin Pop
  """Config object representing instance policy limits dictionary.
940 918eb80b Agata Murawska

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

944 ffa339ca Iustin Pop
  """
945 918eb80b Agata Murawska
  @classmethod
946 a2112db5 Helga Velroyen
  def UpgradeDiskTemplates(cls, ipolicy, enabled_disk_templates):
947 a2112db5 Helga Velroyen
    """Upgrades the ipolicy configuration."""
948 a2112db5 Helga Velroyen
    if constants.IPOLICY_DTS in ipolicy:
949 a2112db5 Helga Velroyen
      if not set(ipolicy[constants.IPOLICY_DTS]).issubset(
950 a2112db5 Helga Velroyen
        set(enabled_disk_templates)):
951 a2112db5 Helga Velroyen
        ipolicy[constants.IPOLICY_DTS] = list(
952 a2112db5 Helga Velroyen
          set(ipolicy[constants.IPOLICY_DTS]) & set(enabled_disk_templates))
953 a2112db5 Helga Velroyen
954 a2112db5 Helga Velroyen
  @classmethod
955 8b057218 Renรฉ Nussbaumer
  def CheckParameterSyntax(cls, ipolicy, check_std):
956 918eb80b Agata Murawska
    """ Check the instance policy for validity.
957 918eb80b Agata Murawska

958 da5f09ef Bernardo Dal Seno
    @type ipolicy: dict
959 da5f09ef Bernardo Dal Seno
    @param ipolicy: dictionary with min/max/std specs and policies
960 da5f09ef Bernardo Dal Seno
    @type check_std: bool
961 da5f09ef Bernardo Dal Seno
    @param check_std: Whether to check std value or just assume compliance
962 da5f09ef Bernardo Dal Seno
    @raise errors.ConfigurationError: when the policy is not legal
963 da5f09ef Bernardo Dal Seno

964 918eb80b Agata Murawska
    """
965 62fed51b Bernardo Dal Seno
    InstancePolicy.CheckISpecSyntax(ipolicy, check_std)
966 d04c9d45 Iustin Pop
    if constants.IPOLICY_DTS in ipolicy:
967 d04c9d45 Iustin Pop
      InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
968 ff6c5e55 Iustin Pop
    for key in constants.IPOLICY_PARAMETERS:
969 ff6c5e55 Iustin Pop
      if key in ipolicy:
970 ff6c5e55 Iustin Pop
        InstancePolicy.CheckParameter(key, ipolicy[key])
971 57dc299a Iustin Pop
    wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
972 57dc299a Iustin Pop
    if wrong_keys:
973 57dc299a Iustin Pop
      raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
974 57dc299a Iustin Pop
                                      utils.CommaJoin(wrong_keys))
975 918eb80b Agata Murawska
976 918eb80b Agata Murawska
  @classmethod
977 0f511c8a Bernardo Dal Seno
  def _CheckIncompleteSpec(cls, spec, keyname):
978 0f511c8a Bernardo Dal Seno
    missing_params = constants.ISPECS_PARAMETERS - frozenset(spec.keys())
979 0f511c8a Bernardo Dal Seno
    if missing_params:
980 0f511c8a Bernardo Dal Seno
      msg = ("Missing instance specs parameters for %s: %s" %
981 0f511c8a Bernardo Dal Seno
             (keyname, utils.CommaJoin(missing_params)))
982 0f511c8a Bernardo Dal Seno
      raise errors.ConfigurationError(msg)
983 0f511c8a Bernardo Dal Seno
984 0f511c8a Bernardo Dal Seno
  @classmethod
985 62fed51b Bernardo Dal Seno
  def CheckISpecSyntax(cls, ipolicy, check_std):
986 62fed51b Bernardo Dal Seno
    """Check the instance policy specs for validity.
987 62fed51b Bernardo Dal Seno

988 62fed51b Bernardo Dal Seno
    @type ipolicy: dict
989 62fed51b Bernardo Dal Seno
    @param ipolicy: dictionary with min/max/std specs
990 62fed51b Bernardo Dal Seno
    @type check_std: bool
991 62fed51b Bernardo Dal Seno
    @param check_std: Whether to check std value or just assume compliance
992 62fed51b Bernardo Dal Seno
    @raise errors.ConfigurationError: when specs are not valid
993 62fed51b Bernardo Dal Seno

994 62fed51b Bernardo Dal Seno
    """
995 62fed51b Bernardo Dal Seno
    if constants.ISPECS_MINMAX not in ipolicy:
996 62fed51b Bernardo Dal Seno
      # Nothing to check
997 62fed51b Bernardo Dal Seno
      return
998 62fed51b Bernardo Dal Seno
999 62fed51b Bernardo Dal Seno
    if check_std and constants.ISPECS_STD not in ipolicy:
1000 62fed51b Bernardo Dal Seno
      msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
1001 62fed51b Bernardo Dal Seno
      raise errors.ConfigurationError(msg)
1002 62fed51b Bernardo Dal Seno
    stdspec = ipolicy.get(constants.ISPECS_STD)
1003 b342c9dd Bernardo Dal Seno
    if check_std:
1004 b342c9dd Bernardo Dal Seno
      InstancePolicy._CheckIncompleteSpec(stdspec, constants.ISPECS_STD)
1005 b342c9dd Bernardo Dal Seno
1006 41044e04 Bernardo Dal Seno
    if not ipolicy[constants.ISPECS_MINMAX]:
1007 41044e04 Bernardo Dal Seno
      raise errors.ConfigurationError("Empty minmax specifications")
1008 41044e04 Bernardo Dal Seno
    std_is_good = False
1009 41044e04 Bernardo Dal Seno
    for minmaxspecs in ipolicy[constants.ISPECS_MINMAX]:
1010 41044e04 Bernardo Dal Seno
      missing = constants.ISPECS_MINMAX_KEYS - frozenset(minmaxspecs.keys())
1011 41044e04 Bernardo Dal Seno
      if missing:
1012 41044e04 Bernardo Dal Seno
        msg = "Missing instance specification: %s" % utils.CommaJoin(missing)
1013 41044e04 Bernardo Dal Seno
        raise errors.ConfigurationError(msg)
1014 41044e04 Bernardo Dal Seno
      for (key, spec) in minmaxspecs.items():
1015 41044e04 Bernardo Dal Seno
        InstancePolicy._CheckIncompleteSpec(spec, key)
1016 41044e04 Bernardo Dal Seno
1017 41044e04 Bernardo Dal Seno
      spec_std_ok = True
1018 41044e04 Bernardo Dal Seno
      for param in constants.ISPECS_PARAMETERS:
1019 41044e04 Bernardo Dal Seno
        par_std_ok = InstancePolicy._CheckISpecParamSyntax(minmaxspecs, stdspec,
1020 41044e04 Bernardo Dal Seno
                                                           param, check_std)
1021 41044e04 Bernardo Dal Seno
        spec_std_ok = spec_std_ok and par_std_ok
1022 41044e04 Bernardo Dal Seno
      std_is_good = std_is_good or spec_std_ok
1023 41044e04 Bernardo Dal Seno
    if not std_is_good:
1024 b342c9dd Bernardo Dal Seno
      raise errors.ConfigurationError("Invalid std specifications")
1025 62fed51b Bernardo Dal Seno
1026 62fed51b Bernardo Dal Seno
  @classmethod
1027 62fed51b Bernardo Dal Seno
  def _CheckISpecParamSyntax(cls, minmaxspecs, stdspec, name, check_std):
1028 da5f09ef Bernardo Dal Seno
    """Check the instance policy specs for validity on a given key.
1029 918eb80b Agata Murawska

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

1033 da5f09ef Bernardo Dal Seno
    @type minmaxspecs: dict
1034 da5f09ef Bernardo Dal Seno
    @param minmaxspecs: dictionary with min and max instance spec
1035 da5f09ef Bernardo Dal Seno
    @type stdspec: dict
1036 da5f09ef Bernardo Dal Seno
    @param stdspec: dictionary with standard instance spec
1037 918eb80b Agata Murawska
    @type name: string
1038 918eb80b Agata Murawska
    @param name: what are the limits for
1039 8b057218 Renรฉ Nussbaumer
    @type check_std: bool
1040 8b057218 Renรฉ Nussbaumer
    @param check_std: Whether to check std value or just assume compliance
1041 b342c9dd Bernardo Dal Seno
    @rtype: bool
1042 b342c9dd Bernardo Dal Seno
    @return: C{True} when specs are valid, C{False} when standard spec for the
1043 b342c9dd Bernardo Dal Seno
        given name is not valid
1044 b342c9dd Bernardo Dal Seno
    @raise errors.ConfigurationError: when min/max specs for the given name
1045 b342c9dd Bernardo Dal Seno
        are not valid
1046 918eb80b Agata Murawska

1047 918eb80b Agata Murawska
    """
1048 da5f09ef Bernardo Dal Seno
    minspec = minmaxspecs[constants.ISPECS_MIN]
1049 da5f09ef Bernardo Dal Seno
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1050 0f511c8a Bernardo Dal Seno
    min_v = minspec[name]
1051 b342c9dd Bernardo Dal Seno
    max_v = maxspec[name]
1052 8b057218 Renรฉ Nussbaumer
1053 b342c9dd Bernardo Dal Seno
    if min_v > max_v:
1054 b342c9dd Bernardo Dal Seno
      err = ("Invalid specification of min/max values for %s: %s/%s" %
1055 b342c9dd Bernardo Dal Seno
             (name, min_v, max_v))
1056 b342c9dd Bernardo Dal Seno
      raise errors.ConfigurationError(err)
1057 b342c9dd Bernardo Dal Seno
    elif check_std:
1058 da5f09ef Bernardo Dal Seno
      std_v = stdspec.get(name, min_v)
1059 b342c9dd Bernardo Dal Seno
      return std_v >= min_v and std_v <= max_v
1060 8b057218 Renรฉ Nussbaumer
    else:
1061 b342c9dd Bernardo Dal Seno
      return True
1062 918eb80b Agata Murawska
1063 2cc673a3 Iustin Pop
  @classmethod
1064 2cc673a3 Iustin Pop
  def CheckDiskTemplates(cls, disk_templates):
1065 2cc673a3 Iustin Pop
    """Checks the disk templates for validity.
1066 2cc673a3 Iustin Pop

1067 2cc673a3 Iustin Pop
    """
1068 ba5c6c6b Bernardo Dal Seno
    if not disk_templates:
1069 ba5c6c6b Bernardo Dal Seno
      raise errors.ConfigurationError("Instance policy must contain" +
1070 ba5c6c6b Bernardo Dal Seno
                                      " at least one disk template")
1071 2cc673a3 Iustin Pop
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1072 2cc673a3 Iustin Pop
    if wrong:
1073 2cc673a3 Iustin Pop
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1074 2cc673a3 Iustin Pop
                                      utils.CommaJoin(wrong))
1075 2cc673a3 Iustin Pop
1076 ff6c5e55 Iustin Pop
  @classmethod
1077 ff6c5e55 Iustin Pop
  def CheckParameter(cls, key, value):
1078 ff6c5e55 Iustin Pop
    """Checks a parameter.
1079 ff6c5e55 Iustin Pop

1080 ff6c5e55 Iustin Pop
    Currently we expect all parameters to be float values.
1081 ff6c5e55 Iustin Pop

1082 ff6c5e55 Iustin Pop
    """
1083 ff6c5e55 Iustin Pop
    try:
1084 ff6c5e55 Iustin Pop
      float(value)
1085 ff6c5e55 Iustin Pop
    except (TypeError, ValueError), err:
1086 ff6c5e55 Iustin Pop
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1087 ff6c5e55 Iustin Pop
                                      " '%s', error: %s" % (key, value, err))
1088 ff6c5e55 Iustin Pop
1089 918eb80b Agata Murawska
1090 ec29fe40 Iustin Pop
class Instance(TaggableObject):
1091 a8083063 Iustin Pop
  """Config object representing an instance."""
1092 154b9580 Balazs Lecz
  __slots__ = [
1093 a8083063 Iustin Pop
    "name",
1094 a8083063 Iustin Pop
    "primary_node",
1095 6ccce5d4 Ilias Tsitsimpis
    "secondary_nodes",
1096 a8083063 Iustin Pop
    "os",
1097 e69d05fd Iustin Pop
    "hypervisor",
1098 5bf7b5cf Iustin Pop
    "hvparams",
1099 5bf7b5cf Iustin Pop
    "beparams",
1100 1bdcbbab Iustin Pop
    "osparams",
1101 a5efec93 Santi Raffa
    "osparams_private",
1102 9ca8a7c5 Agata Murawska
    "admin_state",
1103 a8083063 Iustin Pop
    "nics",
1104 a8083063 Iustin Pop
    "disks",
1105 8e8cf324 Ilias Tsitsimpis
    "disks_info",
1106 a8083063 Iustin Pop
    "disk_template",
1107 1d4a4b26 Thomas Thrainer
    "disks_active",
1108 58acb49d Alexander Schreiber
    "network_port",
1109 be1fa613 Iustin Pop
    "serial_no",
1110 e1dcc53a Iustin Pop
    ] + _TIMESTAMPS + _UUID
1111 a8083063 Iustin Pop
1112 ad24e046 Iustin Pop
  def FindDisk(self, idx):
1113 ad24e046 Iustin Pop
    """Find a disk given having a specified index.
1114 644eeef9 Iustin Pop

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

1117 ad24e046 Iustin Pop
    @type idx: int
1118 ad24e046 Iustin Pop
    @param idx: the disk index
1119 ad24e046 Iustin Pop
    @rtype: L{Disk}
1120 ad24e046 Iustin Pop
    @return: the corresponding disk
1121 ad24e046 Iustin Pop
    @raise errors.OpPrereqError: when the given index is not valid
1122 644eeef9 Iustin Pop

1123 ad24e046 Iustin Pop
    """
1124 ad24e046 Iustin Pop
    try:
1125 ad24e046 Iustin Pop
      idx = int(idx)
1126 ad24e046 Iustin Pop
      return self.disks[idx]
1127 691744c4 Iustin Pop
    except (TypeError, ValueError), err:
1128 debac808 Iustin Pop
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1129 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
1130 ad24e046 Iustin Pop
    except IndexError:
1131 ad24e046 Iustin Pop
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1132 daa55b04 Michael Hanselmann
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1133 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
1134 644eeef9 Iustin Pop
1135 a5efec93 Santi Raffa
  def ToDict(self, _with_private=False):
1136 ff9c047c Iustin Pop
    """Instance-specific conversion to standard python types.
1137 ff9c047c Iustin Pop

1138 ff9c047c Iustin Pop
    This replaces the children lists of objects with lists of standard
1139 ff9c047c Iustin Pop
    python types.
1140 ff9c047c Iustin Pop

1141 ff9c047c Iustin Pop
    """
1142 a5efec93 Santi Raffa
    bo = super(Instance, self).ToDict(_with_private=_with_private)
1143 a5efec93 Santi Raffa
1144 a5efec93 Santi Raffa
    if _with_private:
1145 a5efec93 Santi Raffa
      bo["osparams_private"] = self.osparams_private.Unprivate()
1146 ff9c047c Iustin Pop
1147 8e8cf324 Ilias Tsitsimpis
    for attr in "nics", "disks", "disks_info":
1148 ff9c047c Iustin Pop
      alist = bo.get(attr, None)
1149 ff9c047c Iustin Pop
      if alist:
1150 fe502d25 Iustin Pop
        nlist = outils.ContainerToDicts(alist)
1151 ff9c047c Iustin Pop
      else:
1152 ff9c047c Iustin Pop
        nlist = []
1153 ff9c047c Iustin Pop
      bo[attr] = nlist
1154 ff9c047c Iustin Pop
    return bo
1155 ff9c047c Iustin Pop
1156 ff9c047c Iustin Pop
  @classmethod
1157 ff9c047c Iustin Pop
  def FromDict(cls, val):
1158 ff9c047c Iustin Pop
    """Custom function for instances.
1159 ff9c047c Iustin Pop

1160 ff9c047c Iustin Pop
    """
1161 9ca8a7c5 Agata Murawska
    if "admin_state" not in val:
1162 9ca8a7c5 Agata Murawska
      if val.get("admin_up", False):
1163 9ca8a7c5 Agata Murawska
        val["admin_state"] = constants.ADMINST_UP
1164 9ca8a7c5 Agata Murawska
      else:
1165 9ca8a7c5 Agata Murawska
        val["admin_state"] = constants.ADMINST_DOWN
1166 9ca8a7c5 Agata Murawska
    if "admin_up" in val:
1167 9ca8a7c5 Agata Murawska
      del val["admin_up"]
1168 ff9c047c Iustin Pop
    obj = super(Instance, cls).FromDict(val)
1169 fe502d25 Iustin Pop
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1170 fe502d25 Iustin Pop
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1171 8e8cf324 Ilias Tsitsimpis
    obj.disks_info = outils.ContainerFromDicts(obj.disks_info, list, Disk)
1172 ff9c047c Iustin Pop
    return obj
1173 ff9c047c Iustin Pop
1174 90d726a8 Iustin Pop
  def UpgradeConfig(self):
1175 90d726a8 Iustin Pop
    """Fill defaults for missing configuration values.
1176 90d726a8 Iustin Pop

1177 90d726a8 Iustin Pop
    """
1178 90d726a8 Iustin Pop
    for nic in self.nics:
1179 90d726a8 Iustin Pop
      nic.UpgradeConfig()
1180 90d726a8 Iustin Pop
    for disk in self.disks:
1181 90d726a8 Iustin Pop
      disk.UpgradeConfig()
1182 7736a5f2 Iustin Pop
    if self.hvparams:
1183 7736a5f2 Iustin Pop
      for key in constants.HVC_GLOBALS:
1184 7736a5f2 Iustin Pop
        try:
1185 7736a5f2 Iustin Pop
          del self.hvparams[key]
1186 7736a5f2 Iustin Pop
        except KeyError:
1187 7736a5f2 Iustin Pop
          pass
1188 1bdcbbab Iustin Pop
    if self.osparams is None:
1189 1bdcbbab Iustin Pop
      self.osparams = {}
1190 a5efec93 Santi Raffa
    if self.osparams_private is None:
1191 a5efec93 Santi Raffa
      self.osparams_private = serializer.PrivateDict()
1192 8c72ab2b Guido Trotter
    UpgradeBeParams(self.beparams)
1193 a8e07057 Thomas Thrainer
    if self.disks_active is None:
1194 a8e07057 Thomas Thrainer
      self.disks_active = self.admin_state == constants.ADMINST_UP
1195 90d726a8 Iustin Pop
1196 a8083063 Iustin Pop
1197 a8083063 Iustin Pop
class OS(ConfigObject):
1198 b41b3516 Iustin Pop
  """Config object representing an operating system.
1199 b41b3516 Iustin Pop

1200 b41b3516 Iustin Pop
  @type supported_parameters: list
1201 b41b3516 Iustin Pop
  @ivar supported_parameters: a list of tuples, name and description,
1202 b41b3516 Iustin Pop
      containing the supported parameters by this OS
1203 b41b3516 Iustin Pop

1204 870dc44c Iustin Pop
  @type VARIANT_DELIM: string
1205 870dc44c Iustin Pop
  @cvar VARIANT_DELIM: the variant delimiter
1206 870dc44c Iustin Pop

1207 b41b3516 Iustin Pop
  """
1208 a8083063 Iustin Pop
  __slots__ = [
1209 a8083063 Iustin Pop
    "name",
1210 a8083063 Iustin Pop
    "path",
1211 082a7f91 Guido Trotter
    "api_versions",
1212 a8083063 Iustin Pop
    "create_script",
1213 a8083063 Iustin Pop
    "export_script",
1214 386b57af Iustin Pop
    "import_script",
1215 386b57af Iustin Pop
    "rename_script",
1216 b41b3516 Iustin Pop
    "verify_script",
1217 6d79896b Guido Trotter
    "supported_variants",
1218 b41b3516 Iustin Pop
    "supported_parameters",
1219 a8083063 Iustin Pop
    ]
1220 a8083063 Iustin Pop
1221 870dc44c Iustin Pop
  VARIANT_DELIM = "+"
1222 870dc44c Iustin Pop
1223 870dc44c Iustin Pop
  @classmethod
1224 870dc44c Iustin Pop
  def SplitNameVariant(cls, name):
1225 870dc44c Iustin Pop
    """Splits the name into the proper name and variant.
1226 870dc44c Iustin Pop

1227 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1228 870dc44c Iustin Pop
    @rtype: list
1229 870dc44c Iustin Pop
    @return: a list of two elements; if the original name didn't
1230 870dc44c Iustin Pop
        contain a variant, it's returned as an empty string
1231 870dc44c Iustin Pop

1232 870dc44c Iustin Pop
    """
1233 870dc44c Iustin Pop
    nv = name.split(cls.VARIANT_DELIM, 1)
1234 870dc44c Iustin Pop
    if len(nv) == 1:
1235 870dc44c Iustin Pop
      nv.append("")
1236 870dc44c Iustin Pop
    return nv
1237 870dc44c Iustin Pop
1238 870dc44c Iustin Pop
  @classmethod
1239 870dc44c Iustin Pop
  def GetName(cls, name):
1240 870dc44c Iustin Pop
    """Returns the proper name of the os (without the variant).
1241 870dc44c Iustin Pop

1242 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1243 870dc44c Iustin Pop

1244 870dc44c Iustin Pop
    """
1245 870dc44c Iustin Pop
    return cls.SplitNameVariant(name)[0]
1246 870dc44c Iustin Pop
1247 870dc44c Iustin Pop
  @classmethod
1248 870dc44c Iustin Pop
  def GetVariant(cls, name):
1249 870dc44c Iustin Pop
    """Returns the variant the os (without the base name).
1250 870dc44c Iustin Pop

1251 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1252 870dc44c Iustin Pop

1253 870dc44c Iustin Pop
    """
1254 870dc44c Iustin Pop
    return cls.SplitNameVariant(name)[1]
1255 870dc44c Iustin Pop
1256 7c0d6283 Michael Hanselmann
1257 376631d1 Constantinos Venetsanopoulos
class ExtStorage(ConfigObject):
1258 376631d1 Constantinos Venetsanopoulos
  """Config object representing an External Storage Provider.
1259 376631d1 Constantinos Venetsanopoulos

1260 376631d1 Constantinos Venetsanopoulos
  """
1261 376631d1 Constantinos Venetsanopoulos
  __slots__ = [
1262 376631d1 Constantinos Venetsanopoulos
    "name",
1263 376631d1 Constantinos Venetsanopoulos
    "path",
1264 376631d1 Constantinos Venetsanopoulos
    "create_script",
1265 376631d1 Constantinos Venetsanopoulos
    "remove_script",
1266 376631d1 Constantinos Venetsanopoulos
    "grow_script",
1267 376631d1 Constantinos Venetsanopoulos
    "attach_script",
1268 376631d1 Constantinos Venetsanopoulos
    "detach_script",
1269 376631d1 Constantinos Venetsanopoulos
    "setinfo_script",
1270 938adc87 Constantinos Venetsanopoulos
    "verify_script",
1271 938adc87 Constantinos Venetsanopoulos
    "supported_parameters",
1272 376631d1 Constantinos Venetsanopoulos
    ]
1273 376631d1 Constantinos Venetsanopoulos
1274 376631d1 Constantinos Venetsanopoulos
1275 5f06ce5e Michael Hanselmann
class NodeHvState(ConfigObject):
1276 5f06ce5e Michael Hanselmann
  """Hypvervisor state on a node.
1277 5f06ce5e Michael Hanselmann

1278 5f06ce5e Michael Hanselmann
  @ivar mem_total: Total amount of memory
1279 5f06ce5e Michael Hanselmann
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1280 5f06ce5e Michael Hanselmann
    available)
1281 5f06ce5e Michael Hanselmann
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1282 5f06ce5e Michael Hanselmann
    rounding
1283 5f06ce5e Michael Hanselmann
  @ivar mem_inst: Memory used by instances living on node
1284 5f06ce5e Michael Hanselmann
  @ivar cpu_total: Total node CPU core count
1285 5f06ce5e Michael Hanselmann
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1286 5f06ce5e Michael Hanselmann

1287 5f06ce5e Michael Hanselmann
  """
1288 5f06ce5e Michael Hanselmann
  __slots__ = [
1289 5f06ce5e Michael Hanselmann
    "mem_total",
1290 5f06ce5e Michael Hanselmann
    "mem_node",
1291 5f06ce5e Michael Hanselmann
    "mem_hv",
1292 5f06ce5e Michael Hanselmann
    "mem_inst",
1293 5f06ce5e Michael Hanselmann
    "cpu_total",
1294 5f06ce5e Michael Hanselmann
    "cpu_node",
1295 5f06ce5e Michael Hanselmann
    ] + _TIMESTAMPS
1296 5f06ce5e Michael Hanselmann
1297 5f06ce5e Michael Hanselmann
1298 5f06ce5e Michael Hanselmann
class NodeDiskState(ConfigObject):
1299 5f06ce5e Michael Hanselmann
  """Disk state on a node.
1300 5f06ce5e Michael Hanselmann

1301 5f06ce5e Michael Hanselmann
  """
1302 5f06ce5e Michael Hanselmann
  __slots__ = [
1303 5f06ce5e Michael Hanselmann
    "total",
1304 5f06ce5e Michael Hanselmann
    "reserved",
1305 5f06ce5e Michael Hanselmann
    "overhead",
1306 5f06ce5e Michael Hanselmann
    ] + _TIMESTAMPS
1307 5f06ce5e Michael Hanselmann
1308 5f06ce5e Michael Hanselmann
1309 ec29fe40 Iustin Pop
class Node(TaggableObject):
1310 634d30f4 Michael Hanselmann
  """Config object representing a node.
1311 634d30f4 Michael Hanselmann

1312 634d30f4 Michael Hanselmann
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1313 634d30f4 Michael Hanselmann
  @ivar hv_state_static: Hypervisor state overriden by user
1314 634d30f4 Michael Hanselmann
  @ivar disk_state: Disk state (e.g. free space)
1315 634d30f4 Michael Hanselmann
  @ivar disk_state_static: Disk state overriden by user
1316 634d30f4 Michael Hanselmann

1317 634d30f4 Michael Hanselmann
  """
1318 154b9580 Balazs Lecz
  __slots__ = [
1319 ec29fe40 Iustin Pop
    "name",
1320 ec29fe40 Iustin Pop
    "primary_ip",
1321 ec29fe40 Iustin Pop
    "secondary_ip",
1322 be1fa613 Iustin Pop
    "serial_no",
1323 8b8b8b81 Iustin Pop
    "master_candidate",
1324 fc0fe88c Iustin Pop
    "offline",
1325 af64c0ea Iustin Pop
    "drained",
1326 f936c153 Iustin Pop
    "group",
1327 490acd18 Iustin Pop
    "master_capable",
1328 490acd18 Iustin Pop
    "vm_capable",
1329 095e71aa Renรฉ Nussbaumer
    "ndparams",
1330 25124d4a Renรฉ Nussbaumer
    "powered",
1331 5b49ed09 Renรฉ Nussbaumer
    "hv_state",
1332 634d30f4 Michael Hanselmann
    "hv_state_static",
1333 5b49ed09 Renรฉ Nussbaumer
    "disk_state",
1334 634d30f4 Michael Hanselmann
    "disk_state_static",
1335 e1dcc53a Iustin Pop
    ] + _TIMESTAMPS + _UUID
1336 a8083063 Iustin Pop
1337 490acd18 Iustin Pop
  def UpgradeConfig(self):
1338 490acd18 Iustin Pop
    """Fill defaults for missing configuration values.
1339 490acd18 Iustin Pop

1340 490acd18 Iustin Pop
    """
1341 b459a848 Andrea Spadaccini
    # pylint: disable=E0203
1342 490acd18 Iustin Pop
    # because these are "defined" via slots, not manually
1343 490acd18 Iustin Pop
    if self.master_capable is None:
1344 490acd18 Iustin Pop
      self.master_capable = True
1345 490acd18 Iustin Pop
1346 490acd18 Iustin Pop
    if self.vm_capable is None:
1347 490acd18 Iustin Pop
      self.vm_capable = True
1348 490acd18 Iustin Pop
1349 095e71aa Renรฉ Nussbaumer
    if self.ndparams is None:
1350 095e71aa Renรฉ Nussbaumer
      self.ndparams = {}
1351 250a9404 Bernardo Dal Seno
    # And remove any global parameter
1352 250a9404 Bernardo Dal Seno
    for key in constants.NDC_GLOBALS:
1353 250a9404 Bernardo Dal Seno
      if key in self.ndparams:
1354 250a9404 Bernardo Dal Seno
        logging.warning("Ignoring %s node parameter for node %s",
1355 250a9404 Bernardo Dal Seno
                        key, self.name)
1356 250a9404 Bernardo Dal Seno
        del self.ndparams[key]
1357 095e71aa Renรฉ Nussbaumer
1358 25124d4a Renรฉ Nussbaumer
    if self.powered is None:
1359 25124d4a Renรฉ Nussbaumer
      self.powered = True
1360 25124d4a Renรฉ Nussbaumer
1361 a5efec93 Santi Raffa
  def ToDict(self, _with_private=False):
1362 5f06ce5e Michael Hanselmann
    """Custom function for serializing.
1363 5f06ce5e Michael Hanselmann

1364 5f06ce5e Michael Hanselmann
    """
1365 a5efec93 Santi Raffa
    data = super(Node, self).ToDict(_with_private=_with_private)
1366 5f06ce5e Michael Hanselmann
1367 5f06ce5e Michael Hanselmann
    hv_state = data.get("hv_state", None)
1368 5f06ce5e Michael Hanselmann
    if hv_state is not None:
1369 fe502d25 Iustin Pop
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1370 5f06ce5e Michael Hanselmann
1371 5f06ce5e Michael Hanselmann
    disk_state = data.get("disk_state", None)
1372 5f06ce5e Michael Hanselmann
    if disk_state is not None:
1373 5f06ce5e Michael Hanselmann
      data["disk_state"] = \
1374 fe502d25 Iustin Pop
        dict((key, outils.ContainerToDicts(value))
1375 5f06ce5e Michael Hanselmann
             for (key, value) in disk_state.items())
1376 5f06ce5e Michael Hanselmann
1377 5f06ce5e Michael Hanselmann
    return data
1378 5f06ce5e Michael Hanselmann
1379 5f06ce5e Michael Hanselmann
  @classmethod
1380 5f06ce5e Michael Hanselmann
  def FromDict(cls, val):
1381 5f06ce5e Michael Hanselmann
    """Custom function for deserializing.
1382 5f06ce5e Michael Hanselmann

1383 5f06ce5e Michael Hanselmann
    """
1384 5f06ce5e Michael Hanselmann
    obj = super(Node, cls).FromDict(val)
1385 5f06ce5e Michael Hanselmann
1386 5f06ce5e Michael Hanselmann
    if obj.hv_state is not None:
1387 473ab806 Michael Hanselmann
      obj.hv_state = \
1388 fe502d25 Iustin Pop
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1389 5f06ce5e Michael Hanselmann
1390 5f06ce5e Michael Hanselmann
    if obj.disk_state is not None:
1391 5f06ce5e Michael Hanselmann
      obj.disk_state = \
1392 fe502d25 Iustin Pop
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1393 5f06ce5e Michael Hanselmann
             for (key, value) in obj.disk_state.items())
1394 5f06ce5e Michael Hanselmann
1395 5f06ce5e Michael Hanselmann
    return obj
1396 5f06ce5e Michael Hanselmann
1397 a8083063 Iustin Pop
1398 1ffd2673 Michael Hanselmann
class NodeGroup(TaggableObject):
1399 24a3707f Guido Trotter
  """Config object representing a node group."""
1400 24a3707f Guido Trotter
  __slots__ = [
1401 24a3707f Guido Trotter
    "name",
1402 24a3707f Guido Trotter
    "members",
1403 095e71aa Renรฉ Nussbaumer
    "ndparams",
1404 bc5d0215 Andrea Spadaccini
    "diskparams",
1405 81e3ab4f Agata Murawska
    "ipolicy",
1406 e11a1b77 Adeodato Simo
    "serial_no",
1407 a8282327 Renรฉ Nussbaumer
    "hv_state_static",
1408 a8282327 Renรฉ Nussbaumer
    "disk_state_static",
1409 90e99856 Adeodato Simo
    "alloc_policy",
1410 eaa4c57c Dimitris Aragiorgis
    "networks",
1411 24a3707f Guido Trotter
    ] + _TIMESTAMPS + _UUID
1412 24a3707f Guido Trotter
1413 a5efec93 Santi Raffa
  def ToDict(self, _with_private=False):
1414 24a3707f Guido Trotter
    """Custom function for nodegroup.
1415 24a3707f Guido Trotter

1416 c60abd62 Guido Trotter
    This discards the members object, which gets recalculated and is only kept
1417 c60abd62 Guido Trotter
    in memory.
1418 24a3707f Guido Trotter

1419 24a3707f Guido Trotter
    """
1420 a5efec93 Santi Raffa
    mydict = super(NodeGroup, self).ToDict(_with_private=_with_private)
1421 24a3707f Guido Trotter
    del mydict["members"]
1422 24a3707f Guido Trotter
    return mydict
1423 24a3707f Guido Trotter
1424 24a3707f Guido Trotter
  @classmethod
1425 24a3707f Guido Trotter
  def FromDict(cls, val):
1426 24a3707f Guido Trotter
    """Custom function for nodegroup.
1427 24a3707f Guido Trotter

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

1430 24a3707f Guido Trotter
    """
1431 24a3707f Guido Trotter
    obj = super(NodeGroup, cls).FromDict(val)
1432 24a3707f Guido Trotter
    obj.members = []
1433 24a3707f Guido Trotter
    return obj
1434 24a3707f Guido Trotter
1435 095e71aa Renรฉ Nussbaumer
  def UpgradeConfig(self):
1436 095e71aa Renรฉ Nussbaumer
    """Fill defaults for missing configuration values.
1437 095e71aa Renรฉ Nussbaumer

1438 095e71aa Renรฉ Nussbaumer
    """
1439 095e71aa Renรฉ Nussbaumer
    if self.ndparams is None:
1440 095e71aa Renรฉ Nussbaumer
      self.ndparams = {}
1441 095e71aa Renรฉ Nussbaumer
1442 e11a1b77 Adeodato Simo
    if self.serial_no is None:
1443 e11a1b77 Adeodato Simo
      self.serial_no = 1
1444 e11a1b77 Adeodato Simo
1445 90e99856 Adeodato Simo
    if self.alloc_policy is None:
1446 90e99856 Adeodato Simo
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1447 90e99856 Adeodato Simo
1448 4b97458c Iustin Pop
    # We only update mtime, and not ctime, since we would not be able
1449 4b97458c Iustin Pop
    # to provide a correct value for creation time.
1450 e11a1b77 Adeodato Simo
    if self.mtime is None:
1451 e11a1b77 Adeodato Simo
      self.mtime = time.time()
1452 e11a1b77 Adeodato Simo
1453 7228ca91 Renรฉ Nussbaumer
    if self.diskparams is None:
1454 7228ca91 Renรฉ Nussbaumer
      self.diskparams = {}
1455 81e3ab4f Agata Murawska
    if self.ipolicy is None:
1456 81e3ab4f Agata Murawska
      self.ipolicy = MakeEmptyIPolicy()
1457 bc5d0215 Andrea Spadaccini
1458 eaa4c57c Dimitris Aragiorgis
    if self.networks is None:
1459 eaa4c57c Dimitris Aragiorgis
      self.networks = {}
1460 eaa4c57c Dimitris Aragiorgis
1461 095e71aa Renรฉ Nussbaumer
  def FillND(self, node):
1462 ce523de1 Michael Hanselmann
    """Return filled out ndparams for L{objects.Node}
1463 095e71aa Renรฉ Nussbaumer

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

1468 095e71aa Renรฉ Nussbaumer
    """
1469 095e71aa Renรฉ Nussbaumer
    return self.SimpleFillND(node.ndparams)
1470 095e71aa Renรฉ Nussbaumer
1471 095e71aa Renรฉ Nussbaumer
  def SimpleFillND(self, ndparams):
1472 095e71aa Renรฉ Nussbaumer
    """Fill a given ndparams dict with defaults.
1473 095e71aa Renรฉ Nussbaumer

1474 095e71aa Renรฉ Nussbaumer
    @type ndparams: dict
1475 095e71aa Renรฉ Nussbaumer
    @param ndparams: the dict to fill
1476 095e71aa Renรฉ Nussbaumer
    @rtype: dict
1477 095e71aa Renรฉ Nussbaumer
    @return: a copy of the passed in ndparams with missing keys filled
1478 e6e88de6 Adeodato Simo
        from the node group defaults
1479 095e71aa Renรฉ Nussbaumer

1480 095e71aa Renรฉ Nussbaumer
    """
1481 095e71aa Renรฉ Nussbaumer
    return FillDict(self.ndparams, ndparams)
1482 095e71aa Renรฉ Nussbaumer
1483 24a3707f Guido Trotter
1484 ec29fe40 Iustin Pop
class Cluster(TaggableObject):
1485 a8083063 Iustin Pop
  """Config object representing the cluster."""
1486 154b9580 Balazs Lecz
  __slots__ = [
1487 a8083063 Iustin Pop
    "serial_no",
1488 a8083063 Iustin Pop
    "rsahostkeypub",
1489 a9542a4f Thomas Thrainer
    "dsahostkeypub",
1490 a8083063 Iustin Pop
    "highest_used_port",
1491 b2fddf63 Iustin Pop
    "tcpudp_port_pool",
1492 a8083063 Iustin Pop
    "mac_prefix",
1493 a8083063 Iustin Pop
    "volume_group_name",
1494 999b183c Iustin Pop
    "reserved_lvs",
1495 9e33896b Luca Bigliardi
    "drbd_usermode_helper",
1496 a8083063 Iustin Pop
    "default_bridge",
1497 02691904 Alexander Schreiber
    "default_hypervisor",
1498 f6bd6e98 Michael Hanselmann
    "master_node",
1499 f6bd6e98 Michael Hanselmann
    "master_ip",
1500 f6bd6e98 Michael Hanselmann
    "master_netdev",
1501 5a8648eb Andrea Spadaccini
    "master_netmask",
1502 33be7576 Andrea Spadaccini
    "use_external_mip_script",
1503 f6bd6e98 Michael Hanselmann
    "cluster_name",
1504 f6bd6e98 Michael Hanselmann
    "file_storage_dir",
1505 4b97f902 Apollon Oikonomopoulos
    "shared_file_storage_dir",
1506 d3e6fd0e Santi Raffa
    "gluster_storage_dir",
1507 e69d05fd Iustin Pop
    "enabled_hypervisors",
1508 5bf7b5cf Iustin Pop
    "hvparams",
1509 918eb80b Agata Murawska
    "ipolicy",
1510 17463d22 Renรฉ Nussbaumer
    "os_hvp",
1511 5bf7b5cf Iustin Pop
    "beparams",
1512 1bdcbbab Iustin Pop
    "osparams",
1513 a5efec93 Santi Raffa
    "osparams_private_cluster",
1514 c8fcde47 Guido Trotter
    "nicparams",
1515 095e71aa Renรฉ Nussbaumer
    "ndparams",
1516 bc5d0215 Andrea Spadaccini
    "diskparams",
1517 4b7735f9 Iustin Pop
    "candidate_pool_size",
1518 b86a6bcd Guido Trotter
    "modify_etc_hosts",
1519 b989b9d9 Ken Wehr
    "modify_ssh_setup",
1520 3953242f Iustin Pop
    "maintain_node_health",
1521 4437d889 Balazs Lecz
    "uid_pool",
1522 bf4af505 Apollon Oikonomopoulos
    "default_iallocator",
1523 0359e5d0 Spyros Trigazis
    "default_iallocator_params",
1524 87b2cd45 Iustin Pop
    "hidden_os",
1525 87b2cd45 Iustin Pop
    "blacklisted_os",
1526 2f20d07b Manuel Franceschini
    "primary_ip_family",
1527 3d914585 Renรฉ Nussbaumer
    "prealloc_wipe_disks",
1528 2da9f556 Renรฉ Nussbaumer
    "hv_state_static",
1529 2da9f556 Renรฉ Nussbaumer
    "disk_state_static",
1530 1b02d7ef Helga Velroyen
    "enabled_disk_templates",
1531 3bcf2140 Helga Velroyen
    "candidate_certs",
1532 cf048aea Klaus Aehlig
    "max_running_jobs",
1533 8a5d326f Jose A. Lopes
    "instance_communication_network",
1534 e1dcc53a Iustin Pop
    ] + _TIMESTAMPS + _UUID
1535 a8083063 Iustin Pop
1536 b86a6bcd Guido Trotter
  def UpgradeConfig(self):
1537 b86a6bcd Guido Trotter
    """Fill defaults for missing configuration values.
1538 b86a6bcd Guido Trotter

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

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

1677 0fbedb7a Michael Hanselmann
    """
1678 0fbedb7a Michael Hanselmann
    return self.enabled_hypervisors[0]
1679 0fbedb7a Michael Hanselmann
1680 a5efec93 Santi Raffa
  def ToDict(self, _with_private=False):
1681 319856a9 Michael Hanselmann
    """Custom function for cluster.
1682 319856a9 Michael Hanselmann

1683 319856a9 Michael Hanselmann
    """
1684 a5efec93 Santi Raffa
    mydict = super(Cluster, self).ToDict(_with_private=_with_private)
1685 a5efec93 Santi Raffa
1686 a5efec93 Santi Raffa
    # Explicitly save private parameters.
1687 a5efec93 Santi Raffa
    if _with_private:
1688 a5efec93 Santi Raffa
      for os in mydict["osparams_private_cluster"]:
1689 a5efec93 Santi Raffa
        mydict["osparams_private_cluster"][os] = \
1690 a5efec93 Santi Raffa
          self.osparams_private_cluster[os].Unprivate()
1691 4d36fbf4 Michael Hanselmann
1692 4d36fbf4 Michael Hanselmann
    if self.tcpudp_port_pool is None:
1693 4d36fbf4 Michael Hanselmann
      tcpudp_port_pool = []
1694 4d36fbf4 Michael Hanselmann
    else:
1695 4d36fbf4 Michael Hanselmann
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1696 4d36fbf4 Michael Hanselmann
1697 4d36fbf4 Michael Hanselmann
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1698 4d36fbf4 Michael Hanselmann
1699 319856a9 Michael Hanselmann
    return mydict
1700 319856a9 Michael Hanselmann
1701 319856a9 Michael Hanselmann
  @classmethod
1702 319856a9 Michael Hanselmann
  def FromDict(cls, val):
1703 319856a9 Michael Hanselmann
    """Custom function for cluster.
1704 319856a9 Michael Hanselmann

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

1718 8a147bba Renรฉ Nussbaumer
    @param diskparams: The diskparams
1719 8a147bba Renรฉ Nussbaumer
    @return: The defaults dict
1720 8a147bba Renรฉ Nussbaumer

1721 8a147bba Renรฉ Nussbaumer
    """
1722 8a147bba Renรฉ Nussbaumer
    return FillDiskParams(self.diskparams, diskparams)
1723 8a147bba Renรฉ Nussbaumer
1724 d63479b5 Iustin Pop
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1725 d63479b5 Iustin Pop
    """Get the default hypervisor parameters for the cluster.
1726 d63479b5 Iustin Pop

1727 d63479b5 Iustin Pop
    @param hypervisor: the hypervisor name
1728 d63479b5 Iustin Pop
    @param os_name: if specified, we'll also update the defaults for this OS
1729 d63479b5 Iustin Pop
    @param skip_keys: if passed, list of keys not to use
1730 d63479b5 Iustin Pop
    @return: the defaults dict
1731 d63479b5 Iustin Pop

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

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

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

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

1782 5bf7b5cf Iustin Pop
    """
1783 73e0328b Iustin Pop
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1784 73e0328b Iustin Pop
                             instance.hvparams, skip_globals)
1785 17463d22 Renรฉ Nussbaumer
1786 73e0328b Iustin Pop
  def SimpleFillBE(self, beparams):
1787 73e0328b Iustin Pop
    """Fill a given beparams dict with cluster defaults.
1788 73e0328b Iustin Pop

1789 06596a60 Guido Trotter
    @type beparams: dict
1790 06596a60 Guido Trotter
    @param beparams: the dict to fill
1791 73e0328b Iustin Pop
    @rtype: dict
1792 73e0328b Iustin Pop
    @return: a copy of the passed in beparams with missing keys filled
1793 73e0328b Iustin Pop
        from the cluster defaults
1794 73e0328b Iustin Pop

1795 73e0328b Iustin Pop
    """
1796 73e0328b Iustin Pop
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1797 5bf7b5cf Iustin Pop
1798 5bf7b5cf Iustin Pop
  def FillBE(self, instance):
1799 73e0328b Iustin Pop
    """Fill an instance's beparams dict with cluster defaults.
1800 5bf7b5cf Iustin Pop

1801 a2a24f4c Guido Trotter
    @type instance: L{objects.Instance}
1802 5bf7b5cf Iustin Pop
    @param instance: the instance parameter to fill
1803 5bf7b5cf Iustin Pop
    @rtype: dict
1804 5bf7b5cf Iustin Pop
    @return: a copy of the instance's beparams with missing keys filled from
1805 5bf7b5cf Iustin Pop
        the cluster defaults
1806 5bf7b5cf Iustin Pop

1807 5bf7b5cf Iustin Pop
    """
1808 73e0328b Iustin Pop
    return self.SimpleFillBE(instance.beparams)
1809 73e0328b Iustin Pop
1810 73e0328b Iustin Pop
  def SimpleFillNIC(self, nicparams):
1811 73e0328b Iustin Pop
    """Fill a given nicparams dict with cluster defaults.
1812 73e0328b Iustin Pop

1813 06596a60 Guido Trotter
    @type nicparams: dict
1814 06596a60 Guido Trotter
    @param nicparams: the dict to fill
1815 73e0328b Iustin Pop
    @rtype: dict
1816 73e0328b Iustin Pop
    @return: a copy of the passed in nicparams with missing keys filled
1817 73e0328b Iustin Pop
        from the cluster defaults
1818 73e0328b Iustin Pop

1819 73e0328b Iustin Pop
    """
1820 73e0328b Iustin Pop
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1821 5bf7b5cf Iustin Pop
1822 a5efec93 Santi Raffa
  def SimpleFillOS(self, os_name,
1823 a5efec93 Santi Raffa
                    os_params_public,
1824 a5efec93 Santi Raffa
                    os_params_private=None,
1825 a5efec93 Santi Raffa
                    os_params_secret=None):
1826 1bdcbbab Iustin Pop
    """Fill an instance's osparams dict with cluster defaults.
1827 1bdcbbab Iustin Pop

1828 1bdcbbab Iustin Pop
    @type os_name: string
1829 1bdcbbab Iustin Pop
    @param os_name: the OS name to use
1830 a5efec93 Santi Raffa
    @type os_params_public: dict
1831 a5efec93 Santi Raffa
    @param os_params_public: the dict to fill with default values
1832 a5efec93 Santi Raffa
    @type os_params_private: dict
1833 a5efec93 Santi Raffa
    @param os_params_private: the dict with private fields to fill
1834 a5efec93 Santi Raffa
                              with default values. Not passing this field
1835 a5efec93 Santi Raffa
                              results in no private fields being added to the
1836 a5efec93 Santi Raffa
                              return value. Private fields will be wrapped in
1837 a5efec93 Santi Raffa
                              L{Private} objects.
1838 a5efec93 Santi Raffa
    @type os_params_secret: dict
1839 a5efec93 Santi Raffa
    @param os_params_secret: the dict with secret fields to fill
1840 a5efec93 Santi Raffa
                             with default values. Not passing this field
1841 a5efec93 Santi Raffa
                             results in no secret fields being added to the
1842 a5efec93 Santi Raffa
                             return value. Private fields will be wrapped in
1843 a5efec93 Santi Raffa
                             L{Private} objects.
1844 1bdcbbab Iustin Pop
    @rtype: dict
1845 1bdcbbab Iustin Pop
    @return: a copy of the instance's osparams with missing keys filled from
1846 a5efec93 Santi Raffa
        the cluster defaults. Private and secret parameters are not included
1847 a5efec93 Santi Raffa
        unless the respective optional parameters are supplied.
1848 1bdcbbab Iustin Pop

1849 1bdcbbab Iustin Pop
    """
1850 1bdcbbab Iustin Pop
    name_only = os_name.split("+", 1)[0]
1851 a5efec93 Santi Raffa
1852 a5efec93 Santi Raffa
    defaults_base_public = self.osparams.get(name_only, {})
1853 a5efec93 Santi Raffa
    defaults_public = FillDict(defaults_base_public,
1854 a5efec93 Santi Raffa
                               self.osparams.get(os_name, {}))
1855 a5efec93 Santi Raffa
    params_public = FillDict(defaults_public, os_params_public)
1856 a5efec93 Santi Raffa
1857 a5efec93 Santi Raffa
    if os_params_private is not None:
1858 a5efec93 Santi Raffa
      defaults_base_private = self.osparams_private_cluster.get(name_only, {})
1859 a5efec93 Santi Raffa
      defaults_private = FillDict(defaults_base_private,
1860 a5efec93 Santi Raffa
                                  self.osparams_private_cluster.get(os_name,
1861 a5efec93 Santi Raffa
                                                                    {}))
1862 a5efec93 Santi Raffa
      params_private = FillDict(defaults_private, os_params_private)
1863 a5efec93 Santi Raffa
    else:
1864 a5efec93 Santi Raffa
      params_private = {}
1865 a5efec93 Santi Raffa
1866 a5efec93 Santi Raffa
    if os_params_secret is not None:
1867 a5efec93 Santi Raffa
      # There can't be default secret settings, so there's nothing to be done.
1868 a5efec93 Santi Raffa
      params_secret = os_params_secret
1869 a5efec93 Santi Raffa
    else:
1870 a5efec93 Santi Raffa
      params_secret = {}
1871 a5efec93 Santi Raffa
1872 a5efec93 Santi Raffa
    # Enforce that the set of keys be distinct:
1873 a5efec93 Santi Raffa
    duplicate_keys = utils.GetRepeatedKeys(params_public,
1874 a5efec93 Santi Raffa
                                           params_private,
1875 a5efec93 Santi Raffa
                                           params_secret)
1876 a5efec93 Santi Raffa
    if not duplicate_keys:
1877 a5efec93 Santi Raffa
1878 a5efec93 Santi Raffa
      # Actually update them:
1879 a5efec93 Santi Raffa
      params_public.update(params_private)
1880 a5efec93 Santi Raffa
      params_public.update(params_secret)
1881 a5efec93 Santi Raffa
1882 a5efec93 Santi Raffa
      return params_public
1883 a5efec93 Santi Raffa
1884 a5efec93 Santi Raffa
    else:
1885 a5efec93 Santi Raffa
1886 a5efec93 Santi Raffa
      def formatter(keys):
1887 a5efec93 Santi Raffa
        return utils.CommaJoin(sorted(map(repr, keys))) if keys else "(none)"
1888 a5efec93 Santi Raffa
1889 a5efec93 Santi Raffa
      #Lose the values.
1890 a5efec93 Santi Raffa
      params_public = set(params_public)
1891 a5efec93 Santi Raffa
      params_private = set(params_private)
1892 a5efec93 Santi Raffa
      params_secret = set(params_secret)
1893 a5efec93 Santi Raffa
1894 a5efec93 Santi Raffa
      msg = """Cannot assign multiple values to OS parameters.
1895 a5efec93 Santi Raffa

1896 a5efec93 Santi Raffa
      Conflicting OS parameters that would have been set by this operation:
1897 a5efec93 Santi Raffa
      - at public visibility:  {public}
1898 a5efec93 Santi Raffa
      - at private visibility: {private}
1899 a5efec93 Santi Raffa
      - at secret visibility:  {secret}
1900 a5efec93 Santi Raffa
      """.format(dupes=formatter(duplicate_keys),
1901 a5efec93 Santi Raffa
                 public=formatter(params_public & duplicate_keys),
1902 a5efec93 Santi Raffa
                 private=formatter(params_private & duplicate_keys),
1903 a5efec93 Santi Raffa
                 secret=formatter(params_secret & duplicate_keys))
1904 a5efec93 Santi Raffa
      raise errors.OpPrereqError(msg)
1905 1bdcbbab Iustin Pop
1906 2da9f556 Renรฉ Nussbaumer
  @staticmethod
1907 2da9f556 Renรฉ Nussbaumer
  def SimpleFillHvState(hv_state):
1908 2da9f556 Renรฉ Nussbaumer
    """Fill an hv_state sub dict with cluster defaults.
1909 2da9f556 Renรฉ Nussbaumer

1910 2da9f556 Renรฉ Nussbaumer
    """
1911 2da9f556 Renรฉ Nussbaumer
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1912 2da9f556 Renรฉ Nussbaumer
1913 2da9f556 Renรฉ Nussbaumer
  @staticmethod
1914 2da9f556 Renรฉ Nussbaumer
  def SimpleFillDiskState(disk_state):
1915 2da9f556 Renรฉ Nussbaumer
    """Fill an disk_state sub dict with cluster defaults.
1916 2da9f556 Renรฉ Nussbaumer

1917 2da9f556 Renรฉ Nussbaumer
    """
1918 2da9f556 Renรฉ Nussbaumer
    return FillDict(constants.DS_DEFAULTS, disk_state)
1919 2da9f556 Renรฉ Nussbaumer
1920 095e71aa Renรฉ Nussbaumer
  def FillND(self, node, nodegroup):
1921 ce523de1 Michael Hanselmann
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1922 095e71aa Renรฉ Nussbaumer

1923 095e71aa Renรฉ Nussbaumer
    @type node: L{objects.Node}
1924 095e71aa Renรฉ Nussbaumer
    @param node: A Node object to fill
1925 095e71aa Renรฉ Nussbaumer
    @type nodegroup: L{objects.NodeGroup}
1926 095e71aa Renรฉ Nussbaumer
    @param nodegroup: A Node object to fill
1927 095e71aa Renรฉ Nussbaumer
    @return a copy of the node's ndparams with defaults filled
1928 095e71aa Renรฉ Nussbaumer

1929 095e71aa Renรฉ Nussbaumer
    """
1930 095e71aa Renรฉ Nussbaumer
    return self.SimpleFillND(nodegroup.FillND(node))
1931 095e71aa Renรฉ Nussbaumer
1932 6b2a2942 Petr Pudlak
  def FillNDGroup(self, nodegroup):
1933 6b2a2942 Petr Pudlak
    """Return filled out ndparams for just L{objects.NodeGroup}
1934 6b2a2942 Petr Pudlak

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

1939 6b2a2942 Petr Pudlak
    """
1940 6b2a2942 Petr Pudlak
    return self.SimpleFillND(nodegroup.SimpleFillND({}))
1941 6b2a2942 Petr Pudlak
1942 095e71aa Renรฉ Nussbaumer
  def SimpleFillND(self, ndparams):
1943 095e71aa Renรฉ Nussbaumer
    """Fill a given ndparams dict with defaults.
1944 095e71aa Renรฉ Nussbaumer

1945 095e71aa Renรฉ Nussbaumer
    @type ndparams: dict
1946 095e71aa Renรฉ Nussbaumer
    @param ndparams: the dict to fill
1947 095e71aa Renรฉ Nussbaumer
    @rtype: dict
1948 095e71aa Renรฉ Nussbaumer
    @return: a copy of the passed in ndparams with missing keys filled
1949 095e71aa Renรฉ Nussbaumer
        from the cluster defaults
1950 095e71aa Renรฉ Nussbaumer

1951 095e71aa Renรฉ Nussbaumer
    """
1952 095e71aa Renรฉ Nussbaumer
    return FillDict(self.ndparams, ndparams)
1953 095e71aa Renรฉ Nussbaumer
1954 918eb80b Agata Murawska
  def SimpleFillIPolicy(self, ipolicy):
1955 918eb80b Agata Murawska
    """ Fill instance policy dict with defaults.
1956 918eb80b Agata Murawska

1957 918eb80b Agata Murawska
    @type ipolicy: dict
1958 918eb80b Agata Murawska
    @param ipolicy: the dict to fill
1959 918eb80b Agata Murawska
    @rtype: dict
1960 918eb80b Agata Murawska
    @return: a copy of passed ipolicy with missing keys filled from
1961 918eb80b Agata Murawska
      the cluster defaults
1962 918eb80b Agata Murawska

1963 918eb80b Agata Murawska
    """
1964 2cc673a3 Iustin Pop
    return FillIPolicy(self.ipolicy, ipolicy)
1965 918eb80b Agata Murawska
1966 ebe93784 Helga Velroyen
  def IsDiskTemplateEnabled(self, disk_template):
1967 ebe93784 Helga Velroyen
    """Checks if a particular disk template is enabled.
1968 ebe93784 Helga Velroyen

1969 ebe93784 Helga Velroyen
    """
1970 ebe93784 Helga Velroyen
    return utils.storage.IsDiskTemplateEnabled(
1971 ebe93784 Helga Velroyen
        disk_template, self.enabled_disk_templates)
1972 ebe93784 Helga Velroyen
1973 ebe93784 Helga Velroyen
  def IsFileStorageEnabled(self):
1974 ebe93784 Helga Velroyen
    """Checks if file storage is enabled.
1975 ebe93784 Helga Velroyen

1976 ebe93784 Helga Velroyen
    """
1977 ebe93784 Helga Velroyen
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
1978 ebe93784 Helga Velroyen
1979 ebe93784 Helga Velroyen
  def IsSharedFileStorageEnabled(self):
1980 ebe93784 Helga Velroyen
    """Checks if shared file storage is enabled.
1981 ebe93784 Helga Velroyen

1982 ebe93784 Helga Velroyen
    """
1983 ebe93784 Helga Velroyen
    return utils.storage.IsSharedFileStorageEnabled(
1984 ebe93784 Helga Velroyen
        self.enabled_disk_templates)
1985 ebe93784 Helga Velroyen
1986 5c947f38 Iustin Pop
1987 96acbc09 Michael Hanselmann
class BlockDevStatus(ConfigObject):
1988 96acbc09 Michael Hanselmann
  """Config object representing the status of a block device."""
1989 96acbc09 Michael Hanselmann
  __slots__ = [
1990 96acbc09 Michael Hanselmann
    "dev_path",
1991 96acbc09 Michael Hanselmann
    "major",
1992 96acbc09 Michael Hanselmann
    "minor",
1993 96acbc09 Michael Hanselmann
    "sync_percent",
1994 96acbc09 Michael Hanselmann
    "estimated_time",
1995 96acbc09 Michael Hanselmann
    "is_degraded",
1996 f208978a Michael Hanselmann
    "ldisk_status",
1997 96acbc09 Michael Hanselmann
    ]
1998 96acbc09 Michael Hanselmann
1999 96acbc09 Michael Hanselmann
2000 2d76b580 Michael Hanselmann
class ImportExportStatus(ConfigObject):
2001 2d76b580 Michael Hanselmann
  """Config object representing the status of an import or export."""
2002 2d76b580 Michael Hanselmann
  __slots__ = [
2003 2d76b580 Michael Hanselmann
    "recent_output",
2004 2d76b580 Michael Hanselmann
    "listen_port",
2005 2d76b580 Michael Hanselmann
    "connected",
2006 c08d76f5 Michael Hanselmann
    "progress_mbytes",
2007 c08d76f5 Michael Hanselmann
    "progress_throughput",
2008 c08d76f5 Michael Hanselmann
    "progress_eta",
2009 c08d76f5 Michael Hanselmann
    "progress_percent",
2010 2d76b580 Michael Hanselmann
    "exit_status",
2011 2d76b580 Michael Hanselmann
    "error_message",
2012 2d76b580 Michael Hanselmann
    ] + _TIMESTAMPS
2013 2d76b580 Michael Hanselmann
2014 2d76b580 Michael Hanselmann
2015 eb630f50 Michael Hanselmann
class ImportExportOptions(ConfigObject):
2016 eb630f50 Michael Hanselmann
  """Options for import/export daemon
2017 eb630f50 Michael Hanselmann

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

2025 eb630f50 Michael Hanselmann
  """
2026 eb630f50 Michael Hanselmann
  __slots__ = [
2027 eb630f50 Michael Hanselmann
    "key_name",
2028 eb630f50 Michael Hanselmann
    "ca_pem",
2029 a5310c2a Michael Hanselmann
    "compress",
2030 af1d39b1 Michael Hanselmann
    "magic",
2031 855d2fc7 Michael Hanselmann
    "ipv6",
2032 4478301b Michael Hanselmann
    "connect_timeout",
2033 eb630f50 Michael Hanselmann
    ]
2034 eb630f50 Michael Hanselmann
2035 eb630f50 Michael Hanselmann
2036 18d750b9 Guido Trotter
class ConfdRequest(ConfigObject):
2037 18d750b9 Guido Trotter
  """Object holding a confd request.
2038 18d750b9 Guido Trotter

2039 18d750b9 Guido Trotter
  @ivar protocol: confd protocol version
2040 18d750b9 Guido Trotter
  @ivar type: confd query type
2041 18d750b9 Guido Trotter
  @ivar query: query request
2042 18d750b9 Guido Trotter
  @ivar rsalt: requested reply salt
2043 18d750b9 Guido Trotter

2044 18d750b9 Guido Trotter
  """
2045 18d750b9 Guido Trotter
  __slots__ = [
2046 18d750b9 Guido Trotter
    "protocol",
2047 18d750b9 Guido Trotter
    "type",
2048 18d750b9 Guido Trotter
    "query",
2049 18d750b9 Guido Trotter
    "rsalt",
2050 18d750b9 Guido Trotter
    ]
2051 18d750b9 Guido Trotter
2052 18d750b9 Guido Trotter
2053 18d750b9 Guido Trotter
class ConfdReply(ConfigObject):
2054 18d750b9 Guido Trotter
  """Object holding a confd reply.
2055 18d750b9 Guido Trotter

2056 18d750b9 Guido Trotter
  @ivar protocol: confd protocol version
2057 18d750b9 Guido Trotter
  @ivar status: reply status code (ok, error)
2058 18d750b9 Guido Trotter
  @ivar answer: confd query reply
2059 18d750b9 Guido Trotter
  @ivar serial: configuration serial number
2060 18d750b9 Guido Trotter

2061 18d750b9 Guido Trotter
  """
2062 18d750b9 Guido Trotter
  __slots__ = [
2063 18d750b9 Guido Trotter
    "protocol",
2064 18d750b9 Guido Trotter
    "status",
2065 18d750b9 Guido Trotter
    "answer",
2066 18d750b9 Guido Trotter
    "serial",
2067 18d750b9 Guido Trotter
    ]
2068 18d750b9 Guido Trotter
2069 18d750b9 Guido Trotter
2070 707f23b5 Michael Hanselmann
class QueryFieldDefinition(ConfigObject):
2071 707f23b5 Michael Hanselmann
  """Object holding a query field definition.
2072 707f23b5 Michael Hanselmann

2073 24d6d3e2 Michael Hanselmann
  @ivar name: Field name
2074 707f23b5 Michael Hanselmann
  @ivar title: Human-readable title
2075 707f23b5 Michael Hanselmann
  @ivar kind: Field type
2076 1ae17369 Michael Hanselmann
  @ivar doc: Human-readable description
2077 707f23b5 Michael Hanselmann

2078 707f23b5 Michael Hanselmann
  """
2079 707f23b5 Michael Hanselmann
  __slots__ = [
2080 707f23b5 Michael Hanselmann
    "name",
2081 707f23b5 Michael Hanselmann
    "title",
2082 707f23b5 Michael Hanselmann
    "kind",
2083 1ae17369 Michael Hanselmann
    "doc",
2084 707f23b5 Michael Hanselmann
    ]
2085 707f23b5 Michael Hanselmann
2086 707f23b5 Michael Hanselmann
2087 0538c375 Michael Hanselmann
class _QueryResponseBase(ConfigObject):
2088 0538c375 Michael Hanselmann
  __slots__ = [
2089 0538c375 Michael Hanselmann
    "fields",
2090 0538c375 Michael Hanselmann
    ]
2091 0538c375 Michael Hanselmann
2092 a5efec93 Santi Raffa
  def ToDict(self, _with_private=False):
2093 0538c375 Michael Hanselmann
    """Custom function for serializing.
2094 0538c375 Michael Hanselmann

2095 0538c375 Michael Hanselmann
    """
2096 0538c375 Michael Hanselmann
    mydict = super(_QueryResponseBase, self).ToDict()
2097 fe502d25 Iustin Pop
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2098 0538c375 Michael Hanselmann
    return mydict
2099 0538c375 Michael Hanselmann
2100 0538c375 Michael Hanselmann
  @classmethod
2101 0538c375 Michael Hanselmann
  def FromDict(cls, val):
2102 0538c375 Michael Hanselmann
    """Custom function for de-serializing.
2103 0538c375 Michael Hanselmann

2104 0538c375 Michael Hanselmann
    """
2105 0538c375 Michael Hanselmann
    obj = super(_QueryResponseBase, cls).FromDict(val)
2106 473ab806 Michael Hanselmann
    obj.fields = \
2107 fe502d25 Iustin Pop
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2108 0538c375 Michael Hanselmann
    return obj
2109 0538c375 Michael Hanselmann
2110 0538c375 Michael Hanselmann
2111 0538c375 Michael Hanselmann
class QueryResponse(_QueryResponseBase):
2112 24d6d3e2 Michael Hanselmann
  """Object holding the response to a query.
2113 24d6d3e2 Michael Hanselmann

2114 24d6d3e2 Michael Hanselmann
  @ivar fields: List of L{QueryFieldDefinition} objects
2115 24d6d3e2 Michael Hanselmann
  @ivar data: Requested data
2116 24d6d3e2 Michael Hanselmann

2117 24d6d3e2 Michael Hanselmann
  """
2118 24d6d3e2 Michael Hanselmann
  __slots__ = [
2119 24d6d3e2 Michael Hanselmann
    "data",
2120 24d6d3e2 Michael Hanselmann
    ]
2121 24d6d3e2 Michael Hanselmann
2122 24d6d3e2 Michael Hanselmann
2123 24d6d3e2 Michael Hanselmann
class QueryFieldsRequest(ConfigObject):
2124 24d6d3e2 Michael Hanselmann
  """Object holding a request for querying available fields.
2125 24d6d3e2 Michael Hanselmann

2126 24d6d3e2 Michael Hanselmann
  """
2127 24d6d3e2 Michael Hanselmann
  __slots__ = [
2128 24d6d3e2 Michael Hanselmann
    "what",
2129 24d6d3e2 Michael Hanselmann
    "fields",
2130 24d6d3e2 Michael Hanselmann
    ]
2131 24d6d3e2 Michael Hanselmann
2132 24d6d3e2 Michael Hanselmann
2133 0538c375 Michael Hanselmann
class QueryFieldsResponse(_QueryResponseBase):
2134 24d6d3e2 Michael Hanselmann
  """Object holding the response to a query for fields.
2135 24d6d3e2 Michael Hanselmann

2136 24d6d3e2 Michael Hanselmann
  @ivar fields: List of L{QueryFieldDefinition} objects
2137 24d6d3e2 Michael Hanselmann

2138 24d6d3e2 Michael Hanselmann
  """
2139 5ae4945a Iustin Pop
  __slots__ = []
2140 24d6d3e2 Michael Hanselmann
2141 24d6d3e2 Michael Hanselmann
2142 6a1434d7 Andrea Spadaccini
class MigrationStatus(ConfigObject):
2143 6a1434d7 Andrea Spadaccini
  """Object holding the status of a migration.
2144 6a1434d7 Andrea Spadaccini

2145 6a1434d7 Andrea Spadaccini
  """
2146 6a1434d7 Andrea Spadaccini
  __slots__ = [
2147 6a1434d7 Andrea Spadaccini
    "status",
2148 6a1434d7 Andrea Spadaccini
    "transferred_ram",
2149 6a1434d7 Andrea Spadaccini
    "total_ram",
2150 6a1434d7 Andrea Spadaccini
    ]
2151 6a1434d7 Andrea Spadaccini
2152 6a1434d7 Andrea Spadaccini
2153 25ce3ec4 Michael Hanselmann
class InstanceConsole(ConfigObject):
2154 25ce3ec4 Michael Hanselmann
  """Object describing how to access the console of an instance.
2155 25ce3ec4 Michael Hanselmann

2156 25ce3ec4 Michael Hanselmann
  """
2157 25ce3ec4 Michael Hanselmann
  __slots__ = [
2158 25ce3ec4 Michael Hanselmann
    "instance",
2159 25ce3ec4 Michael Hanselmann
    "kind",
2160 25ce3ec4 Michael Hanselmann
    "message",
2161 25ce3ec4 Michael Hanselmann
    "host",
2162 25ce3ec4 Michael Hanselmann
    "port",
2163 25ce3ec4 Michael Hanselmann
    "user",
2164 25ce3ec4 Michael Hanselmann
    "command",
2165 25ce3ec4 Michael Hanselmann
    "display",
2166 25ce3ec4 Michael Hanselmann
    ]
2167 25ce3ec4 Michael Hanselmann
2168 25ce3ec4 Michael Hanselmann
  def Validate(self):
2169 25ce3ec4 Michael Hanselmann
    """Validates contents of this object.
2170 25ce3ec4 Michael Hanselmann

2171 25ce3ec4 Michael Hanselmann
    """
2172 25ce3ec4 Michael Hanselmann
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2173 25ce3ec4 Michael Hanselmann
    assert self.instance, "Missing instance name"
2174 4d2cdb5a Andrea Spadaccini
    assert self.message or self.kind in [constants.CONS_SSH,
2175 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2176 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_VNC]
2177 25ce3ec4 Michael Hanselmann
    assert self.host or self.kind == constants.CONS_MESSAGE
2178 25ce3ec4 Michael Hanselmann
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2179 25ce3ec4 Michael Hanselmann
                                      constants.CONS_SSH]
2180 25ce3ec4 Michael Hanselmann
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2181 4d2cdb5a Andrea Spadaccini
                                      constants.CONS_SPICE,
2182 25ce3ec4 Michael Hanselmann
                                      constants.CONS_VNC]
2183 25ce3ec4 Michael Hanselmann
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2184 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2185 25ce3ec4 Michael Hanselmann
                                         constants.CONS_VNC]
2186 25ce3ec4 Michael Hanselmann
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2187 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2188 25ce3ec4 Michael Hanselmann
                                         constants.CONS_SSH]
2189 25ce3ec4 Michael Hanselmann
    return True
2190 25ce3ec4 Michael Hanselmann
2191 25ce3ec4 Michael Hanselmann
2192 8140e24f Dimitris Aragiorgis
class Network(TaggableObject):
2193 eaa4c57c Dimitris Aragiorgis
  """Object representing a network definition for ganeti.
2194 eaa4c57c Dimitris Aragiorgis

2195 eaa4c57c Dimitris Aragiorgis
  """
2196 eaa4c57c Dimitris Aragiorgis
  __slots__ = [
2197 eaa4c57c Dimitris Aragiorgis
    "name",
2198 eaa4c57c Dimitris Aragiorgis
    "serial_no",
2199 eaa4c57c Dimitris Aragiorgis
    "mac_prefix",
2200 eaa4c57c Dimitris Aragiorgis
    "network",
2201 eaa4c57c Dimitris Aragiorgis
    "network6",
2202 eaa4c57c Dimitris Aragiorgis
    "gateway",
2203 eaa4c57c Dimitris Aragiorgis
    "gateway6",
2204 eaa4c57c Dimitris Aragiorgis
    "reservations",
2205 eaa4c57c Dimitris Aragiorgis
    "ext_reservations",
2206 eaa4c57c Dimitris Aragiorgis
    ] + _TIMESTAMPS + _UUID
2207 eaa4c57c Dimitris Aragiorgis
2208 7e8f03e3 Dimitris Aragiorgis
  def HooksDict(self, prefix=""):
2209 d89168ff Guido Trotter
    """Export a dictionary used by hooks with a network's information.
2210 d89168ff Guido Trotter

2211 d89168ff Guido Trotter
    @type prefix: String
2212 d89168ff Guido Trotter
    @param prefix: Prefix to prepend to the dict entries
2213 d89168ff Guido Trotter

2214 d89168ff Guido Trotter
    """
2215 d89168ff Guido Trotter
    result = {
2216 7e8f03e3 Dimitris Aragiorgis
      "%sNETWORK_NAME" % prefix: self.name,
2217 d89168ff Guido Trotter
      "%sNETWORK_UUID" % prefix: self.uuid,
2218 5a76adf7 Dimitris Aragiorgis
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2219 d89168ff Guido Trotter
    }
2220 d89168ff Guido Trotter
    if self.network:
2221 d89168ff Guido Trotter
      result["%sNETWORK_SUBNET" % prefix] = self.network
2222 d89168ff Guido Trotter
    if self.gateway:
2223 d89168ff Guido Trotter
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2224 d89168ff Guido Trotter
    if self.network6:
2225 d89168ff Guido Trotter
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2226 d89168ff Guido Trotter
    if self.gateway6:
2227 d89168ff Guido Trotter
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2228 d89168ff Guido Trotter
    if self.mac_prefix:
2229 d89168ff Guido Trotter
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2230 d89168ff Guido Trotter
2231 d89168ff Guido Trotter
    return result
2232 d89168ff Guido Trotter
2233 5cfa6c37 Dimitris Aragiorgis
  @classmethod
2234 5cfa6c37 Dimitris Aragiorgis
  def FromDict(cls, val):
2235 5cfa6c37 Dimitris Aragiorgis
    """Custom function for networks.
2236 5cfa6c37 Dimitris Aragiorgis

2237 48616625 Dimitris Aragiorgis
    Remove deprecated network_type and family.
2238 5cfa6c37 Dimitris Aragiorgis

2239 5cfa6c37 Dimitris Aragiorgis
    """
2240 5cfa6c37 Dimitris Aragiorgis
    if "network_type" in val:
2241 5cfa6c37 Dimitris Aragiorgis
      del val["network_type"]
2242 48616625 Dimitris Aragiorgis
    if "family" in val:
2243 48616625 Dimitris Aragiorgis
      del val["family"]
2244 5cfa6c37 Dimitris Aragiorgis
    obj = super(Network, cls).FromDict(val)
2245 5cfa6c37 Dimitris Aragiorgis
    return obj
2246 5cfa6c37 Dimitris Aragiorgis
2247 eaa4c57c Dimitris Aragiorgis
2248 a8083063 Iustin Pop
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2249 a8083063 Iustin Pop
  """Simple wrapper over ConfigParse that allows serialization.
2250 a8083063 Iustin Pop

2251 a8083063 Iustin Pop
  This class is basically ConfigParser.SafeConfigParser with two
2252 a8083063 Iustin Pop
  additional methods that allow it to serialize/unserialize to/from a
2253 a8083063 Iustin Pop
  buffer.
2254 a8083063 Iustin Pop

2255 a8083063 Iustin Pop
  """
2256 a8083063 Iustin Pop
  def Dumps(self):
2257 a8083063 Iustin Pop
    """Dump this instance and return the string representation."""
2258 a8083063 Iustin Pop
    buf = StringIO()
2259 a8083063 Iustin Pop
    self.write(buf)
2260 a8083063 Iustin Pop
    return buf.getvalue()
2261 a8083063 Iustin Pop
2262 b39bf4bb Guido Trotter
  @classmethod
2263 b39bf4bb Guido Trotter
  def Loads(cls, data):
2264 a8083063 Iustin Pop
    """Load data from a string."""
2265 a8083063 Iustin Pop
    buf = StringIO(data)
2266 b39bf4bb Guido Trotter
    cfp = cls()
2267 a8083063 Iustin Pop
    cfp.readfp(buf)
2268 a8083063 Iustin Pop
    return cfp
2269 59726e15 Bernardo Dal Seno
2270 59726e15 Bernardo Dal Seno
2271 59726e15 Bernardo Dal Seno
class LvmPvInfo(ConfigObject):
2272 59726e15 Bernardo Dal Seno
  """Information about an LVM physical volume (PV).
2273 59726e15 Bernardo Dal Seno

2274 59726e15 Bernardo Dal Seno
  @type name: string
2275 59726e15 Bernardo Dal Seno
  @ivar name: name of the PV
2276 59726e15 Bernardo Dal Seno
  @type vg_name: string
2277 59726e15 Bernardo Dal Seno
  @ivar vg_name: name of the volume group containing the PV
2278 59726e15 Bernardo Dal Seno
  @type size: float
2279 59726e15 Bernardo Dal Seno
  @ivar size: size of the PV in MiB
2280 59726e15 Bernardo Dal Seno
  @type free: float
2281 59726e15 Bernardo Dal Seno
  @ivar free: free space in the PV, in MiB
2282 59726e15 Bernardo Dal Seno
  @type attributes: string
2283 59726e15 Bernardo Dal Seno
  @ivar attributes: PV attributes
2284 b496abdb Bernardo Dal Seno
  @type lv_list: list of strings
2285 b496abdb Bernardo Dal Seno
  @ivar lv_list: names of the LVs hosted on the PV
2286 59726e15 Bernardo Dal Seno
  """
2287 59726e15 Bernardo Dal Seno
  __slots__ = [
2288 59726e15 Bernardo Dal Seno
    "name",
2289 59726e15 Bernardo Dal Seno
    "vg_name",
2290 59726e15 Bernardo Dal Seno
    "size",
2291 59726e15 Bernardo Dal Seno
    "free",
2292 59726e15 Bernardo Dal Seno
    "attributes",
2293 b496abdb Bernardo Dal Seno
    "lv_list"
2294 59726e15 Bernardo Dal Seno
    ]
2295 59726e15 Bernardo Dal Seno
2296 59726e15 Bernardo Dal Seno
  def IsEmpty(self):
2297 59726e15 Bernardo Dal Seno
    """Is this PV empty?
2298 59726e15 Bernardo Dal Seno

2299 59726e15 Bernardo Dal Seno
    """
2300 59726e15 Bernardo Dal Seno
    return self.size <= (self.free + 1)
2301 59726e15 Bernardo Dal Seno
2302 59726e15 Bernardo Dal Seno
  def IsAllocatable(self):
2303 59726e15 Bernardo Dal Seno
    """Is this PV allocatable?
2304 59726e15 Bernardo Dal Seno

2305 59726e15 Bernardo Dal Seno
    """
2306 59726e15 Bernardo Dal Seno
    return ("a" in self.attributes)