Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ f7f03738

History | View | Annotate | Download (62.7 kB)

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

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

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

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

73 29921401 Iustin Pop
  """
74 29921401 Iustin Pop
  ret_dict = copy.deepcopy(defaults_dict)
75 29921401 Iustin Pop
  ret_dict.update(custom_dict)
76 e11ddf13 Iustin Pop
  if skip_keys:
77 e11ddf13 Iustin Pop
    for k in skip_keys:
78 e11ddf13 Iustin Pop
      try:
79 e11ddf13 Iustin Pop
        del ret_dict[k]
80 e11ddf13 Iustin Pop
      except KeyError:
81 e11ddf13 Iustin Pop
        pass
82 29921401 Iustin Pop
  return ret_dict
83 a8083063 Iustin Pop
84 6e34b628 Guido Trotter
85 da5f09ef Bernardo Dal Seno
def _FillMinMaxISpecs(default_specs, custom_specs):
86 da5f09ef Bernardo Dal Seno
  assert frozenset(default_specs.keys()) == constants.ISPECS_MINMAX_KEYS
87 da5f09ef Bernardo Dal Seno
  ret_specs = {}
88 da5f09ef Bernardo Dal Seno
  for key in constants.ISPECS_MINMAX_KEYS:
89 da5f09ef Bernardo Dal Seno
    ret_specs[key] = FillDict(default_specs[key],
90 da5f09ef Bernardo Dal Seno
                              custom_specs.get(key, {}))
91 da5f09ef Bernardo Dal Seno
  return ret_specs
92 da5f09ef Bernardo Dal Seno
93 da5f09ef Bernardo Dal Seno
94 da5f09ef Bernardo Dal Seno
def FillIPolicy(default_ipolicy, custom_ipolicy):
95 2cc673a3 Iustin Pop
  """Fills an instance policy with defaults.
96 918eb80b Agata Murawska

97 918eb80b Agata Murawska
  """
98 2cc673a3 Iustin Pop
  assert frozenset(default_ipolicy.keys()) == constants.IPOLICY_ALL_KEYS
99 918eb80b Agata Murawska
  ret_dict = {}
100 da5f09ef Bernardo Dal Seno
  # Instance specs
101 da5f09ef Bernardo Dal Seno
  new_mm = _FillMinMaxISpecs(default_ipolicy[constants.ISPECS_MINMAX],
102 da5f09ef Bernardo Dal Seno
                             custom_ipolicy.get(constants.ISPECS_MINMAX, {}))
103 da5f09ef Bernardo Dal Seno
  ret_dict[constants.ISPECS_MINMAX] = new_mm
104 da5f09ef Bernardo Dal Seno
  new_std = FillDict(default_ipolicy[constants.ISPECS_STD],
105 da5f09ef Bernardo Dal Seno
                     custom_ipolicy.get(constants.ISPECS_STD, {}))
106 da5f09ef Bernardo Dal Seno
  ret_dict[constants.ISPECS_STD] = new_std
107 2cc673a3 Iustin Pop
  # list items
108 d04c9d45 Iustin Pop
  for key in [constants.IPOLICY_DTS]:
109 2cc673a3 Iustin Pop
    ret_dict[key] = list(custom_ipolicy.get(key, default_ipolicy[key]))
110 ff6c5e55 Iustin Pop
  # other items which we know we can directly copy (immutables)
111 ff6c5e55 Iustin Pop
  for key in constants.IPOLICY_PARAMETERS:
112 ff6c5e55 Iustin Pop
    ret_dict[key] = custom_ipolicy.get(key, default_ipolicy[key])
113 2cc673a3 Iustin Pop
114 918eb80b Agata Murawska
  return ret_dict
115 918eb80b Agata Murawska
116 918eb80b Agata Murawska
117 57987785 Renรฉ Nussbaumer
def FillDiskParams(default_dparams, custom_dparams, skip_keys=None):
118 57987785 Renรฉ Nussbaumer
  """Fills the disk parameter defaults.
119 57987785 Renรฉ Nussbaumer

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

122 57987785 Renรฉ Nussbaumer
  """
123 57987785 Renรฉ Nussbaumer
  assert frozenset(default_dparams.keys()) == constants.DISK_TEMPLATES
124 57987785 Renรฉ Nussbaumer
125 57987785 Renรฉ Nussbaumer
  return dict((dt, FillDict(default_dparams[dt], custom_dparams.get(dt, {}),
126 57987785 Renรฉ Nussbaumer
                             skip_keys=skip_keys))
127 57987785 Renรฉ Nussbaumer
              for dt in constants.DISK_TEMPLATES)
128 57987785 Renรฉ Nussbaumer
129 57987785 Renรฉ Nussbaumer
130 6e34b628 Guido Trotter
def UpgradeGroupedParams(target, defaults):
131 6e34b628 Guido Trotter
  """Update all groups for the target parameter.
132 6e34b628 Guido Trotter

133 6e34b628 Guido Trotter
  @type target: dict of dicts
134 6e34b628 Guido Trotter
  @param target: {group: {parameter: value}}
135 6e34b628 Guido Trotter
  @type defaults: dict
136 6e34b628 Guido Trotter
  @param defaults: default parameter values
137 6e34b628 Guido Trotter

138 6e34b628 Guido Trotter
  """
139 6e34b628 Guido Trotter
  if target is None:
140 6e34b628 Guido Trotter
    target = {constants.PP_DEFAULT: defaults}
141 6e34b628 Guido Trotter
  else:
142 6e34b628 Guido Trotter
    for group in target:
143 6e34b628 Guido Trotter
      target[group] = FillDict(defaults, target[group])
144 6e34b628 Guido Trotter
  return target
145 6e34b628 Guido Trotter
146 6e34b628 Guido Trotter
147 8c72ab2b Guido Trotter
def UpgradeBeParams(target):
148 8c72ab2b Guido Trotter
  """Update the be parameters dict to the new format.
149 8c72ab2b Guido Trotter

150 8c72ab2b Guido Trotter
  @type target: dict
151 8c72ab2b Guido Trotter
  @param target: "be" parameters dict
152 8c72ab2b Guido Trotter

153 8c72ab2b Guido Trotter
  """
154 8c72ab2b Guido Trotter
  if constants.BE_MEMORY in target:
155 8c72ab2b Guido Trotter
    memory = target[constants.BE_MEMORY]
156 8c72ab2b Guido Trotter
    target[constants.BE_MAXMEM] = memory
157 8c72ab2b Guido Trotter
    target[constants.BE_MINMEM] = memory
158 b2e233a5 Guido Trotter
    del target[constants.BE_MEMORY]
159 8c72ab2b Guido Trotter
160 8c72ab2b Guido Trotter
161 bc5d0215 Andrea Spadaccini
def UpgradeDiskParams(diskparams):
162 bc5d0215 Andrea Spadaccini
  """Upgrade the disk parameters.
163 bc5d0215 Andrea Spadaccini

164 bc5d0215 Andrea Spadaccini
  @type diskparams: dict
165 bc5d0215 Andrea Spadaccini
  @param diskparams: disk parameters to upgrade
166 bc5d0215 Andrea Spadaccini
  @rtype: dict
167 765ada2b Iustin Pop
  @return: the upgraded disk parameters dict
168 bc5d0215 Andrea Spadaccini

169 bc5d0215 Andrea Spadaccini
  """
170 99ccf8b9 Renรฉ Nussbaumer
  if not diskparams:
171 99ccf8b9 Renรฉ Nussbaumer
    result = {}
172 bc5d0215 Andrea Spadaccini
  else:
173 57987785 Renรฉ Nussbaumer
    result = FillDiskParams(constants.DISK_DT_DEFAULTS, diskparams)
174 bc5d0215 Andrea Spadaccini
175 bc5d0215 Andrea Spadaccini
  return result
176 bc5d0215 Andrea Spadaccini
177 bc5d0215 Andrea Spadaccini
178 2a27dac3 Iustin Pop
def UpgradeNDParams(ndparams):
179 2a27dac3 Iustin Pop
  """Upgrade ndparams structure.
180 2a27dac3 Iustin Pop

181 2a27dac3 Iustin Pop
  @type ndparams: dict
182 2a27dac3 Iustin Pop
  @param ndparams: disk parameters to upgrade
183 2a27dac3 Iustin Pop
  @rtype: dict
184 2a27dac3 Iustin Pop
  @return: the upgraded node parameters dict
185 2a27dac3 Iustin Pop

186 2a27dac3 Iustin Pop
  """
187 2a27dac3 Iustin Pop
  if ndparams is None:
188 2a27dac3 Iustin Pop
    ndparams = {}
189 2a27dac3 Iustin Pop
190 1df4d430 Iustin Pop
  if (constants.ND_OOB_PROGRAM in ndparams and
191 1df4d430 Iustin Pop
      ndparams[constants.ND_OOB_PROGRAM] is None):
192 1df4d430 Iustin Pop
    # will be reset by the line below
193 1df4d430 Iustin Pop
    del ndparams[constants.ND_OOB_PROGRAM]
194 2a27dac3 Iustin Pop
  return FillDict(constants.NDC_DEFAULTS, ndparams)
195 2a27dac3 Iustin Pop
196 2a27dac3 Iustin Pop
197 918eb80b Agata Murawska
def MakeEmptyIPolicy():
198 918eb80b Agata Murawska
  """Create empty IPolicy dictionary.
199 918eb80b Agata Murawska

200 918eb80b Agata Murawska
  """
201 da5f09ef Bernardo Dal Seno
  return {
202 da5f09ef Bernardo Dal Seno
    constants.ISPECS_MINMAX: {
203 da5f09ef Bernardo Dal Seno
      constants.ISPECS_MIN: {},
204 da5f09ef Bernardo Dal Seno
      constants.ISPECS_MAX: {},
205 da5f09ef Bernardo Dal Seno
      },
206 da5f09ef Bernardo Dal Seno
    constants.ISPECS_STD: {},
207 da5f09ef Bernardo Dal Seno
    }
208 918eb80b Agata Murawska
209 918eb80b Agata Murawska
210 473d87a3 Iustin Pop
class ConfigObject(outils.ValidatedSlots):
211 a8083063 Iustin Pop
  """A generic config object.
212 a8083063 Iustin Pop

213 a8083063 Iustin Pop
  It has the following properties:
214 a8083063 Iustin Pop

215 a8083063 Iustin Pop
    - provides somewhat safe recursive unpickling and pickling for its classes
216 a8083063 Iustin Pop
    - unset attributes which are defined in slots are always returned
217 a8083063 Iustin Pop
      as None instead of raising an error
218 a8083063 Iustin Pop

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

222 a8083063 Iustin Pop
  """
223 a8083063 Iustin Pop
  __slots__ = []
224 a8083063 Iustin Pop
225 a8083063 Iustin Pop
  def __getattr__(self, name):
226 32683096 Renรฉ Nussbaumer
    if name not in self.GetAllSlots():
227 3ecf6786 Iustin Pop
      raise AttributeError("Invalid object attribute %s.%s" %
228 3ecf6786 Iustin Pop
                           (type(self).__name__, name))
229 a8083063 Iustin Pop
    return None
230 a8083063 Iustin Pop
231 a8083063 Iustin Pop
  def __setstate__(self, state):
232 32683096 Renรฉ Nussbaumer
    slots = self.GetAllSlots()
233 a8083063 Iustin Pop
    for name in state:
234 adf385c7 Iustin Pop
      if name in slots:
235 a8083063 Iustin Pop
        setattr(self, name, state[name])
236 a8083063 Iustin Pop
237 32683096 Renรฉ Nussbaumer
  def Validate(self):
238 32683096 Renรฉ Nussbaumer
    """Validates the slots.
239 adf385c7 Iustin Pop

240 adf385c7 Iustin Pop
    """
241 415feb2e Renรฉ Nussbaumer
242 ff9c047c Iustin Pop
  def ToDict(self):
243 ff9c047c Iustin Pop
    """Convert to a dict holding only standard python types.
244 ff9c047c Iustin Pop

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

251 ff9c047c Iustin Pop
    """
252 4c14965f Guido Trotter
    result = {}
253 32683096 Renรฉ Nussbaumer
    for name in self.GetAllSlots():
254 4c14965f Guido Trotter
      value = getattr(self, name, None)
255 4c14965f Guido Trotter
      if value is not None:
256 4c14965f Guido Trotter
        result[name] = value
257 4c14965f Guido Trotter
    return result
258 4c14965f Guido Trotter
259 4c14965f Guido Trotter
  __getstate__ = ToDict
260 ff9c047c Iustin Pop
261 ff9c047c Iustin Pop
  @classmethod
262 ff9c047c Iustin Pop
  def FromDict(cls, val):
263 ff9c047c Iustin Pop
    """Create an object from a dictionary.
264 ff9c047c Iustin Pop

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

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

273 ff9c047c Iustin Pop
    """
274 ff9c047c Iustin Pop
    if not isinstance(val, dict):
275 ff9c047c Iustin Pop
      raise errors.ConfigurationError("Invalid object passed to FromDict:"
276 ff9c047c Iustin Pop
                                      " expected dict, got %s" % type(val))
277 319856a9 Michael Hanselmann
    val_str = dict([(str(k), v) for k, v in val.iteritems()])
278 b459a848 Andrea Spadaccini
    obj = cls(**val_str) # pylint: disable=W0142
279 ff9c047c Iustin Pop
    return obj
280 ff9c047c Iustin Pop
281 e8d563f3 Iustin Pop
  def Copy(self):
282 e8d563f3 Iustin Pop
    """Makes a deep copy of the current object and its children.
283 e8d563f3 Iustin Pop

284 e8d563f3 Iustin Pop
    """
285 e8d563f3 Iustin Pop
    dict_form = self.ToDict()
286 e8d563f3 Iustin Pop
    clone_obj = self.__class__.FromDict(dict_form)
287 e8d563f3 Iustin Pop
    return clone_obj
288 e8d563f3 Iustin Pop
289 ff9c047c Iustin Pop
  def __repr__(self):
290 ff9c047c Iustin Pop
    """Implement __repr__ for ConfigObjects."""
291 ff9c047c Iustin Pop
    return repr(self.ToDict())
292 ff9c047c Iustin Pop
293 560428be Guido Trotter
  def UpgradeConfig(self):
294 560428be Guido Trotter
    """Fill defaults for missing configuration values.
295 560428be Guido Trotter

296 90d726a8 Iustin Pop
    This method will be called at configuration load time, and its
297 90d726a8 Iustin Pop
    implementation will be object dependent.
298 560428be Guido Trotter

299 560428be Guido Trotter
    """
300 560428be Guido Trotter
    pass
301 560428be Guido Trotter
302 a8083063 Iustin Pop
303 ec29fe40 Iustin Pop
class TaggableObject(ConfigObject):
304 5c947f38 Iustin Pop
  """An generic class supporting tags.
305 5c947f38 Iustin Pop

306 5c947f38 Iustin Pop
  """
307 154b9580 Balazs Lecz
  __slots__ = ["tags"]
308 b5e5632e Iustin Pop
  VALID_TAG_RE = re.compile("^[\w.+*/:@-]+$")
309 2057f6c7 Iustin Pop
310 b5e5632e Iustin Pop
  @classmethod
311 b5e5632e Iustin Pop
  def ValidateTag(cls, tag):
312 5c947f38 Iustin Pop
    """Check if a tag is valid.
313 5c947f38 Iustin Pop

314 5c947f38 Iustin Pop
    If the tag is invalid, an errors.TagError will be raised. The
315 5c947f38 Iustin Pop
    function has no return value.
316 5c947f38 Iustin Pop

317 5c947f38 Iustin Pop
    """
318 5c947f38 Iustin Pop
    if not isinstance(tag, basestring):
319 3ecf6786 Iustin Pop
      raise errors.TagError("Invalid tag type (not a string)")
320 5c947f38 Iustin Pop
    if len(tag) > constants.MAX_TAG_LEN:
321 319856a9 Michael Hanselmann
      raise errors.TagError("Tag too long (>%d characters)" %
322 319856a9 Michael Hanselmann
                            constants.MAX_TAG_LEN)
323 5c947f38 Iustin Pop
    if not tag:
324 3ecf6786 Iustin Pop
      raise errors.TagError("Tags cannot be empty")
325 b5e5632e Iustin Pop
    if not cls.VALID_TAG_RE.match(tag):
326 3ecf6786 Iustin Pop
      raise errors.TagError("Tag contains invalid characters")
327 5c947f38 Iustin Pop
328 5c947f38 Iustin Pop
  def GetTags(self):
329 5c947f38 Iustin Pop
    """Return the tags list.
330 5c947f38 Iustin Pop

331 5c947f38 Iustin Pop
    """
332 5c947f38 Iustin Pop
    tags = getattr(self, "tags", None)
333 5c947f38 Iustin Pop
    if tags is None:
334 5c947f38 Iustin Pop
      tags = self.tags = set()
335 5c947f38 Iustin Pop
    return tags
336 5c947f38 Iustin Pop
337 5c947f38 Iustin Pop
  def AddTag(self, tag):
338 5c947f38 Iustin Pop
    """Add a new tag.
339 5c947f38 Iustin Pop

340 5c947f38 Iustin Pop
    """
341 5c947f38 Iustin Pop
    self.ValidateTag(tag)
342 5c947f38 Iustin Pop
    tags = self.GetTags()
343 5c947f38 Iustin Pop
    if len(tags) >= constants.MAX_TAGS_PER_OBJ:
344 3ecf6786 Iustin Pop
      raise errors.TagError("Too many tags")
345 5c947f38 Iustin Pop
    self.GetTags().add(tag)
346 5c947f38 Iustin Pop
347 5c947f38 Iustin Pop
  def RemoveTag(self, tag):
348 5c947f38 Iustin Pop
    """Remove a tag.
349 5c947f38 Iustin Pop

350 5c947f38 Iustin Pop
    """
351 5c947f38 Iustin Pop
    self.ValidateTag(tag)
352 5c947f38 Iustin Pop
    tags = self.GetTags()
353 5c947f38 Iustin Pop
    try:
354 5c947f38 Iustin Pop
      tags.remove(tag)
355 5c947f38 Iustin Pop
    except KeyError:
356 3ecf6786 Iustin Pop
      raise errors.TagError("Tag not found")
357 5c947f38 Iustin Pop
358 ff9c047c Iustin Pop
  def ToDict(self):
359 ff9c047c Iustin Pop
    """Taggable-object-specific conversion to standard python types.
360 ff9c047c Iustin Pop

361 ff9c047c Iustin Pop
    This replaces the tags set with a list.
362 ff9c047c Iustin Pop

363 ff9c047c Iustin Pop
    """
364 ff9c047c Iustin Pop
    bo = super(TaggableObject, self).ToDict()
365 ff9c047c Iustin Pop
366 ff9c047c Iustin Pop
    tags = bo.get("tags", None)
367 ff9c047c Iustin Pop
    if isinstance(tags, set):
368 ff9c047c Iustin Pop
      bo["tags"] = list(tags)
369 ff9c047c Iustin Pop
    return bo
370 ff9c047c Iustin Pop
371 ff9c047c Iustin Pop
  @classmethod
372 ff9c047c Iustin Pop
  def FromDict(cls, val):
373 ff9c047c Iustin Pop
    """Custom function for instances.
374 ff9c047c Iustin Pop

375 ff9c047c Iustin Pop
    """
376 ff9c047c Iustin Pop
    obj = super(TaggableObject, cls).FromDict(val)
377 ff9c047c Iustin Pop
    if hasattr(obj, "tags") and isinstance(obj.tags, list):
378 ff9c047c Iustin Pop
      obj.tags = set(obj.tags)
379 ff9c047c Iustin Pop
    return obj
380 ff9c047c Iustin Pop
381 5c947f38 Iustin Pop
382 061af273 Andrea Spadaccini
class MasterNetworkParameters(ConfigObject):
383 061af273 Andrea Spadaccini
  """Network configuration parameters for the master
384 061af273 Andrea Spadaccini

385 061af273 Andrea Spadaccini
  @ivar name: master name
386 061af273 Andrea Spadaccini
  @ivar ip: master IP
387 061af273 Andrea Spadaccini
  @ivar netmask: master netmask
388 061af273 Andrea Spadaccini
  @ivar netdev: master network device
389 061af273 Andrea Spadaccini
  @ivar ip_family: master IP family
390 061af273 Andrea Spadaccini

391 061af273 Andrea Spadaccini
  """
392 061af273 Andrea Spadaccini
  __slots__ = [
393 061af273 Andrea Spadaccini
    "name",
394 061af273 Andrea Spadaccini
    "ip",
395 061af273 Andrea Spadaccini
    "netmask",
396 061af273 Andrea Spadaccini
    "netdev",
397 3c286190 Dimitris Aragiorgis
    "ip_family",
398 061af273 Andrea Spadaccini
    ]
399 061af273 Andrea Spadaccini
400 061af273 Andrea Spadaccini
401 a8083063 Iustin Pop
class ConfigData(ConfigObject):
402 a8083063 Iustin Pop
  """Top-level config object."""
403 3df43542 Guido Trotter
  __slots__ = [
404 3df43542 Guido Trotter
    "version",
405 3df43542 Guido Trotter
    "cluster",
406 3df43542 Guido Trotter
    "nodes",
407 3df43542 Guido Trotter
    "nodegroups",
408 3df43542 Guido Trotter
    "instances",
409 eaa4c57c Dimitris Aragiorgis
    "networks",
410 3df43542 Guido Trotter
    "serial_no",
411 3df43542 Guido Trotter
    ] + _TIMESTAMPS
412 a8083063 Iustin Pop
413 ff9c047c Iustin Pop
  def ToDict(self):
414 ff9c047c Iustin Pop
    """Custom function for top-level config data.
415 ff9c047c Iustin Pop

416 ff9c047c Iustin Pop
    This just replaces the list of instances, nodes and the cluster
417 ff9c047c Iustin Pop
    with standard python types.
418 ff9c047c Iustin Pop

419 ff9c047c Iustin Pop
    """
420 ff9c047c Iustin Pop
    mydict = super(ConfigData, self).ToDict()
421 ff9c047c Iustin Pop
    mydict["cluster"] = mydict["cluster"].ToDict()
422 eaa4c57c Dimitris Aragiorgis
    for key in "nodes", "instances", "nodegroups", "networks":
423 fe502d25 Iustin Pop
      mydict[key] = outils.ContainerToDicts(mydict[key])
424 ff9c047c Iustin Pop
425 ff9c047c Iustin Pop
    return mydict
426 ff9c047c Iustin Pop
427 ff9c047c Iustin Pop
  @classmethod
428 ff9c047c Iustin Pop
  def FromDict(cls, val):
429 ff9c047c Iustin Pop
    """Custom function for top-level config data
430 ff9c047c Iustin Pop

431 ff9c047c Iustin Pop
    """
432 ff9c047c Iustin Pop
    obj = super(ConfigData, cls).FromDict(val)
433 ff9c047c Iustin Pop
    obj.cluster = Cluster.FromDict(obj.cluster)
434 fe502d25 Iustin Pop
    obj.nodes = outils.ContainerFromDicts(obj.nodes, dict, Node)
435 473ab806 Michael Hanselmann
    obj.instances = \
436 fe502d25 Iustin Pop
      outils.ContainerFromDicts(obj.instances, dict, Instance)
437 473ab806 Michael Hanselmann
    obj.nodegroups = \
438 fe502d25 Iustin Pop
      outils.ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
439 fe502d25 Iustin Pop
    obj.networks = outils.ContainerFromDicts(obj.networks, dict, Network)
440 ff9c047c Iustin Pop
    return obj
441 ff9c047c Iustin Pop
442 51cb1581 Luca Bigliardi
  def HasAnyDiskOfType(self, dev_type):
443 51cb1581 Luca Bigliardi
    """Check if in there is at disk of the given type in the configuration.
444 51cb1581 Luca Bigliardi

445 51cb1581 Luca Bigliardi
    @type dev_type: L{constants.LDS_BLOCK}
446 51cb1581 Luca Bigliardi
    @param dev_type: the type to look for
447 51cb1581 Luca Bigliardi
    @rtype: boolean
448 51cb1581 Luca Bigliardi
    @return: boolean indicating if a disk of the given type was found or not
449 51cb1581 Luca Bigliardi

450 51cb1581 Luca Bigliardi
    """
451 51cb1581 Luca Bigliardi
    for instance in self.instances.values():
452 51cb1581 Luca Bigliardi
      for disk in instance.disks:
453 51cb1581 Luca Bigliardi
        if disk.IsBasedOnDiskType(dev_type):
454 51cb1581 Luca Bigliardi
          return True
455 51cb1581 Luca Bigliardi
    return False
456 51cb1581 Luca Bigliardi
457 90d726a8 Iustin Pop
  def UpgradeConfig(self):
458 90d726a8 Iustin Pop
    """Fill defaults for missing configuration values.
459 90d726a8 Iustin Pop

460 90d726a8 Iustin Pop
    """
461 90d726a8 Iustin Pop
    self.cluster.UpgradeConfig()
462 90d726a8 Iustin Pop
    for node in self.nodes.values():
463 90d726a8 Iustin Pop
      node.UpgradeConfig()
464 90d726a8 Iustin Pop
    for instance in self.instances.values():
465 90d726a8 Iustin Pop
      instance.UpgradeConfig()
466 3df43542 Guido Trotter
    if self.nodegroups is None:
467 3df43542 Guido Trotter
      self.nodegroups = {}
468 3df43542 Guido Trotter
    for nodegroup in self.nodegroups.values():
469 3df43542 Guido Trotter
      nodegroup.UpgradeConfig()
470 ee2f0ed4 Luca Bigliardi
    if self.cluster.drbd_usermode_helper is None:
471 ee2f0ed4 Luca Bigliardi
      # To decide if we set an helper let's check if at least one instance has
472 ee2f0ed4 Luca Bigliardi
      # a DRBD disk. This does not cover all the possible scenarios but it
473 ee2f0ed4 Luca Bigliardi
      # gives a good approximation.
474 ee2f0ed4 Luca Bigliardi
      if self.HasAnyDiskOfType(constants.LD_DRBD8):
475 ee2f0ed4 Luca Bigliardi
        self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
476 eaa4c57c Dimitris Aragiorgis
    if self.networks is None:
477 eaa4c57c Dimitris Aragiorgis
      self.networks = {}
478 ee9516c8 Guido Trotter
    for network in self.networks.values():
479 ee9516c8 Guido Trotter
      network.UpgradeConfig()
480 c66d8987 Helga Velroyen
    self._UpgradeStorageTypes()
481 c66d8987 Helga Velroyen
482 c66d8987 Helga Velroyen
  def _UpgradeStorageTypes(self):
483 c66d8987 Helga Velroyen
    """Upgrade the cluster's enabled storage types by inspecting the currently
484 c66d8987 Helga Velroyen
       enabled and/or used storage types.
485 c66d8987 Helga Velroyen

486 c66d8987 Helga Velroyen
    """
487 c66d8987 Helga Velroyen
    # enabled_storage_types in the cluster config were introduced in 2.8. Remove
488 c66d8987 Helga Velroyen
    # this code once upgrading from earlier versions is deprecated.
489 c66d8987 Helga Velroyen
    if not self.cluster.enabled_storage_types:
490 c66d8987 Helga Velroyen
      storage_type_set = \
491 c66d8987 Helga Velroyen
        set([constants.DISK_TEMPLATES_STORAGE_TYPE[inst.disk_template]
492 c66d8987 Helga Velroyen
               for inst in self.instances.values()])
493 c66d8987 Helga Velroyen
      # Add lvm, file and shared file storage, if they are enabled, even though
494 c66d8987 Helga Velroyen
      # they might currently not be used.
495 c66d8987 Helga Velroyen
      if self.cluster.volume_group_name:
496 c66d8987 Helga Velroyen
        storage_type_set.add(constants.ST_LVM_VG)
497 c66d8987 Helga Velroyen
      # FIXME: Adapt this when dis/enabling at configure time is removed.
498 c66d8987 Helga Velroyen
      if constants.ENABLE_FILE_STORAGE:
499 c66d8987 Helga Velroyen
        storage_type_set.add(constants.ST_FILE)
500 c66d8987 Helga Velroyen
      if constants.ENABLE_SHARED_FILE_STORAGE:
501 c66d8987 Helga Velroyen
        storage_type_set.add(constants.ST_SHARED_FILE)
502 c66d8987 Helga Velroyen
      # Set enabled_storage_types to the inferred storage types. Order them
503 c66d8987 Helga Velroyen
      # according to a preference list that is based on Ganeti's history of
504 c66d8987 Helga Velroyen
      # supported storage types.
505 c66d8987 Helga Velroyen
      self.cluster.enabled_storage_types = []
506 c66d8987 Helga Velroyen
      for preferred_type in constants.STORAGE_TYPES_PREFERENCE:
507 c66d8987 Helga Velroyen
        if preferred_type in storage_type_set:
508 c66d8987 Helga Velroyen
          self.cluster.enabled_storage_types.append(preferred_type)
509 c66d8987 Helga Velroyen
          storage_type_set.remove(preferred_type)
510 c66d8987 Helga Velroyen
      self.cluster.enabled_storage_types.extend(list(storage_type_set))
511 90d726a8 Iustin Pop
512 a8083063 Iustin Pop
513 a8083063 Iustin Pop
class NIC(ConfigObject):
514 a8083063 Iustin Pop
  """Config object representing a network card."""
515 cbe4a0a5 Dimitris Aragiorgis
  __slots__ = ["mac", "ip", "network", "nicparams", "netinfo"]
516 a8083063 Iustin Pop
517 255e19d4 Guido Trotter
  @classmethod
518 255e19d4 Guido Trotter
  def CheckParameterSyntax(cls, nicparams):
519 255e19d4 Guido Trotter
    """Check the given parameters for validity.
520 255e19d4 Guido Trotter

521 255e19d4 Guido Trotter
    @type nicparams:  dict
522 255e19d4 Guido Trotter
    @param nicparams: dictionary with parameter names/value
523 255e19d4 Guido Trotter
    @raise errors.ConfigurationError: when a parameter is not valid
524 255e19d4 Guido Trotter

525 255e19d4 Guido Trotter
    """
526 53258324 Michael Hanselmann
    mode = nicparams[constants.NIC_MODE]
527 53258324 Michael Hanselmann
    if (mode not in constants.NIC_VALID_MODES and
528 53258324 Michael Hanselmann
        mode != constants.VALUE_AUTO):
529 53258324 Michael Hanselmann
      raise errors.ConfigurationError("Invalid NIC mode '%s'" % mode)
530 255e19d4 Guido Trotter
531 53258324 Michael Hanselmann
    if (mode == constants.NIC_MODE_BRIDGED and
532 255e19d4 Guido Trotter
        not nicparams[constants.NIC_LINK]):
533 53258324 Michael Hanselmann
      raise errors.ConfigurationError("Missing bridged NIC link")
534 255e19d4 Guido Trotter
535 a8083063 Iustin Pop
536 a8083063 Iustin Pop
class Disk(ConfigObject):
537 a8083063 Iustin Pop
  """Config object representing a block device."""
538 a8083063 Iustin Pop
  __slots__ = ["dev_type", "logical_id", "physical_id",
539 bc5d0215 Andrea Spadaccini
               "children", "iv_name", "size", "mode", "params"]
540 a8083063 Iustin Pop
541 a8083063 Iustin Pop
  def CreateOnSecondary(self):
542 a8083063 Iustin Pop
    """Test if this device needs to be created on a secondary node."""
543 00fb8246 Michael Hanselmann
    return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
544 a8083063 Iustin Pop
545 a8083063 Iustin Pop
  def AssembleOnSecondary(self):
546 a8083063 Iustin Pop
    """Test if this device needs to be assembled on a secondary node."""
547 00fb8246 Michael Hanselmann
    return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
548 a8083063 Iustin Pop
549 a8083063 Iustin Pop
  def OpenOnSecondary(self):
550 a8083063 Iustin Pop
    """Test if this device needs to be opened on a secondary node."""
551 fe96220b Iustin Pop
    return self.dev_type in (constants.LD_LV,)
552 a8083063 Iustin Pop
553 222f2dd5 Iustin Pop
  def StaticDevPath(self):
554 222f2dd5 Iustin Pop
    """Return the device path if this device type has a static one.
555 222f2dd5 Iustin Pop

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

560 e51db2a6 Iustin Pop
    @warning: The path returned is not a normalized pathname; callers
561 e51db2a6 Iustin Pop
        should check that it is a valid path.
562 e51db2a6 Iustin Pop

563 222f2dd5 Iustin Pop
    """
564 222f2dd5 Iustin Pop
    if self.dev_type == constants.LD_LV:
565 222f2dd5 Iustin Pop
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
566 b6135bbc Apollon Oikonomopoulos
    elif self.dev_type == constants.LD_BLOCKDEV:
567 b6135bbc Apollon Oikonomopoulos
      return self.logical_id[1]
568 7181fba0 Constantinos Venetsanopoulos
    elif self.dev_type == constants.LD_RBD:
569 7181fba0 Constantinos Venetsanopoulos
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
570 222f2dd5 Iustin Pop
    return None
571 222f2dd5 Iustin Pop
572 fc1dc9d7 Iustin Pop
  def ChildrenNeeded(self):
573 fc1dc9d7 Iustin Pop
    """Compute the needed number of children for activation.
574 fc1dc9d7 Iustin Pop

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

579 fc1dc9d7 Iustin Pop
    Currently, only DRBD8 supports diskless activation (therefore we
580 fc1dc9d7 Iustin Pop
    return 0), for all other we keep the previous semantics and return
581 fc1dc9d7 Iustin Pop
    -1.
582 fc1dc9d7 Iustin Pop

583 fc1dc9d7 Iustin Pop
    """
584 fc1dc9d7 Iustin Pop
    if self.dev_type == constants.LD_DRBD8:
585 fc1dc9d7 Iustin Pop
      return 0
586 fc1dc9d7 Iustin Pop
    return -1
587 fc1dc9d7 Iustin Pop
588 51cb1581 Luca Bigliardi
  def IsBasedOnDiskType(self, dev_type):
589 51cb1581 Luca Bigliardi
    """Check if the disk or its children are based on the given type.
590 51cb1581 Luca Bigliardi

591 51cb1581 Luca Bigliardi
    @type dev_type: L{constants.LDS_BLOCK}
592 51cb1581 Luca Bigliardi
    @param dev_type: the type to look for
593 51cb1581 Luca Bigliardi
    @rtype: boolean
594 51cb1581 Luca Bigliardi
    @return: boolean indicating if a device of the given type was found or not
595 51cb1581 Luca Bigliardi

596 51cb1581 Luca Bigliardi
    """
597 51cb1581 Luca Bigliardi
    if self.children:
598 51cb1581 Luca Bigliardi
      for child in self.children:
599 51cb1581 Luca Bigliardi
        if child.IsBasedOnDiskType(dev_type):
600 51cb1581 Luca Bigliardi
          return True
601 51cb1581 Luca Bigliardi
    return self.dev_type == dev_type
602 51cb1581 Luca Bigliardi
603 a8083063 Iustin Pop
  def GetNodes(self, node):
604 a8083063 Iustin Pop
    """This function returns the nodes this device lives on.
605 a8083063 Iustin Pop

606 a8083063 Iustin Pop
    Given the node on which the parent of the device lives on (or, in
607 a8083063 Iustin Pop
    case of a top-level device, the primary node of the devices'
608 a8083063 Iustin Pop
    instance), this function will return a list of nodes on which this
609 a8083063 Iustin Pop
    devices needs to (or can) be assembled.
610 a8083063 Iustin Pop

611 a8083063 Iustin Pop
    """
612 b6135bbc Apollon Oikonomopoulos
    if self.dev_type in [constants.LD_LV, constants.LD_FILE,
613 376631d1 Constantinos Venetsanopoulos
                         constants.LD_BLOCKDEV, constants.LD_RBD,
614 376631d1 Constantinos Venetsanopoulos
                         constants.LD_EXT]:
615 a8083063 Iustin Pop
      result = [node]
616 a1f445d3 Iustin Pop
    elif self.dev_type in constants.LDS_DRBD:
617 a8083063 Iustin Pop
      result = [self.logical_id[0], self.logical_id[1]]
618 a8083063 Iustin Pop
      if node not in result:
619 3ecf6786 Iustin Pop
        raise errors.ConfigurationError("DRBD device passed unknown node")
620 a8083063 Iustin Pop
    else:
621 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
622 a8083063 Iustin Pop
    return result
623 a8083063 Iustin Pop
624 a8083063 Iustin Pop
  def ComputeNodeTree(self, parent_node):
625 a8083063 Iustin Pop
    """Compute the node/disk tree for this disk and its children.
626 a8083063 Iustin Pop

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

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

662 6d33a6eb Iustin Pop
    This only works for VG-based disks.
663 6d33a6eb Iustin Pop

664 6d33a6eb Iustin Pop
    @type amount: integer
665 6d33a6eb Iustin Pop
    @param amount: the desired increase in (user-visible) disk space
666 6d33a6eb Iustin Pop
    @rtype: dict
667 6d33a6eb Iustin Pop
    @return: a dictionary of volume-groups and the required size
668 6d33a6eb Iustin Pop

669 6d33a6eb Iustin Pop
    """
670 6d33a6eb Iustin Pop
    if self.dev_type == constants.LD_LV:
671 6d33a6eb Iustin Pop
      return {self.logical_id[0]: amount}
672 6d33a6eb Iustin Pop
    elif self.dev_type == constants.LD_DRBD8:
673 6d33a6eb Iustin Pop
      if self.children:
674 6d33a6eb Iustin Pop
        return self.children[0].ComputeGrowth(amount)
675 6d33a6eb Iustin Pop
      else:
676 6d33a6eb Iustin Pop
        return {}
677 6d33a6eb Iustin Pop
    else:
678 6d33a6eb Iustin Pop
      # Other disk types do not require VG space
679 6d33a6eb Iustin Pop
      return {}
680 6d33a6eb Iustin Pop
681 acec9d51 Iustin Pop
  def RecordGrow(self, amount):
682 acec9d51 Iustin Pop
    """Update the size of this disk after growth.
683 acec9d51 Iustin Pop

684 acec9d51 Iustin Pop
    This method recurses over the disks's children and updates their
685 acec9d51 Iustin Pop
    size correspondigly. The method needs to be kept in sync with the
686 acec9d51 Iustin Pop
    actual algorithms from bdev.
687 acec9d51 Iustin Pop

688 acec9d51 Iustin Pop
    """
689 7181fba0 Constantinos Venetsanopoulos
    if self.dev_type in (constants.LD_LV, constants.LD_FILE,
690 376631d1 Constantinos Venetsanopoulos
                         constants.LD_RBD, constants.LD_EXT):
691 acec9d51 Iustin Pop
      self.size += amount
692 acec9d51 Iustin Pop
    elif self.dev_type == constants.LD_DRBD8:
693 acec9d51 Iustin Pop
      if self.children:
694 acec9d51 Iustin Pop
        self.children[0].RecordGrow(amount)
695 acec9d51 Iustin Pop
      self.size += amount
696 acec9d51 Iustin Pop
    else:
697 acec9d51 Iustin Pop
      raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
698 acec9d51 Iustin Pop
                                   " disk type %s" % self.dev_type)
699 acec9d51 Iustin Pop
700 735e1318 Michael Hanselmann
  def Update(self, size=None, mode=None):
701 735e1318 Michael Hanselmann
    """Apply changes to size and mode.
702 735e1318 Michael Hanselmann

703 735e1318 Michael Hanselmann
    """
704 735e1318 Michael Hanselmann
    if self.dev_type == constants.LD_DRBD8:
705 735e1318 Michael Hanselmann
      if self.children:
706 735e1318 Michael Hanselmann
        self.children[0].Update(size=size, mode=mode)
707 735e1318 Michael Hanselmann
    else:
708 735e1318 Michael Hanselmann
      assert not self.children
709 735e1318 Michael Hanselmann
710 735e1318 Michael Hanselmann
    if size is not None:
711 735e1318 Michael Hanselmann
      self.size = size
712 735e1318 Michael Hanselmann
    if mode is not None:
713 735e1318 Michael Hanselmann
      self.mode = mode
714 735e1318 Michael Hanselmann
715 a805ec18 Iustin Pop
  def UnsetSize(self):
716 a805ec18 Iustin Pop
    """Sets recursively the size to zero for the disk and its children.
717 a805ec18 Iustin Pop

718 a805ec18 Iustin Pop
    """
719 a805ec18 Iustin Pop
    if self.children:
720 a805ec18 Iustin Pop
      for child in self.children:
721 a805ec18 Iustin Pop
        child.UnsetSize()
722 a805ec18 Iustin Pop
    self.size = 0
723 a805ec18 Iustin Pop
724 0402302c Iustin Pop
  def SetPhysicalID(self, target_node, nodes_ip):
725 0402302c Iustin Pop
    """Convert the logical ID to the physical ID.
726 0402302c Iustin Pop

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

729 0402302c Iustin Pop
    The routine descends down and updates its children also, because
730 0402302c Iustin Pop
    this helps when the only the top device is passed to the remote
731 0402302c Iustin Pop
    node.
732 0402302c Iustin Pop

733 0402302c Iustin Pop
    Arguments:
734 0402302c Iustin Pop
      - target_node: the node we wish to configure for
735 0402302c Iustin Pop
      - nodes_ip: a mapping of node name to ip
736 0402302c Iustin Pop

737 0402302c Iustin Pop
    The target_node must exist in in nodes_ip, and must be one of the
738 0402302c Iustin Pop
    nodes in the logical ID for each of the DRBD devices encountered
739 0402302c Iustin Pop
    in the disk tree.
740 0402302c Iustin Pop

741 0402302c Iustin Pop
    """
742 0402302c Iustin Pop
    if self.children:
743 0402302c Iustin Pop
      for child in self.children:
744 0402302c Iustin Pop
        child.SetPhysicalID(target_node, nodes_ip)
745 0402302c Iustin Pop
746 0402302c Iustin Pop
    if self.logical_id is None and self.physical_id is not None:
747 0402302c Iustin Pop
      return
748 0402302c Iustin Pop
    if self.dev_type in constants.LDS_DRBD:
749 f9518d38 Iustin Pop
      pnode, snode, port, pminor, sminor, secret = self.logical_id
750 0402302c Iustin Pop
      if target_node not in (pnode, snode):
751 0402302c Iustin Pop
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
752 0402302c Iustin Pop
                                        target_node)
753 0402302c Iustin Pop
      pnode_ip = nodes_ip.get(pnode, None)
754 0402302c Iustin Pop
      snode_ip = nodes_ip.get(snode, None)
755 0402302c Iustin Pop
      if pnode_ip is None or snode_ip is None:
756 0402302c Iustin Pop
        raise errors.ConfigurationError("Can't find primary or secondary node"
757 0402302c Iustin Pop
                                        " for %s" % str(self))
758 ffa1c0dc Iustin Pop
      p_data = (pnode_ip, port)
759 ffa1c0dc Iustin Pop
      s_data = (snode_ip, port)
760 0402302c Iustin Pop
      if pnode == target_node:
761 f9518d38 Iustin Pop
        self.physical_id = p_data + s_data + (pminor, secret)
762 0402302c Iustin Pop
      else: # it must be secondary, we tested above
763 f9518d38 Iustin Pop
        self.physical_id = s_data + p_data + (sminor, secret)
764 0402302c Iustin Pop
    else:
765 0402302c Iustin Pop
      self.physical_id = self.logical_id
766 0402302c Iustin Pop
    return
767 0402302c Iustin Pop
768 ff9c047c Iustin Pop
  def ToDict(self):
769 ff9c047c Iustin Pop
    """Disk-specific conversion to standard python types.
770 ff9c047c Iustin Pop

771 ff9c047c Iustin Pop
    This replaces the children lists of objects with lists of
772 ff9c047c Iustin Pop
    standard python types.
773 ff9c047c Iustin Pop

774 ff9c047c Iustin Pop
    """
775 ff9c047c Iustin Pop
    bo = super(Disk, self).ToDict()
776 ff9c047c Iustin Pop
777 ff9c047c Iustin Pop
    for attr in ("children",):
778 ff9c047c Iustin Pop
      alist = bo.get(attr, None)
779 ff9c047c Iustin Pop
      if alist:
780 fe502d25 Iustin Pop
        bo[attr] = outils.ContainerToDicts(alist)
781 ff9c047c Iustin Pop
    return bo
782 ff9c047c Iustin Pop
783 ff9c047c Iustin Pop
  @classmethod
784 ff9c047c Iustin Pop
  def FromDict(cls, val):
785 ff9c047c Iustin Pop
    """Custom function for Disks
786 ff9c047c Iustin Pop

787 ff9c047c Iustin Pop
    """
788 ff9c047c Iustin Pop
    obj = super(Disk, cls).FromDict(val)
789 ff9c047c Iustin Pop
    if obj.children:
790 fe502d25 Iustin Pop
      obj.children = outils.ContainerFromDicts(obj.children, list, Disk)
791 ff9c047c Iustin Pop
    if obj.logical_id and isinstance(obj.logical_id, list):
792 ff9c047c Iustin Pop
      obj.logical_id = tuple(obj.logical_id)
793 ff9c047c Iustin Pop
    if obj.physical_id and isinstance(obj.physical_id, list):
794 ff9c047c Iustin Pop
      obj.physical_id = tuple(obj.physical_id)
795 f9518d38 Iustin Pop
    if obj.dev_type in constants.LDS_DRBD:
796 f9518d38 Iustin Pop
      # we need a tuple of length six here
797 f9518d38 Iustin Pop
      if len(obj.logical_id) < 6:
798 f9518d38 Iustin Pop
        obj.logical_id += (None,) * (6 - len(obj.logical_id))
799 ff9c047c Iustin Pop
    return obj
800 ff9c047c Iustin Pop
801 65a15336 Iustin Pop
  def __str__(self):
802 65a15336 Iustin Pop
    """Custom str() formatter for disks.
803 65a15336 Iustin Pop

804 65a15336 Iustin Pop
    """
805 65a15336 Iustin Pop
    if self.dev_type == constants.LD_LV:
806 e687ec01 Michael Hanselmann
      val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
807 65a15336 Iustin Pop
    elif self.dev_type in constants.LDS_DRBD:
808 89f28b76 Iustin Pop
      node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
809 00fb8246 Michael Hanselmann
      val = "<DRBD8("
810 073ca59e Iustin Pop
      if self.physical_id is None:
811 073ca59e Iustin Pop
        phy = "unconfigured"
812 073ca59e Iustin Pop
      else:
813 073ca59e Iustin Pop
        phy = ("configured as %s:%s %s:%s" %
814 25a915d0 Iustin Pop
               (self.physical_id[0], self.physical_id[1],
815 25a915d0 Iustin Pop
                self.physical_id[2], self.physical_id[3]))
816 073ca59e Iustin Pop
817 89f28b76 Iustin Pop
      val += ("hosts=%s/%d-%s/%d, port=%s, %s, " %
818 89f28b76 Iustin Pop
              (node_a, minor_a, node_b, minor_b, port, phy))
819 65a15336 Iustin Pop
      if self.children and self.children.count(None) == 0:
820 65a15336 Iustin Pop
        val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
821 65a15336 Iustin Pop
      else:
822 65a15336 Iustin Pop
        val += "no local storage"
823 65a15336 Iustin Pop
    else:
824 65a15336 Iustin Pop
      val = ("<Disk(type=%s, logical_id=%s, physical_id=%s, children=%s" %
825 65a15336 Iustin Pop
             (self.dev_type, self.logical_id, self.physical_id, self.children))
826 65a15336 Iustin Pop
    if self.iv_name is None:
827 65a15336 Iustin Pop
      val += ", not visible"
828 65a15336 Iustin Pop
    else:
829 65a15336 Iustin Pop
      val += ", visible as /dev/%s" % self.iv_name
830 fd965830 Iustin Pop
    if isinstance(self.size, int):
831 fd965830 Iustin Pop
      val += ", size=%dm)>" % self.size
832 fd965830 Iustin Pop
    else:
833 fd965830 Iustin Pop
      val += ", size='%s')>" % (self.size,)
834 65a15336 Iustin Pop
    return val
835 65a15336 Iustin Pop
836 332d0e37 Iustin Pop
  def Verify(self):
837 332d0e37 Iustin Pop
    """Checks that this disk is correctly configured.
838 332d0e37 Iustin Pop

839 332d0e37 Iustin Pop
    """
840 7c4d6c7b Michael Hanselmann
    all_errors = []
841 332d0e37 Iustin Pop
    if self.mode not in constants.DISK_ACCESS_SET:
842 7c4d6c7b Michael Hanselmann
      all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
843 7c4d6c7b Michael Hanselmann
    return all_errors
844 332d0e37 Iustin Pop
845 90d726a8 Iustin Pop
  def UpgradeConfig(self):
846 90d726a8 Iustin Pop
    """Fill defaults for missing configuration values.
847 90d726a8 Iustin Pop

848 90d726a8 Iustin Pop
    """
849 90d726a8 Iustin Pop
    if self.children:
850 90d726a8 Iustin Pop
      for child in self.children:
851 90d726a8 Iustin Pop
        child.UpgradeConfig()
852 bc5d0215 Andrea Spadaccini
853 cce46164 Renรฉ Nussbaumer
    # FIXME: Make this configurable in Ganeti 2.7
854 5dbee5ea Iustin Pop
    self.params = {}
855 90d726a8 Iustin Pop
    # add here config upgrade for this disk
856 90d726a8 Iustin Pop
857 cd46491f Renรฉ Nussbaumer
  @staticmethod
858 cd46491f Renรฉ Nussbaumer
  def ComputeLDParams(disk_template, disk_params):
859 cd46491f Renรฉ Nussbaumer
    """Computes Logical Disk parameters from Disk Template parameters.
860 cd46491f Renรฉ Nussbaumer

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

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

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

932 ffa339ca Iustin Pop
  """
933 918eb80b Agata Murawska
  @classmethod
934 8b057218 Renรฉ Nussbaumer
  def CheckParameterSyntax(cls, ipolicy, check_std):
935 918eb80b Agata Murawska
    """ Check the instance policy for validity.
936 918eb80b Agata Murawska

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

943 918eb80b Agata Murawska
    """
944 da5f09ef Bernardo Dal Seno
    if constants.ISPECS_MINMAX in ipolicy:
945 da5f09ef Bernardo Dal Seno
      if check_std and constants.ISPECS_STD not in ipolicy:
946 da5f09ef Bernardo Dal Seno
        msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
947 da5f09ef Bernardo Dal Seno
        raise errors.ConfigurationError(msg)
948 da5f09ef Bernardo Dal Seno
      minmaxspecs = ipolicy[constants.ISPECS_MINMAX]
949 da5f09ef Bernardo Dal Seno
      stdspec = ipolicy.get(constants.ISPECS_STD)
950 da5f09ef Bernardo Dal Seno
      for param in constants.ISPECS_PARAMETERS:
951 da5f09ef Bernardo Dal Seno
        InstancePolicy.CheckISpecSyntax(minmaxspecs, stdspec, param, check_std)
952 d04c9d45 Iustin Pop
    if constants.IPOLICY_DTS in ipolicy:
953 d04c9d45 Iustin Pop
      InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
954 ff6c5e55 Iustin Pop
    for key in constants.IPOLICY_PARAMETERS:
955 ff6c5e55 Iustin Pop
      if key in ipolicy:
956 ff6c5e55 Iustin Pop
        InstancePolicy.CheckParameter(key, ipolicy[key])
957 57dc299a Iustin Pop
    wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
958 57dc299a Iustin Pop
    if wrong_keys:
959 57dc299a Iustin Pop
      raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
960 57dc299a Iustin Pop
                                      utils.CommaJoin(wrong_keys))
961 918eb80b Agata Murawska
962 918eb80b Agata Murawska
  @classmethod
963 da5f09ef Bernardo Dal Seno
  def CheckISpecSyntax(cls, minmaxspecs, stdspec, name, check_std):
964 da5f09ef Bernardo Dal Seno
    """Check the instance policy specs for validity on a given key.
965 918eb80b Agata Murawska

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

969 da5f09ef Bernardo Dal Seno
    @type minmaxspecs: dict
970 da5f09ef Bernardo Dal Seno
    @param minmaxspecs: dictionary with min and max instance spec
971 da5f09ef Bernardo Dal Seno
    @type stdspec: dict
972 da5f09ef Bernardo Dal Seno
    @param stdspec: dictionary with standard instance spec
973 918eb80b Agata Murawska
    @type name: string
974 918eb80b Agata Murawska
    @param name: what are the limits for
975 8b057218 Renรฉ Nussbaumer
    @type check_std: bool
976 8b057218 Renรฉ Nussbaumer
    @param check_std: Whether to check std value or just assume compliance
977 da5f09ef Bernardo Dal Seno
    @raise errors.ConfigurationError: when specs for the given name are not
978 da5f09ef Bernardo Dal Seno
        valid
979 918eb80b Agata Murawska

980 918eb80b Agata Murawska
    """
981 da5f09ef Bernardo Dal Seno
    missing = constants.ISPECS_MINMAX_KEYS - frozenset(minmaxspecs.keys())
982 da5f09ef Bernardo Dal Seno
    if missing:
983 da5f09ef Bernardo Dal Seno
      msg = "Missing instance specification: %s" % utils.CommaJoin(missing)
984 da5f09ef Bernardo Dal Seno
      raise errors.ConfigurationError(msg)
985 da5f09ef Bernardo Dal Seno
986 da5f09ef Bernardo Dal Seno
    minspec = minmaxspecs[constants.ISPECS_MIN]
987 da5f09ef Bernardo Dal Seno
    maxspec = minmaxspecs[constants.ISPECS_MAX]
988 da5f09ef Bernardo Dal Seno
    min_v = minspec.get(name, 0)
989 8b057218 Renรฉ Nussbaumer
990 8b057218 Renรฉ Nussbaumer
    if check_std:
991 da5f09ef Bernardo Dal Seno
      std_v = stdspec.get(name, min_v)
992 8b057218 Renรฉ Nussbaumer
      std_msg = std_v
993 8b057218 Renรฉ Nussbaumer
    else:
994 8b057218 Renรฉ Nussbaumer
      std_v = min_v
995 8b057218 Renรฉ Nussbaumer
      std_msg = "-"
996 8b057218 Renรฉ Nussbaumer
997 da5f09ef Bernardo Dal Seno
    max_v = maxspec.get(name, std_v)
998 918eb80b Agata Murawska
    if min_v > std_v or std_v > max_v:
999 da5f09ef Bernardo Dal Seno
      err = ("Invalid specification of min/max/std values for %s: %s/%s/%s" %
1000 da5f09ef Bernardo Dal Seno
             (name,
1001 da5f09ef Bernardo Dal Seno
              minspec.get(name, "-"),
1002 da5f09ef Bernardo Dal Seno
              maxspec.get(name, "-"),
1003 da5f09ef Bernardo Dal Seno
              std_msg))
1004 918eb80b Agata Murawska
      raise errors.ConfigurationError(err)
1005 918eb80b Agata Murawska
1006 2cc673a3 Iustin Pop
  @classmethod
1007 2cc673a3 Iustin Pop
  def CheckDiskTemplates(cls, disk_templates):
1008 2cc673a3 Iustin Pop
    """Checks the disk templates for validity.
1009 2cc673a3 Iustin Pop

1010 2cc673a3 Iustin Pop
    """
1011 ba5c6c6b Bernardo Dal Seno
    if not disk_templates:
1012 ba5c6c6b Bernardo Dal Seno
      raise errors.ConfigurationError("Instance policy must contain" +
1013 ba5c6c6b Bernardo Dal Seno
                                      " at least one disk template")
1014 2cc673a3 Iustin Pop
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1015 2cc673a3 Iustin Pop
    if wrong:
1016 2cc673a3 Iustin Pop
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1017 2cc673a3 Iustin Pop
                                      utils.CommaJoin(wrong))
1018 2cc673a3 Iustin Pop
1019 ff6c5e55 Iustin Pop
  @classmethod
1020 ff6c5e55 Iustin Pop
  def CheckParameter(cls, key, value):
1021 ff6c5e55 Iustin Pop
    """Checks a parameter.
1022 ff6c5e55 Iustin Pop

1023 ff6c5e55 Iustin Pop
    Currently we expect all parameters to be float values.
1024 ff6c5e55 Iustin Pop

1025 ff6c5e55 Iustin Pop
    """
1026 ff6c5e55 Iustin Pop
    try:
1027 ff6c5e55 Iustin Pop
      float(value)
1028 ff6c5e55 Iustin Pop
    except (TypeError, ValueError), err:
1029 ff6c5e55 Iustin Pop
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1030 ff6c5e55 Iustin Pop
                                      " '%s', error: %s" % (key, value, err))
1031 ff6c5e55 Iustin Pop
1032 918eb80b Agata Murawska
1033 ec29fe40 Iustin Pop
class Instance(TaggableObject):
1034 a8083063 Iustin Pop
  """Config object representing an instance."""
1035 154b9580 Balazs Lecz
  __slots__ = [
1036 a8083063 Iustin Pop
    "name",
1037 a8083063 Iustin Pop
    "primary_node",
1038 a8083063 Iustin Pop
    "os",
1039 e69d05fd Iustin Pop
    "hypervisor",
1040 5bf7b5cf Iustin Pop
    "hvparams",
1041 5bf7b5cf Iustin Pop
    "beparams",
1042 1bdcbbab Iustin Pop
    "osparams",
1043 9ca8a7c5 Agata Murawska
    "admin_state",
1044 a8083063 Iustin Pop
    "nics",
1045 a8083063 Iustin Pop
    "disks",
1046 a8083063 Iustin Pop
    "disk_template",
1047 58acb49d Alexander Schreiber
    "network_port",
1048 be1fa613 Iustin Pop
    "serial_no",
1049 e1dcc53a Iustin Pop
    ] + _TIMESTAMPS + _UUID
1050 a8083063 Iustin Pop
1051 a8083063 Iustin Pop
  def _ComputeSecondaryNodes(self):
1052 a8083063 Iustin Pop
    """Compute the list of secondary nodes.
1053 a8083063 Iustin Pop

1054 cfcc5c6d Iustin Pop
    This is a simple wrapper over _ComputeAllNodes.
1055 cfcc5c6d Iustin Pop

1056 cfcc5c6d Iustin Pop
    """
1057 cfcc5c6d Iustin Pop
    all_nodes = set(self._ComputeAllNodes())
1058 cfcc5c6d Iustin Pop
    all_nodes.discard(self.primary_node)
1059 cfcc5c6d Iustin Pop
    return tuple(all_nodes)
1060 cfcc5c6d Iustin Pop
1061 cfcc5c6d Iustin Pop
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1062 05325a35 Bernardo Dal Seno
                             "List of names of secondary nodes")
1063 cfcc5c6d Iustin Pop
1064 cfcc5c6d Iustin Pop
  def _ComputeAllNodes(self):
1065 cfcc5c6d Iustin Pop
    """Compute the list of all nodes.
1066 cfcc5c6d Iustin Pop

1067 a8083063 Iustin Pop
    Since the data is already there (in the drbd disks), keeping it as
1068 a8083063 Iustin Pop
    a separate normal attribute is redundant and if not properly
1069 a8083063 Iustin Pop
    synchronised can cause problems. Thus it's better to compute it
1070 a8083063 Iustin Pop
    dynamically.
1071 a8083063 Iustin Pop

1072 a8083063 Iustin Pop
    """
1073 cfcc5c6d Iustin Pop
    def _Helper(nodes, device):
1074 cfcc5c6d Iustin Pop
      """Recursively computes nodes given a top device."""
1075 a1f445d3 Iustin Pop
      if device.dev_type in constants.LDS_DRBD:
1076 cfcc5c6d Iustin Pop
        nodea, nodeb = device.logical_id[:2]
1077 cfcc5c6d Iustin Pop
        nodes.add(nodea)
1078 cfcc5c6d Iustin Pop
        nodes.add(nodeb)
1079 a8083063 Iustin Pop
      if device.children:
1080 a8083063 Iustin Pop
        for child in device.children:
1081 cfcc5c6d Iustin Pop
          _Helper(nodes, child)
1082 a8083063 Iustin Pop
1083 cfcc5c6d Iustin Pop
    all_nodes = set()
1084 99c7b2a1 Iustin Pop
    all_nodes.add(self.primary_node)
1085 a8083063 Iustin Pop
    for device in self.disks:
1086 cfcc5c6d Iustin Pop
      _Helper(all_nodes, device)
1087 cfcc5c6d Iustin Pop
    return tuple(all_nodes)
1088 a8083063 Iustin Pop
1089 cfcc5c6d Iustin Pop
  all_nodes = property(_ComputeAllNodes, None, None,
1090 05325a35 Bernardo Dal Seno
                       "List of names of all the nodes of the instance")
1091 a8083063 Iustin Pop
1092 a8083063 Iustin Pop
  def MapLVsByNode(self, lvmap=None, devs=None, node=None):
1093 a8083063 Iustin Pop
    """Provide a mapping of nodes to LVs this instance owns.
1094 a8083063 Iustin Pop

1095 c41eea6e Iustin Pop
    This function figures out what logical volumes should belong on
1096 c41eea6e Iustin Pop
    which nodes, recursing through a device tree.
1097 a8083063 Iustin Pop

1098 c41eea6e Iustin Pop
    @param lvmap: optional dictionary to receive the
1099 c41eea6e Iustin Pop
        'node' : ['lv', ...] data.
1100 a8083063 Iustin Pop

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

1106 a8083063 Iustin Pop
    """
1107 5ae4945a Iustin Pop
    if node is None:
1108 a8083063 Iustin Pop
      node = self.primary_node
1109 a8083063 Iustin Pop
1110 a8083063 Iustin Pop
    if lvmap is None:
1111 e687ec01 Michael Hanselmann
      lvmap = {
1112 e687ec01 Michael Hanselmann
        node: [],
1113 e687ec01 Michael Hanselmann
        }
1114 a8083063 Iustin Pop
      ret = lvmap
1115 a8083063 Iustin Pop
    else:
1116 a8083063 Iustin Pop
      if not node in lvmap:
1117 a8083063 Iustin Pop
        lvmap[node] = []
1118 a8083063 Iustin Pop
      ret = None
1119 a8083063 Iustin Pop
1120 a8083063 Iustin Pop
    if not devs:
1121 a8083063 Iustin Pop
      devs = self.disks
1122 a8083063 Iustin Pop
1123 a8083063 Iustin Pop
    for dev in devs:
1124 fe96220b Iustin Pop
      if dev.dev_type == constants.LD_LV:
1125 e687ec01 Michael Hanselmann
        lvmap[node].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1126 a8083063 Iustin Pop
1127 a1f445d3 Iustin Pop
      elif dev.dev_type in constants.LDS_DRBD:
1128 a8083063 Iustin Pop
        if dev.children:
1129 a8083063 Iustin Pop
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1130 a8083063 Iustin Pop
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1131 a8083063 Iustin Pop
1132 a8083063 Iustin Pop
      elif dev.children:
1133 a8083063 Iustin Pop
        self.MapLVsByNode(lvmap, dev.children, node)
1134 a8083063 Iustin Pop
1135 a8083063 Iustin Pop
    return ret
1136 a8083063 Iustin Pop
1137 ad24e046 Iustin Pop
  def FindDisk(self, idx):
1138 ad24e046 Iustin Pop
    """Find a disk given having a specified index.
1139 644eeef9 Iustin Pop

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

1142 ad24e046 Iustin Pop
    @type idx: int
1143 ad24e046 Iustin Pop
    @param idx: the disk index
1144 ad24e046 Iustin Pop
    @rtype: L{Disk}
1145 ad24e046 Iustin Pop
    @return: the corresponding disk
1146 ad24e046 Iustin Pop
    @raise errors.OpPrereqError: when the given index is not valid
1147 644eeef9 Iustin Pop

1148 ad24e046 Iustin Pop
    """
1149 ad24e046 Iustin Pop
    try:
1150 ad24e046 Iustin Pop
      idx = int(idx)
1151 ad24e046 Iustin Pop
      return self.disks[idx]
1152 691744c4 Iustin Pop
    except (TypeError, ValueError), err:
1153 debac808 Iustin Pop
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1154 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
1155 ad24e046 Iustin Pop
    except IndexError:
1156 ad24e046 Iustin Pop
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1157 daa55b04 Michael Hanselmann
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1158 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
1159 644eeef9 Iustin Pop
1160 ff9c047c Iustin Pop
  def ToDict(self):
1161 ff9c047c Iustin Pop
    """Instance-specific conversion to standard python types.
1162 ff9c047c Iustin Pop

1163 ff9c047c Iustin Pop
    This replaces the children lists of objects with lists of standard
1164 ff9c047c Iustin Pop
    python types.
1165 ff9c047c Iustin Pop

1166 ff9c047c Iustin Pop
    """
1167 ff9c047c Iustin Pop
    bo = super(Instance, self).ToDict()
1168 ff9c047c Iustin Pop
1169 ff9c047c Iustin Pop
    for attr in "nics", "disks":
1170 ff9c047c Iustin Pop
      alist = bo.get(attr, None)
1171 ff9c047c Iustin Pop
      if alist:
1172 fe502d25 Iustin Pop
        nlist = outils.ContainerToDicts(alist)
1173 ff9c047c Iustin Pop
      else:
1174 ff9c047c Iustin Pop
        nlist = []
1175 ff9c047c Iustin Pop
      bo[attr] = nlist
1176 ff9c047c Iustin Pop
    return bo
1177 ff9c047c Iustin Pop
1178 ff9c047c Iustin Pop
  @classmethod
1179 ff9c047c Iustin Pop
  def FromDict(cls, val):
1180 ff9c047c Iustin Pop
    """Custom function for instances.
1181 ff9c047c Iustin Pop

1182 ff9c047c Iustin Pop
    """
1183 9ca8a7c5 Agata Murawska
    if "admin_state" not in val:
1184 9ca8a7c5 Agata Murawska
      if val.get("admin_up", False):
1185 9ca8a7c5 Agata Murawska
        val["admin_state"] = constants.ADMINST_UP
1186 9ca8a7c5 Agata Murawska
      else:
1187 9ca8a7c5 Agata Murawska
        val["admin_state"] = constants.ADMINST_DOWN
1188 9ca8a7c5 Agata Murawska
    if "admin_up" in val:
1189 9ca8a7c5 Agata Murawska
      del val["admin_up"]
1190 ff9c047c Iustin Pop
    obj = super(Instance, cls).FromDict(val)
1191 fe502d25 Iustin Pop
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1192 fe502d25 Iustin Pop
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1193 ff9c047c Iustin Pop
    return obj
1194 ff9c047c Iustin Pop
1195 90d726a8 Iustin Pop
  def UpgradeConfig(self):
1196 90d726a8 Iustin Pop
    """Fill defaults for missing configuration values.
1197 90d726a8 Iustin Pop

1198 90d726a8 Iustin Pop
    """
1199 90d726a8 Iustin Pop
    for nic in self.nics:
1200 90d726a8 Iustin Pop
      nic.UpgradeConfig()
1201 90d726a8 Iustin Pop
    for disk in self.disks:
1202 90d726a8 Iustin Pop
      disk.UpgradeConfig()
1203 7736a5f2 Iustin Pop
    if self.hvparams:
1204 7736a5f2 Iustin Pop
      for key in constants.HVC_GLOBALS:
1205 7736a5f2 Iustin Pop
        try:
1206 7736a5f2 Iustin Pop
          del self.hvparams[key]
1207 7736a5f2 Iustin Pop
        except KeyError:
1208 7736a5f2 Iustin Pop
          pass
1209 1bdcbbab Iustin Pop
    if self.osparams is None:
1210 1bdcbbab Iustin Pop
      self.osparams = {}
1211 8c72ab2b Guido Trotter
    UpgradeBeParams(self.beparams)
1212 90d726a8 Iustin Pop
1213 a8083063 Iustin Pop
1214 a8083063 Iustin Pop
class OS(ConfigObject):
1215 b41b3516 Iustin Pop
  """Config object representing an operating system.
1216 b41b3516 Iustin Pop

1217 b41b3516 Iustin Pop
  @type supported_parameters: list
1218 b41b3516 Iustin Pop
  @ivar supported_parameters: a list of tuples, name and description,
1219 b41b3516 Iustin Pop
      containing the supported parameters by this OS
1220 b41b3516 Iustin Pop

1221 870dc44c Iustin Pop
  @type VARIANT_DELIM: string
1222 870dc44c Iustin Pop
  @cvar VARIANT_DELIM: the variant delimiter
1223 870dc44c Iustin Pop

1224 b41b3516 Iustin Pop
  """
1225 a8083063 Iustin Pop
  __slots__ = [
1226 a8083063 Iustin Pop
    "name",
1227 a8083063 Iustin Pop
    "path",
1228 082a7f91 Guido Trotter
    "api_versions",
1229 a8083063 Iustin Pop
    "create_script",
1230 a8083063 Iustin Pop
    "export_script",
1231 386b57af Iustin Pop
    "import_script",
1232 386b57af Iustin Pop
    "rename_script",
1233 b41b3516 Iustin Pop
    "verify_script",
1234 6d79896b Guido Trotter
    "supported_variants",
1235 b41b3516 Iustin Pop
    "supported_parameters",
1236 a8083063 Iustin Pop
    ]
1237 a8083063 Iustin Pop
1238 870dc44c Iustin Pop
  VARIANT_DELIM = "+"
1239 870dc44c Iustin Pop
1240 870dc44c Iustin Pop
  @classmethod
1241 870dc44c Iustin Pop
  def SplitNameVariant(cls, name):
1242 870dc44c Iustin Pop
    """Splits the name into the proper name and variant.
1243 870dc44c Iustin Pop

1244 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1245 870dc44c Iustin Pop
    @rtype: list
1246 870dc44c Iustin Pop
    @return: a list of two elements; if the original name didn't
1247 870dc44c Iustin Pop
        contain a variant, it's returned as an empty string
1248 870dc44c Iustin Pop

1249 870dc44c Iustin Pop
    """
1250 870dc44c Iustin Pop
    nv = name.split(cls.VARIANT_DELIM, 1)
1251 870dc44c Iustin Pop
    if len(nv) == 1:
1252 870dc44c Iustin Pop
      nv.append("")
1253 870dc44c Iustin Pop
    return nv
1254 870dc44c Iustin Pop
1255 870dc44c Iustin Pop
  @classmethod
1256 870dc44c Iustin Pop
  def GetName(cls, name):
1257 870dc44c Iustin Pop
    """Returns the proper name of the os (without the variant).
1258 870dc44c Iustin Pop

1259 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1260 870dc44c Iustin Pop

1261 870dc44c Iustin Pop
    """
1262 870dc44c Iustin Pop
    return cls.SplitNameVariant(name)[0]
1263 870dc44c Iustin Pop
1264 870dc44c Iustin Pop
  @classmethod
1265 870dc44c Iustin Pop
  def GetVariant(cls, name):
1266 870dc44c Iustin Pop
    """Returns the variant the os (without the base name).
1267 870dc44c Iustin Pop

1268 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1269 870dc44c Iustin Pop

1270 870dc44c Iustin Pop
    """
1271 870dc44c Iustin Pop
    return cls.SplitNameVariant(name)[1]
1272 870dc44c Iustin Pop
1273 7c0d6283 Michael Hanselmann
1274 376631d1 Constantinos Venetsanopoulos
class ExtStorage(ConfigObject):
1275 376631d1 Constantinos Venetsanopoulos
  """Config object representing an External Storage Provider.
1276 376631d1 Constantinos Venetsanopoulos

1277 376631d1 Constantinos Venetsanopoulos
  """
1278 376631d1 Constantinos Venetsanopoulos
  __slots__ = [
1279 376631d1 Constantinos Venetsanopoulos
    "name",
1280 376631d1 Constantinos Venetsanopoulos
    "path",
1281 376631d1 Constantinos Venetsanopoulos
    "create_script",
1282 376631d1 Constantinos Venetsanopoulos
    "remove_script",
1283 376631d1 Constantinos Venetsanopoulos
    "grow_script",
1284 376631d1 Constantinos Venetsanopoulos
    "attach_script",
1285 376631d1 Constantinos Venetsanopoulos
    "detach_script",
1286 376631d1 Constantinos Venetsanopoulos
    "setinfo_script",
1287 938adc87 Constantinos Venetsanopoulos
    "verify_script",
1288 938adc87 Constantinos Venetsanopoulos
    "supported_parameters",
1289 376631d1 Constantinos Venetsanopoulos
    ]
1290 376631d1 Constantinos Venetsanopoulos
1291 376631d1 Constantinos Venetsanopoulos
1292 5f06ce5e Michael Hanselmann
class NodeHvState(ConfigObject):
1293 5f06ce5e Michael Hanselmann
  """Hypvervisor state on a node.
1294 5f06ce5e Michael Hanselmann

1295 5f06ce5e Michael Hanselmann
  @ivar mem_total: Total amount of memory
1296 5f06ce5e Michael Hanselmann
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1297 5f06ce5e Michael Hanselmann
    available)
1298 5f06ce5e Michael Hanselmann
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1299 5f06ce5e Michael Hanselmann
    rounding
1300 5f06ce5e Michael Hanselmann
  @ivar mem_inst: Memory used by instances living on node
1301 5f06ce5e Michael Hanselmann
  @ivar cpu_total: Total node CPU core count
1302 5f06ce5e Michael Hanselmann
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1303 5f06ce5e Michael Hanselmann

1304 5f06ce5e Michael Hanselmann
  """
1305 5f06ce5e Michael Hanselmann
  __slots__ = [
1306 5f06ce5e Michael Hanselmann
    "mem_total",
1307 5f06ce5e Michael Hanselmann
    "mem_node",
1308 5f06ce5e Michael Hanselmann
    "mem_hv",
1309 5f06ce5e Michael Hanselmann
    "mem_inst",
1310 5f06ce5e Michael Hanselmann
    "cpu_total",
1311 5f06ce5e Michael Hanselmann
    "cpu_node",
1312 5f06ce5e Michael Hanselmann
    ] + _TIMESTAMPS
1313 5f06ce5e Michael Hanselmann
1314 5f06ce5e Michael Hanselmann
1315 5f06ce5e Michael Hanselmann
class NodeDiskState(ConfigObject):
1316 5f06ce5e Michael Hanselmann
  """Disk state on a node.
1317 5f06ce5e Michael Hanselmann

1318 5f06ce5e Michael Hanselmann
  """
1319 5f06ce5e Michael Hanselmann
  __slots__ = [
1320 5f06ce5e Michael Hanselmann
    "total",
1321 5f06ce5e Michael Hanselmann
    "reserved",
1322 5f06ce5e Michael Hanselmann
    "overhead",
1323 5f06ce5e Michael Hanselmann
    ] + _TIMESTAMPS
1324 5f06ce5e Michael Hanselmann
1325 5f06ce5e Michael Hanselmann
1326 ec29fe40 Iustin Pop
class Node(TaggableObject):
1327 634d30f4 Michael Hanselmann
  """Config object representing a node.
1328 634d30f4 Michael Hanselmann

1329 634d30f4 Michael Hanselmann
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1330 634d30f4 Michael Hanselmann
  @ivar hv_state_static: Hypervisor state overriden by user
1331 634d30f4 Michael Hanselmann
  @ivar disk_state: Disk state (e.g. free space)
1332 634d30f4 Michael Hanselmann
  @ivar disk_state_static: Disk state overriden by user
1333 634d30f4 Michael Hanselmann

1334 634d30f4 Michael Hanselmann
  """
1335 154b9580 Balazs Lecz
  __slots__ = [
1336 ec29fe40 Iustin Pop
    "name",
1337 ec29fe40 Iustin Pop
    "primary_ip",
1338 ec29fe40 Iustin Pop
    "secondary_ip",
1339 be1fa613 Iustin Pop
    "serial_no",
1340 8b8b8b81 Iustin Pop
    "master_candidate",
1341 fc0fe88c Iustin Pop
    "offline",
1342 af64c0ea Iustin Pop
    "drained",
1343 f936c153 Iustin Pop
    "group",
1344 490acd18 Iustin Pop
    "master_capable",
1345 490acd18 Iustin Pop
    "vm_capable",
1346 095e71aa Renรฉ Nussbaumer
    "ndparams",
1347 25124d4a Renรฉ Nussbaumer
    "powered",
1348 5b49ed09 Renรฉ Nussbaumer
    "hv_state",
1349 634d30f4 Michael Hanselmann
    "hv_state_static",
1350 5b49ed09 Renรฉ Nussbaumer
    "disk_state",
1351 634d30f4 Michael Hanselmann
    "disk_state_static",
1352 e1dcc53a Iustin Pop
    ] + _TIMESTAMPS + _UUID
1353 a8083063 Iustin Pop
1354 490acd18 Iustin Pop
  def UpgradeConfig(self):
1355 490acd18 Iustin Pop
    """Fill defaults for missing configuration values.
1356 490acd18 Iustin Pop

1357 490acd18 Iustin Pop
    """
1358 b459a848 Andrea Spadaccini
    # pylint: disable=E0203
1359 490acd18 Iustin Pop
    # because these are "defined" via slots, not manually
1360 490acd18 Iustin Pop
    if self.master_capable is None:
1361 490acd18 Iustin Pop
      self.master_capable = True
1362 490acd18 Iustin Pop
1363 490acd18 Iustin Pop
    if self.vm_capable is None:
1364 490acd18 Iustin Pop
      self.vm_capable = True
1365 490acd18 Iustin Pop
1366 095e71aa Renรฉ Nussbaumer
    if self.ndparams is None:
1367 095e71aa Renรฉ Nussbaumer
      self.ndparams = {}
1368 250a9404 Bernardo Dal Seno
    # And remove any global parameter
1369 250a9404 Bernardo Dal Seno
    for key in constants.NDC_GLOBALS:
1370 250a9404 Bernardo Dal Seno
      if key in self.ndparams:
1371 250a9404 Bernardo Dal Seno
        logging.warning("Ignoring %s node parameter for node %s",
1372 250a9404 Bernardo Dal Seno
                        key, self.name)
1373 250a9404 Bernardo Dal Seno
        del self.ndparams[key]
1374 095e71aa Renรฉ Nussbaumer
1375 25124d4a Renรฉ Nussbaumer
    if self.powered is None:
1376 25124d4a Renรฉ Nussbaumer
      self.powered = True
1377 25124d4a Renรฉ Nussbaumer
1378 5f06ce5e Michael Hanselmann
  def ToDict(self):
1379 5f06ce5e Michael Hanselmann
    """Custom function for serializing.
1380 5f06ce5e Michael Hanselmann

1381 5f06ce5e Michael Hanselmann
    """
1382 5f06ce5e Michael Hanselmann
    data = super(Node, self).ToDict()
1383 5f06ce5e Michael Hanselmann
1384 5f06ce5e Michael Hanselmann
    hv_state = data.get("hv_state", None)
1385 5f06ce5e Michael Hanselmann
    if hv_state is not None:
1386 fe502d25 Iustin Pop
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1387 5f06ce5e Michael Hanselmann
1388 5f06ce5e Michael Hanselmann
    disk_state = data.get("disk_state", None)
1389 5f06ce5e Michael Hanselmann
    if disk_state is not None:
1390 5f06ce5e Michael Hanselmann
      data["disk_state"] = \
1391 fe502d25 Iustin Pop
        dict((key, outils.ContainerToDicts(value))
1392 5f06ce5e Michael Hanselmann
             for (key, value) in disk_state.items())
1393 5f06ce5e Michael Hanselmann
1394 5f06ce5e Michael Hanselmann
    return data
1395 5f06ce5e Michael Hanselmann
1396 5f06ce5e Michael Hanselmann
  @classmethod
1397 5f06ce5e Michael Hanselmann
  def FromDict(cls, val):
1398 5f06ce5e Michael Hanselmann
    """Custom function for deserializing.
1399 5f06ce5e Michael Hanselmann

1400 5f06ce5e Michael Hanselmann
    """
1401 5f06ce5e Michael Hanselmann
    obj = super(Node, cls).FromDict(val)
1402 5f06ce5e Michael Hanselmann
1403 5f06ce5e Michael Hanselmann
    if obj.hv_state is not None:
1404 473ab806 Michael Hanselmann
      obj.hv_state = \
1405 fe502d25 Iustin Pop
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1406 5f06ce5e Michael Hanselmann
1407 5f06ce5e Michael Hanselmann
    if obj.disk_state is not None:
1408 5f06ce5e Michael Hanselmann
      obj.disk_state = \
1409 fe502d25 Iustin Pop
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1410 5f06ce5e Michael Hanselmann
             for (key, value) in obj.disk_state.items())
1411 5f06ce5e Michael Hanselmann
1412 5f06ce5e Michael Hanselmann
    return obj
1413 5f06ce5e Michael Hanselmann
1414 a8083063 Iustin Pop
1415 1ffd2673 Michael Hanselmann
class NodeGroup(TaggableObject):
1416 24a3707f Guido Trotter
  """Config object representing a node group."""
1417 24a3707f Guido Trotter
  __slots__ = [
1418 24a3707f Guido Trotter
    "name",
1419 24a3707f Guido Trotter
    "members",
1420 095e71aa Renรฉ Nussbaumer
    "ndparams",
1421 bc5d0215 Andrea Spadaccini
    "diskparams",
1422 81e3ab4f Agata Murawska
    "ipolicy",
1423 e11a1b77 Adeodato Simo
    "serial_no",
1424 a8282327 Renรฉ Nussbaumer
    "hv_state_static",
1425 a8282327 Renรฉ Nussbaumer
    "disk_state_static",
1426 90e99856 Adeodato Simo
    "alloc_policy",
1427 eaa4c57c Dimitris Aragiorgis
    "networks",
1428 24a3707f Guido Trotter
    ] + _TIMESTAMPS + _UUID
1429 24a3707f Guido Trotter
1430 24a3707f Guido Trotter
  def ToDict(self):
1431 24a3707f Guido Trotter
    """Custom function for nodegroup.
1432 24a3707f Guido Trotter

1433 c60abd62 Guido Trotter
    This discards the members object, which gets recalculated and is only kept
1434 c60abd62 Guido Trotter
    in memory.
1435 24a3707f Guido Trotter

1436 24a3707f Guido Trotter
    """
1437 24a3707f Guido Trotter
    mydict = super(NodeGroup, self).ToDict()
1438 24a3707f Guido Trotter
    del mydict["members"]
1439 24a3707f Guido Trotter
    return mydict
1440 24a3707f Guido Trotter
1441 24a3707f Guido Trotter
  @classmethod
1442 24a3707f Guido Trotter
  def FromDict(cls, val):
1443 24a3707f Guido Trotter
    """Custom function for nodegroup.
1444 24a3707f Guido Trotter

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

1447 24a3707f Guido Trotter
    """
1448 24a3707f Guido Trotter
    obj = super(NodeGroup, cls).FromDict(val)
1449 24a3707f Guido Trotter
    obj.members = []
1450 24a3707f Guido Trotter
    return obj
1451 24a3707f Guido Trotter
1452 095e71aa Renรฉ Nussbaumer
  def UpgradeConfig(self):
1453 095e71aa Renรฉ Nussbaumer
    """Fill defaults for missing configuration values.
1454 095e71aa Renรฉ Nussbaumer

1455 095e71aa Renรฉ Nussbaumer
    """
1456 095e71aa Renรฉ Nussbaumer
    if self.ndparams is None:
1457 095e71aa Renรฉ Nussbaumer
      self.ndparams = {}
1458 095e71aa Renรฉ Nussbaumer
1459 e11a1b77 Adeodato Simo
    if self.serial_no is None:
1460 e11a1b77 Adeodato Simo
      self.serial_no = 1
1461 e11a1b77 Adeodato Simo
1462 90e99856 Adeodato Simo
    if self.alloc_policy is None:
1463 90e99856 Adeodato Simo
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1464 90e99856 Adeodato Simo
1465 4b97458c Iustin Pop
    # We only update mtime, and not ctime, since we would not be able
1466 4b97458c Iustin Pop
    # to provide a correct value for creation time.
1467 e11a1b77 Adeodato Simo
    if self.mtime is None:
1468 e11a1b77 Adeodato Simo
      self.mtime = time.time()
1469 e11a1b77 Adeodato Simo
1470 7228ca91 Renรฉ Nussbaumer
    if self.diskparams is None:
1471 7228ca91 Renรฉ Nussbaumer
      self.diskparams = {}
1472 81e3ab4f Agata Murawska
    if self.ipolicy is None:
1473 81e3ab4f Agata Murawska
      self.ipolicy = MakeEmptyIPolicy()
1474 bc5d0215 Andrea Spadaccini
1475 eaa4c57c Dimitris Aragiorgis
    if self.networks is None:
1476 eaa4c57c Dimitris Aragiorgis
      self.networks = {}
1477 eaa4c57c Dimitris Aragiorgis
1478 095e71aa Renรฉ Nussbaumer
  def FillND(self, node):
1479 ce523de1 Michael Hanselmann
    """Return filled out ndparams for L{objects.Node}
1480 095e71aa Renรฉ Nussbaumer

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

1485 095e71aa Renรฉ Nussbaumer
    """
1486 095e71aa Renรฉ Nussbaumer
    return self.SimpleFillND(node.ndparams)
1487 095e71aa Renรฉ Nussbaumer
1488 095e71aa Renรฉ Nussbaumer
  def SimpleFillND(self, ndparams):
1489 095e71aa Renรฉ Nussbaumer
    """Fill a given ndparams dict with defaults.
1490 095e71aa Renรฉ Nussbaumer

1491 095e71aa Renรฉ Nussbaumer
    @type ndparams: dict
1492 095e71aa Renรฉ Nussbaumer
    @param ndparams: the dict to fill
1493 095e71aa Renรฉ Nussbaumer
    @rtype: dict
1494 095e71aa Renรฉ Nussbaumer
    @return: a copy of the passed in ndparams with missing keys filled
1495 e6e88de6 Adeodato Simo
        from the node group defaults
1496 095e71aa Renรฉ Nussbaumer

1497 095e71aa Renรฉ Nussbaumer
    """
1498 095e71aa Renรฉ Nussbaumer
    return FillDict(self.ndparams, ndparams)
1499 095e71aa Renรฉ Nussbaumer
1500 24a3707f Guido Trotter
1501 ec29fe40 Iustin Pop
class Cluster(TaggableObject):
1502 a8083063 Iustin Pop
  """Config object representing the cluster."""
1503 154b9580 Balazs Lecz
  __slots__ = [
1504 a8083063 Iustin Pop
    "serial_no",
1505 a8083063 Iustin Pop
    "rsahostkeypub",
1506 a8083063 Iustin Pop
    "highest_used_port",
1507 b2fddf63 Iustin Pop
    "tcpudp_port_pool",
1508 a8083063 Iustin Pop
    "mac_prefix",
1509 a8083063 Iustin Pop
    "volume_group_name",
1510 999b183c Iustin Pop
    "reserved_lvs",
1511 9e33896b Luca Bigliardi
    "drbd_usermode_helper",
1512 a8083063 Iustin Pop
    "default_bridge",
1513 02691904 Alexander Schreiber
    "default_hypervisor",
1514 f6bd6e98 Michael Hanselmann
    "master_node",
1515 f6bd6e98 Michael Hanselmann
    "master_ip",
1516 f6bd6e98 Michael Hanselmann
    "master_netdev",
1517 5a8648eb Andrea Spadaccini
    "master_netmask",
1518 33be7576 Andrea Spadaccini
    "use_external_mip_script",
1519 f6bd6e98 Michael Hanselmann
    "cluster_name",
1520 f6bd6e98 Michael Hanselmann
    "file_storage_dir",
1521 4b97f902 Apollon Oikonomopoulos
    "shared_file_storage_dir",
1522 e69d05fd Iustin Pop
    "enabled_hypervisors",
1523 5bf7b5cf Iustin Pop
    "hvparams",
1524 918eb80b Agata Murawska
    "ipolicy",
1525 17463d22 Renรฉ Nussbaumer
    "os_hvp",
1526 5bf7b5cf Iustin Pop
    "beparams",
1527 1bdcbbab Iustin Pop
    "osparams",
1528 c8fcde47 Guido Trotter
    "nicparams",
1529 095e71aa Renรฉ Nussbaumer
    "ndparams",
1530 bc5d0215 Andrea Spadaccini
    "diskparams",
1531 4b7735f9 Iustin Pop
    "candidate_pool_size",
1532 b86a6bcd Guido Trotter
    "modify_etc_hosts",
1533 b989b9d9 Ken Wehr
    "modify_ssh_setup",
1534 3953242f Iustin Pop
    "maintain_node_health",
1535 4437d889 Balazs Lecz
    "uid_pool",
1536 bf4af505 Apollon Oikonomopoulos
    "default_iallocator",
1537 87b2cd45 Iustin Pop
    "hidden_os",
1538 87b2cd45 Iustin Pop
    "blacklisted_os",
1539 2f20d07b Manuel Franceschini
    "primary_ip_family",
1540 3d914585 Renรฉ Nussbaumer
    "prealloc_wipe_disks",
1541 2da9f556 Renรฉ Nussbaumer
    "hv_state_static",
1542 2da9f556 Renรฉ Nussbaumer
    "disk_state_static",
1543 d0de443e Helga Velroyen
    "enabled_storage_types",
1544 e1dcc53a Iustin Pop
    ] + _TIMESTAMPS + _UUID
1545 a8083063 Iustin Pop
1546 b86a6bcd Guido Trotter
  def UpgradeConfig(self):
1547 b86a6bcd Guido Trotter
    """Fill defaults for missing configuration values.
1548 b86a6bcd Guido Trotter

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

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

1665 0fbedb7a Michael Hanselmann
    """
1666 0fbedb7a Michael Hanselmann
    return self.enabled_hypervisors[0]
1667 0fbedb7a Michael Hanselmann
1668 319856a9 Michael Hanselmann
  def ToDict(self):
1669 319856a9 Michael Hanselmann
    """Custom function for cluster.
1670 319856a9 Michael Hanselmann

1671 319856a9 Michael Hanselmann
    """
1672 b60ae2ca Iustin Pop
    mydict = super(Cluster, self).ToDict()
1673 4d36fbf4 Michael Hanselmann
1674 4d36fbf4 Michael Hanselmann
    if self.tcpudp_port_pool is None:
1675 4d36fbf4 Michael Hanselmann
      tcpudp_port_pool = []
1676 4d36fbf4 Michael Hanselmann
    else:
1677 4d36fbf4 Michael Hanselmann
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1678 4d36fbf4 Michael Hanselmann
1679 4d36fbf4 Michael Hanselmann
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1680 4d36fbf4 Michael Hanselmann
1681 319856a9 Michael Hanselmann
    return mydict
1682 319856a9 Michael Hanselmann
1683 319856a9 Michael Hanselmann
  @classmethod
1684 319856a9 Michael Hanselmann
  def FromDict(cls, val):
1685 319856a9 Michael Hanselmann
    """Custom function for cluster.
1686 319856a9 Michael Hanselmann

1687 319856a9 Michael Hanselmann
    """
1688 b60ae2ca Iustin Pop
    obj = super(Cluster, cls).FromDict(val)
1689 4d36fbf4 Michael Hanselmann
1690 4d36fbf4 Michael Hanselmann
    if obj.tcpudp_port_pool is None:
1691 4d36fbf4 Michael Hanselmann
      obj.tcpudp_port_pool = set()
1692 4d36fbf4 Michael Hanselmann
    elif not isinstance(obj.tcpudp_port_pool, set):
1693 319856a9 Michael Hanselmann
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1694 4d36fbf4 Michael Hanselmann
1695 319856a9 Michael Hanselmann
    return obj
1696 319856a9 Michael Hanselmann
1697 8a147bba Renรฉ Nussbaumer
  def SimpleFillDP(self, diskparams):
1698 8a147bba Renรฉ Nussbaumer
    """Fill a given diskparams dict with cluster defaults.
1699 8a147bba Renรฉ Nussbaumer

1700 8a147bba Renรฉ Nussbaumer
    @param diskparams: The diskparams
1701 8a147bba Renรฉ Nussbaumer
    @return: The defaults dict
1702 8a147bba Renรฉ Nussbaumer

1703 8a147bba Renรฉ Nussbaumer
    """
1704 8a147bba Renรฉ Nussbaumer
    return FillDiskParams(self.diskparams, diskparams)
1705 8a147bba Renรฉ Nussbaumer
1706 d63479b5 Iustin Pop
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1707 d63479b5 Iustin Pop
    """Get the default hypervisor parameters for the cluster.
1708 d63479b5 Iustin Pop

1709 d63479b5 Iustin Pop
    @param hypervisor: the hypervisor name
1710 d63479b5 Iustin Pop
    @param os_name: if specified, we'll also update the defaults for this OS
1711 d63479b5 Iustin Pop
    @param skip_keys: if passed, list of keys not to use
1712 d63479b5 Iustin Pop
    @return: the defaults dict
1713 d63479b5 Iustin Pop

1714 d63479b5 Iustin Pop
    """
1715 d63479b5 Iustin Pop
    if skip_keys is None:
1716 d63479b5 Iustin Pop
      skip_keys = []
1717 d63479b5 Iustin Pop
1718 d63479b5 Iustin Pop
    fill_stack = [self.hvparams.get(hypervisor, {})]
1719 d63479b5 Iustin Pop
    if os_name is not None:
1720 d63479b5 Iustin Pop
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1721 d63479b5 Iustin Pop
      fill_stack.append(os_hvp)
1722 d63479b5 Iustin Pop
1723 d63479b5 Iustin Pop
    ret_dict = {}
1724 d63479b5 Iustin Pop
    for o_dict in fill_stack:
1725 d63479b5 Iustin Pop
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1726 d63479b5 Iustin Pop
1727 d63479b5 Iustin Pop
    return ret_dict
1728 d63479b5 Iustin Pop
1729 73e0328b Iustin Pop
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1730 73e0328b Iustin Pop
    """Fill a given hvparams dict with cluster defaults.
1731 73e0328b Iustin Pop

1732 73e0328b Iustin Pop
    @type hv_name: string
1733 73e0328b Iustin Pop
    @param hv_name: the hypervisor to use
1734 73e0328b Iustin Pop
    @type os_name: string
1735 73e0328b Iustin Pop
    @param os_name: the OS to use for overriding the hypervisor defaults
1736 73e0328b Iustin Pop
    @type skip_globals: boolean
1737 73e0328b Iustin Pop
    @param skip_globals: if True, the global hypervisor parameters will
1738 73e0328b Iustin Pop
        not be filled
1739 73e0328b Iustin Pop
    @rtype: dict
1740 73e0328b Iustin Pop
    @return: a copy of the given hvparams with missing keys filled from
1741 73e0328b Iustin Pop
        the cluster defaults
1742 73e0328b Iustin Pop

1743 73e0328b Iustin Pop
    """
1744 73e0328b Iustin Pop
    if skip_globals:
1745 73e0328b Iustin Pop
      skip_keys = constants.HVC_GLOBALS
1746 73e0328b Iustin Pop
    else:
1747 73e0328b Iustin Pop
      skip_keys = []
1748 73e0328b Iustin Pop
1749 73e0328b Iustin Pop
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1750 73e0328b Iustin Pop
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1751 d63479b5 Iustin Pop
1752 7736a5f2 Iustin Pop
  def FillHV(self, instance, skip_globals=False):
1753 73e0328b Iustin Pop
    """Fill an instance's hvparams dict with cluster defaults.
1754 5bf7b5cf Iustin Pop

1755 a2a24f4c Guido Trotter
    @type instance: L{objects.Instance}
1756 5bf7b5cf Iustin Pop
    @param instance: the instance parameter to fill
1757 7736a5f2 Iustin Pop
    @type skip_globals: boolean
1758 7736a5f2 Iustin Pop
    @param skip_globals: if True, the global hypervisor parameters will
1759 7736a5f2 Iustin Pop
        not be filled
1760 5bf7b5cf Iustin Pop
    @rtype: dict
1761 5bf7b5cf Iustin Pop
    @return: a copy of the instance's hvparams with missing keys filled from
1762 5bf7b5cf Iustin Pop
        the cluster defaults
1763 5bf7b5cf Iustin Pop

1764 5bf7b5cf Iustin Pop
    """
1765 73e0328b Iustin Pop
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1766 73e0328b Iustin Pop
                             instance.hvparams, skip_globals)
1767 17463d22 Renรฉ Nussbaumer
1768 73e0328b Iustin Pop
  def SimpleFillBE(self, beparams):
1769 73e0328b Iustin Pop
    """Fill a given beparams dict with cluster defaults.
1770 73e0328b Iustin Pop

1771 06596a60 Guido Trotter
    @type beparams: dict
1772 06596a60 Guido Trotter
    @param beparams: the dict to fill
1773 73e0328b Iustin Pop
    @rtype: dict
1774 73e0328b Iustin Pop
    @return: a copy of the passed in beparams with missing keys filled
1775 73e0328b Iustin Pop
        from the cluster defaults
1776 73e0328b Iustin Pop

1777 73e0328b Iustin Pop
    """
1778 73e0328b Iustin Pop
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1779 5bf7b5cf Iustin Pop
1780 5bf7b5cf Iustin Pop
  def FillBE(self, instance):
1781 73e0328b Iustin Pop
    """Fill an instance's beparams dict with cluster defaults.
1782 5bf7b5cf Iustin Pop

1783 a2a24f4c Guido Trotter
    @type instance: L{objects.Instance}
1784 5bf7b5cf Iustin Pop
    @param instance: the instance parameter to fill
1785 5bf7b5cf Iustin Pop
    @rtype: dict
1786 5bf7b5cf Iustin Pop
    @return: a copy of the instance's beparams with missing keys filled from
1787 5bf7b5cf Iustin Pop
        the cluster defaults
1788 5bf7b5cf Iustin Pop

1789 5bf7b5cf Iustin Pop
    """
1790 73e0328b Iustin Pop
    return self.SimpleFillBE(instance.beparams)
1791 73e0328b Iustin Pop
1792 73e0328b Iustin Pop
  def SimpleFillNIC(self, nicparams):
1793 73e0328b Iustin Pop
    """Fill a given nicparams dict with cluster defaults.
1794 73e0328b Iustin Pop

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

1801 73e0328b Iustin Pop
    """
1802 73e0328b Iustin Pop
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1803 5bf7b5cf Iustin Pop
1804 1bdcbbab Iustin Pop
  def SimpleFillOS(self, os_name, os_params):
1805 1bdcbbab Iustin Pop
    """Fill an instance's osparams dict with cluster defaults.
1806 1bdcbbab Iustin Pop

1807 1bdcbbab Iustin Pop
    @type os_name: string
1808 1bdcbbab Iustin Pop
    @param os_name: the OS name to use
1809 1bdcbbab Iustin Pop
    @type os_params: dict
1810 1bdcbbab Iustin Pop
    @param os_params: the dict to fill with default values
1811 1bdcbbab Iustin Pop
    @rtype: dict
1812 1bdcbbab Iustin Pop
    @return: a copy of the instance's osparams with missing keys filled from
1813 1bdcbbab Iustin Pop
        the cluster defaults
1814 1bdcbbab Iustin Pop

1815 1bdcbbab Iustin Pop
    """
1816 1bdcbbab Iustin Pop
    name_only = os_name.split("+", 1)[0]
1817 1bdcbbab Iustin Pop
    # base OS
1818 1bdcbbab Iustin Pop
    result = self.osparams.get(name_only, {})
1819 1bdcbbab Iustin Pop
    # OS with variant
1820 1bdcbbab Iustin Pop
    result = FillDict(result, self.osparams.get(os_name, {}))
1821 1bdcbbab Iustin Pop
    # specified params
1822 1bdcbbab Iustin Pop
    return FillDict(result, os_params)
1823 1bdcbbab Iustin Pop
1824 2da9f556 Renรฉ Nussbaumer
  @staticmethod
1825 2da9f556 Renรฉ Nussbaumer
  def SimpleFillHvState(hv_state):
1826 2da9f556 Renรฉ Nussbaumer
    """Fill an hv_state sub dict with cluster defaults.
1827 2da9f556 Renรฉ Nussbaumer

1828 2da9f556 Renรฉ Nussbaumer
    """
1829 2da9f556 Renรฉ Nussbaumer
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1830 2da9f556 Renรฉ Nussbaumer
1831 2da9f556 Renรฉ Nussbaumer
  @staticmethod
1832 2da9f556 Renรฉ Nussbaumer
  def SimpleFillDiskState(disk_state):
1833 2da9f556 Renรฉ Nussbaumer
    """Fill an disk_state sub dict with cluster defaults.
1834 2da9f556 Renรฉ Nussbaumer

1835 2da9f556 Renรฉ Nussbaumer
    """
1836 2da9f556 Renรฉ Nussbaumer
    return FillDict(constants.DS_DEFAULTS, disk_state)
1837 2da9f556 Renรฉ Nussbaumer
1838 095e71aa Renรฉ Nussbaumer
  def FillND(self, node, nodegroup):
1839 ce523de1 Michael Hanselmann
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1840 095e71aa Renรฉ Nussbaumer

1841 095e71aa Renรฉ Nussbaumer
    @type node: L{objects.Node}
1842 095e71aa Renรฉ Nussbaumer
    @param node: A Node object to fill
1843 095e71aa Renรฉ Nussbaumer
    @type nodegroup: L{objects.NodeGroup}
1844 095e71aa Renรฉ Nussbaumer
    @param nodegroup: A Node object to fill
1845 095e71aa Renรฉ Nussbaumer
    @return a copy of the node's ndparams with defaults filled
1846 095e71aa Renรฉ Nussbaumer

1847 095e71aa Renรฉ Nussbaumer
    """
1848 095e71aa Renรฉ Nussbaumer
    return self.SimpleFillND(nodegroup.FillND(node))
1849 095e71aa Renรฉ Nussbaumer
1850 095e71aa Renรฉ Nussbaumer
  def SimpleFillND(self, ndparams):
1851 095e71aa Renรฉ Nussbaumer
    """Fill a given ndparams dict with defaults.
1852 095e71aa Renรฉ Nussbaumer

1853 095e71aa Renรฉ Nussbaumer
    @type ndparams: dict
1854 095e71aa Renรฉ Nussbaumer
    @param ndparams: the dict to fill
1855 095e71aa Renรฉ Nussbaumer
    @rtype: dict
1856 095e71aa Renรฉ Nussbaumer
    @return: a copy of the passed in ndparams with missing keys filled
1857 095e71aa Renรฉ Nussbaumer
        from the cluster defaults
1858 095e71aa Renรฉ Nussbaumer

1859 095e71aa Renรฉ Nussbaumer
    """
1860 095e71aa Renรฉ Nussbaumer
    return FillDict(self.ndparams, ndparams)
1861 095e71aa Renรฉ Nussbaumer
1862 918eb80b Agata Murawska
  def SimpleFillIPolicy(self, ipolicy):
1863 918eb80b Agata Murawska
    """ Fill instance policy dict with defaults.
1864 918eb80b Agata Murawska

1865 918eb80b Agata Murawska
    @type ipolicy: dict
1866 918eb80b Agata Murawska
    @param ipolicy: the dict to fill
1867 918eb80b Agata Murawska
    @rtype: dict
1868 918eb80b Agata Murawska
    @return: a copy of passed ipolicy with missing keys filled from
1869 918eb80b Agata Murawska
      the cluster defaults
1870 918eb80b Agata Murawska

1871 918eb80b Agata Murawska
    """
1872 2cc673a3 Iustin Pop
    return FillIPolicy(self.ipolicy, ipolicy)
1873 918eb80b Agata Murawska
1874 5c947f38 Iustin Pop
1875 96acbc09 Michael Hanselmann
class BlockDevStatus(ConfigObject):
1876 96acbc09 Michael Hanselmann
  """Config object representing the status of a block device."""
1877 96acbc09 Michael Hanselmann
  __slots__ = [
1878 96acbc09 Michael Hanselmann
    "dev_path",
1879 96acbc09 Michael Hanselmann
    "major",
1880 96acbc09 Michael Hanselmann
    "minor",
1881 96acbc09 Michael Hanselmann
    "sync_percent",
1882 96acbc09 Michael Hanselmann
    "estimated_time",
1883 96acbc09 Michael Hanselmann
    "is_degraded",
1884 f208978a Michael Hanselmann
    "ldisk_status",
1885 96acbc09 Michael Hanselmann
    ]
1886 96acbc09 Michael Hanselmann
1887 96acbc09 Michael Hanselmann
1888 2d76b580 Michael Hanselmann
class ImportExportStatus(ConfigObject):
1889 2d76b580 Michael Hanselmann
  """Config object representing the status of an import or export."""
1890 2d76b580 Michael Hanselmann
  __slots__ = [
1891 2d76b580 Michael Hanselmann
    "recent_output",
1892 2d76b580 Michael Hanselmann
    "listen_port",
1893 2d76b580 Michael Hanselmann
    "connected",
1894 c08d76f5 Michael Hanselmann
    "progress_mbytes",
1895 c08d76f5 Michael Hanselmann
    "progress_throughput",
1896 c08d76f5 Michael Hanselmann
    "progress_eta",
1897 c08d76f5 Michael Hanselmann
    "progress_percent",
1898 2d76b580 Michael Hanselmann
    "exit_status",
1899 2d76b580 Michael Hanselmann
    "error_message",
1900 2d76b580 Michael Hanselmann
    ] + _TIMESTAMPS
1901 2d76b580 Michael Hanselmann
1902 2d76b580 Michael Hanselmann
1903 eb630f50 Michael Hanselmann
class ImportExportOptions(ConfigObject):
1904 eb630f50 Michael Hanselmann
  """Options for import/export daemon
1905 eb630f50 Michael Hanselmann

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

1913 eb630f50 Michael Hanselmann
  """
1914 eb630f50 Michael Hanselmann
  __slots__ = [
1915 eb630f50 Michael Hanselmann
    "key_name",
1916 eb630f50 Michael Hanselmann
    "ca_pem",
1917 a5310c2a Michael Hanselmann
    "compress",
1918 af1d39b1 Michael Hanselmann
    "magic",
1919 855d2fc7 Michael Hanselmann
    "ipv6",
1920 4478301b Michael Hanselmann
    "connect_timeout",
1921 eb630f50 Michael Hanselmann
    ]
1922 eb630f50 Michael Hanselmann
1923 eb630f50 Michael Hanselmann
1924 18d750b9 Guido Trotter
class ConfdRequest(ConfigObject):
1925 18d750b9 Guido Trotter
  """Object holding a confd request.
1926 18d750b9 Guido Trotter

1927 18d750b9 Guido Trotter
  @ivar protocol: confd protocol version
1928 18d750b9 Guido Trotter
  @ivar type: confd query type
1929 18d750b9 Guido Trotter
  @ivar query: query request
1930 18d750b9 Guido Trotter
  @ivar rsalt: requested reply salt
1931 18d750b9 Guido Trotter

1932 18d750b9 Guido Trotter
  """
1933 18d750b9 Guido Trotter
  __slots__ = [
1934 18d750b9 Guido Trotter
    "protocol",
1935 18d750b9 Guido Trotter
    "type",
1936 18d750b9 Guido Trotter
    "query",
1937 18d750b9 Guido Trotter
    "rsalt",
1938 18d750b9 Guido Trotter
    ]
1939 18d750b9 Guido Trotter
1940 18d750b9 Guido Trotter
1941 18d750b9 Guido Trotter
class ConfdReply(ConfigObject):
1942 18d750b9 Guido Trotter
  """Object holding a confd reply.
1943 18d750b9 Guido Trotter

1944 18d750b9 Guido Trotter
  @ivar protocol: confd protocol version
1945 18d750b9 Guido Trotter
  @ivar status: reply status code (ok, error)
1946 18d750b9 Guido Trotter
  @ivar answer: confd query reply
1947 18d750b9 Guido Trotter
  @ivar serial: configuration serial number
1948 18d750b9 Guido Trotter

1949 18d750b9 Guido Trotter
  """
1950 18d750b9 Guido Trotter
  __slots__ = [
1951 18d750b9 Guido Trotter
    "protocol",
1952 18d750b9 Guido Trotter
    "status",
1953 18d750b9 Guido Trotter
    "answer",
1954 18d750b9 Guido Trotter
    "serial",
1955 18d750b9 Guido Trotter
    ]
1956 18d750b9 Guido Trotter
1957 18d750b9 Guido Trotter
1958 707f23b5 Michael Hanselmann
class QueryFieldDefinition(ConfigObject):
1959 707f23b5 Michael Hanselmann
  """Object holding a query field definition.
1960 707f23b5 Michael Hanselmann

1961 24d6d3e2 Michael Hanselmann
  @ivar name: Field name
1962 707f23b5 Michael Hanselmann
  @ivar title: Human-readable title
1963 707f23b5 Michael Hanselmann
  @ivar kind: Field type
1964 1ae17369 Michael Hanselmann
  @ivar doc: Human-readable description
1965 707f23b5 Michael Hanselmann

1966 707f23b5 Michael Hanselmann
  """
1967 707f23b5 Michael Hanselmann
  __slots__ = [
1968 707f23b5 Michael Hanselmann
    "name",
1969 707f23b5 Michael Hanselmann
    "title",
1970 707f23b5 Michael Hanselmann
    "kind",
1971 1ae17369 Michael Hanselmann
    "doc",
1972 707f23b5 Michael Hanselmann
    ]
1973 707f23b5 Michael Hanselmann
1974 707f23b5 Michael Hanselmann
1975 0538c375 Michael Hanselmann
class _QueryResponseBase(ConfigObject):
1976 0538c375 Michael Hanselmann
  __slots__ = [
1977 0538c375 Michael Hanselmann
    "fields",
1978 0538c375 Michael Hanselmann
    ]
1979 0538c375 Michael Hanselmann
1980 0538c375 Michael Hanselmann
  def ToDict(self):
1981 0538c375 Michael Hanselmann
    """Custom function for serializing.
1982 0538c375 Michael Hanselmann

1983 0538c375 Michael Hanselmann
    """
1984 0538c375 Michael Hanselmann
    mydict = super(_QueryResponseBase, self).ToDict()
1985 fe502d25 Iustin Pop
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
1986 0538c375 Michael Hanselmann
    return mydict
1987 0538c375 Michael Hanselmann
1988 0538c375 Michael Hanselmann
  @classmethod
1989 0538c375 Michael Hanselmann
  def FromDict(cls, val):
1990 0538c375 Michael Hanselmann
    """Custom function for de-serializing.
1991 0538c375 Michael Hanselmann

1992 0538c375 Michael Hanselmann
    """
1993 0538c375 Michael Hanselmann
    obj = super(_QueryResponseBase, cls).FromDict(val)
1994 473ab806 Michael Hanselmann
    obj.fields = \
1995 fe502d25 Iustin Pop
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
1996 0538c375 Michael Hanselmann
    return obj
1997 0538c375 Michael Hanselmann
1998 0538c375 Michael Hanselmann
1999 0538c375 Michael Hanselmann
class QueryResponse(_QueryResponseBase):
2000 24d6d3e2 Michael Hanselmann
  """Object holding the response to a query.
2001 24d6d3e2 Michael Hanselmann

2002 24d6d3e2 Michael Hanselmann
  @ivar fields: List of L{QueryFieldDefinition} objects
2003 24d6d3e2 Michael Hanselmann
  @ivar data: Requested data
2004 24d6d3e2 Michael Hanselmann

2005 24d6d3e2 Michael Hanselmann
  """
2006 24d6d3e2 Michael Hanselmann
  __slots__ = [
2007 24d6d3e2 Michael Hanselmann
    "data",
2008 24d6d3e2 Michael Hanselmann
    ]
2009 24d6d3e2 Michael Hanselmann
2010 24d6d3e2 Michael Hanselmann
2011 24d6d3e2 Michael Hanselmann
class QueryFieldsRequest(ConfigObject):
2012 24d6d3e2 Michael Hanselmann
  """Object holding a request for querying available fields.
2013 24d6d3e2 Michael Hanselmann

2014 24d6d3e2 Michael Hanselmann
  """
2015 24d6d3e2 Michael Hanselmann
  __slots__ = [
2016 24d6d3e2 Michael Hanselmann
    "what",
2017 24d6d3e2 Michael Hanselmann
    "fields",
2018 24d6d3e2 Michael Hanselmann
    ]
2019 24d6d3e2 Michael Hanselmann
2020 24d6d3e2 Michael Hanselmann
2021 0538c375 Michael Hanselmann
class QueryFieldsResponse(_QueryResponseBase):
2022 24d6d3e2 Michael Hanselmann
  """Object holding the response to a query for fields.
2023 24d6d3e2 Michael Hanselmann

2024 24d6d3e2 Michael Hanselmann
  @ivar fields: List of L{QueryFieldDefinition} objects
2025 24d6d3e2 Michael Hanselmann

2026 24d6d3e2 Michael Hanselmann
  """
2027 5ae4945a Iustin Pop
  __slots__ = []
2028 24d6d3e2 Michael Hanselmann
2029 24d6d3e2 Michael Hanselmann
2030 6a1434d7 Andrea Spadaccini
class MigrationStatus(ConfigObject):
2031 6a1434d7 Andrea Spadaccini
  """Object holding the status of a migration.
2032 6a1434d7 Andrea Spadaccini

2033 6a1434d7 Andrea Spadaccini
  """
2034 6a1434d7 Andrea Spadaccini
  __slots__ = [
2035 6a1434d7 Andrea Spadaccini
    "status",
2036 6a1434d7 Andrea Spadaccini
    "transferred_ram",
2037 6a1434d7 Andrea Spadaccini
    "total_ram",
2038 6a1434d7 Andrea Spadaccini
    ]
2039 6a1434d7 Andrea Spadaccini
2040 6a1434d7 Andrea Spadaccini
2041 25ce3ec4 Michael Hanselmann
class InstanceConsole(ConfigObject):
2042 25ce3ec4 Michael Hanselmann
  """Object describing how to access the console of an instance.
2043 25ce3ec4 Michael Hanselmann

2044 25ce3ec4 Michael Hanselmann
  """
2045 25ce3ec4 Michael Hanselmann
  __slots__ = [
2046 25ce3ec4 Michael Hanselmann
    "instance",
2047 25ce3ec4 Michael Hanselmann
    "kind",
2048 25ce3ec4 Michael Hanselmann
    "message",
2049 25ce3ec4 Michael Hanselmann
    "host",
2050 25ce3ec4 Michael Hanselmann
    "port",
2051 25ce3ec4 Michael Hanselmann
    "user",
2052 25ce3ec4 Michael Hanselmann
    "command",
2053 25ce3ec4 Michael Hanselmann
    "display",
2054 25ce3ec4 Michael Hanselmann
    ]
2055 25ce3ec4 Michael Hanselmann
2056 25ce3ec4 Michael Hanselmann
  def Validate(self):
2057 25ce3ec4 Michael Hanselmann
    """Validates contents of this object.
2058 25ce3ec4 Michael Hanselmann

2059 25ce3ec4 Michael Hanselmann
    """
2060 25ce3ec4 Michael Hanselmann
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2061 25ce3ec4 Michael Hanselmann
    assert self.instance, "Missing instance name"
2062 4d2cdb5a Andrea Spadaccini
    assert self.message or self.kind in [constants.CONS_SSH,
2063 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2064 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_VNC]
2065 25ce3ec4 Michael Hanselmann
    assert self.host or self.kind == constants.CONS_MESSAGE
2066 25ce3ec4 Michael Hanselmann
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2067 25ce3ec4 Michael Hanselmann
                                      constants.CONS_SSH]
2068 25ce3ec4 Michael Hanselmann
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2069 4d2cdb5a Andrea Spadaccini
                                      constants.CONS_SPICE,
2070 25ce3ec4 Michael Hanselmann
                                      constants.CONS_VNC]
2071 25ce3ec4 Michael Hanselmann
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2072 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2073 25ce3ec4 Michael Hanselmann
                                         constants.CONS_VNC]
2074 25ce3ec4 Michael Hanselmann
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2075 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2076 25ce3ec4 Michael Hanselmann
                                         constants.CONS_SSH]
2077 25ce3ec4 Michael Hanselmann
    return True
2078 25ce3ec4 Michael Hanselmann
2079 25ce3ec4 Michael Hanselmann
2080 8140e24f Dimitris Aragiorgis
class Network(TaggableObject):
2081 eaa4c57c Dimitris Aragiorgis
  """Object representing a network definition for ganeti.
2082 eaa4c57c Dimitris Aragiorgis

2083 eaa4c57c Dimitris Aragiorgis
  """
2084 eaa4c57c Dimitris Aragiorgis
  __slots__ = [
2085 eaa4c57c Dimitris Aragiorgis
    "name",
2086 eaa4c57c Dimitris Aragiorgis
    "serial_no",
2087 eaa4c57c Dimitris Aragiorgis
    "mac_prefix",
2088 eaa4c57c Dimitris Aragiorgis
    "network",
2089 eaa4c57c Dimitris Aragiorgis
    "network6",
2090 eaa4c57c Dimitris Aragiorgis
    "gateway",
2091 eaa4c57c Dimitris Aragiorgis
    "gateway6",
2092 eaa4c57c Dimitris Aragiorgis
    "reservations",
2093 eaa4c57c Dimitris Aragiorgis
    "ext_reservations",
2094 eaa4c57c Dimitris Aragiorgis
    ] + _TIMESTAMPS + _UUID
2095 eaa4c57c Dimitris Aragiorgis
2096 7e8f03e3 Dimitris Aragiorgis
  def HooksDict(self, prefix=""):
2097 d89168ff Guido Trotter
    """Export a dictionary used by hooks with a network's information.
2098 d89168ff Guido Trotter

2099 d89168ff Guido Trotter
    @type prefix: String
2100 d89168ff Guido Trotter
    @param prefix: Prefix to prepend to the dict entries
2101 d89168ff Guido Trotter

2102 d89168ff Guido Trotter
    """
2103 d89168ff Guido Trotter
    result = {
2104 7e8f03e3 Dimitris Aragiorgis
      "%sNETWORK_NAME" % prefix: self.name,
2105 d89168ff Guido Trotter
      "%sNETWORK_UUID" % prefix: self.uuid,
2106 5a76adf7 Dimitris Aragiorgis
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2107 d89168ff Guido Trotter
    }
2108 d89168ff Guido Trotter
    if self.network:
2109 d89168ff Guido Trotter
      result["%sNETWORK_SUBNET" % prefix] = self.network
2110 d89168ff Guido Trotter
    if self.gateway:
2111 d89168ff Guido Trotter
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2112 d89168ff Guido Trotter
    if self.network6:
2113 d89168ff Guido Trotter
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2114 d89168ff Guido Trotter
    if self.gateway6:
2115 d89168ff Guido Trotter
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2116 d89168ff Guido Trotter
    if self.mac_prefix:
2117 d89168ff Guido Trotter
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2118 d89168ff Guido Trotter
2119 d89168ff Guido Trotter
    return result
2120 d89168ff Guido Trotter
2121 5cfa6c37 Dimitris Aragiorgis
  @classmethod
2122 5cfa6c37 Dimitris Aragiorgis
  def FromDict(cls, val):
2123 5cfa6c37 Dimitris Aragiorgis
    """Custom function for networks.
2124 5cfa6c37 Dimitris Aragiorgis

2125 48616625 Dimitris Aragiorgis
    Remove deprecated network_type and family.
2126 5cfa6c37 Dimitris Aragiorgis

2127 5cfa6c37 Dimitris Aragiorgis
    """
2128 5cfa6c37 Dimitris Aragiorgis
    if "network_type" in val:
2129 5cfa6c37 Dimitris Aragiorgis
      del val["network_type"]
2130 48616625 Dimitris Aragiorgis
    if "family" in val:
2131 48616625 Dimitris Aragiorgis
      del val["family"]
2132 5cfa6c37 Dimitris Aragiorgis
    obj = super(Network, cls).FromDict(val)
2133 5cfa6c37 Dimitris Aragiorgis
    return obj
2134 5cfa6c37 Dimitris Aragiorgis
2135 eaa4c57c Dimitris Aragiorgis
2136 a8083063 Iustin Pop
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2137 a8083063 Iustin Pop
  """Simple wrapper over ConfigParse that allows serialization.
2138 a8083063 Iustin Pop

2139 a8083063 Iustin Pop
  This class is basically ConfigParser.SafeConfigParser with two
2140 a8083063 Iustin Pop
  additional methods that allow it to serialize/unserialize to/from a
2141 a8083063 Iustin Pop
  buffer.
2142 a8083063 Iustin Pop

2143 a8083063 Iustin Pop
  """
2144 a8083063 Iustin Pop
  def Dumps(self):
2145 a8083063 Iustin Pop
    """Dump this instance and return the string representation."""
2146 a8083063 Iustin Pop
    buf = StringIO()
2147 a8083063 Iustin Pop
    self.write(buf)
2148 a8083063 Iustin Pop
    return buf.getvalue()
2149 a8083063 Iustin Pop
2150 b39bf4bb Guido Trotter
  @classmethod
2151 b39bf4bb Guido Trotter
  def Loads(cls, data):
2152 a8083063 Iustin Pop
    """Load data from a string."""
2153 a8083063 Iustin Pop
    buf = StringIO(data)
2154 b39bf4bb Guido Trotter
    cfp = cls()
2155 a8083063 Iustin Pop
    cfp.readfp(buf)
2156 a8083063 Iustin Pop
    return cfp
2157 59726e15 Bernardo Dal Seno
2158 59726e15 Bernardo Dal Seno
2159 59726e15 Bernardo Dal Seno
class LvmPvInfo(ConfigObject):
2160 59726e15 Bernardo Dal Seno
  """Information about an LVM physical volume (PV).
2161 59726e15 Bernardo Dal Seno

2162 59726e15 Bernardo Dal Seno
  @type name: string
2163 59726e15 Bernardo Dal Seno
  @ivar name: name of the PV
2164 59726e15 Bernardo Dal Seno
  @type vg_name: string
2165 59726e15 Bernardo Dal Seno
  @ivar vg_name: name of the volume group containing the PV
2166 59726e15 Bernardo Dal Seno
  @type size: float
2167 59726e15 Bernardo Dal Seno
  @ivar size: size of the PV in MiB
2168 59726e15 Bernardo Dal Seno
  @type free: float
2169 59726e15 Bernardo Dal Seno
  @ivar free: free space in the PV, in MiB
2170 59726e15 Bernardo Dal Seno
  @type attributes: string
2171 59726e15 Bernardo Dal Seno
  @ivar attributes: PV attributes
2172 b496abdb Bernardo Dal Seno
  @type lv_list: list of strings
2173 b496abdb Bernardo Dal Seno
  @ivar lv_list: names of the LVs hosted on the PV
2174 59726e15 Bernardo Dal Seno
  """
2175 59726e15 Bernardo Dal Seno
  __slots__ = [
2176 59726e15 Bernardo Dal Seno
    "name",
2177 59726e15 Bernardo Dal Seno
    "vg_name",
2178 59726e15 Bernardo Dal Seno
    "size",
2179 59726e15 Bernardo Dal Seno
    "free",
2180 59726e15 Bernardo Dal Seno
    "attributes",
2181 b496abdb Bernardo Dal Seno
    "lv_list"
2182 59726e15 Bernardo Dal Seno
    ]
2183 59726e15 Bernardo Dal Seno
2184 59726e15 Bernardo Dal Seno
  def IsEmpty(self):
2185 59726e15 Bernardo Dal Seno
    """Is this PV empty?
2186 59726e15 Bernardo Dal Seno

2187 59726e15 Bernardo Dal Seno
    """
2188 59726e15 Bernardo Dal Seno
    return self.size <= (self.free + 1)
2189 59726e15 Bernardo Dal Seno
2190 59726e15 Bernardo Dal Seno
  def IsAllocatable(self):
2191 59726e15 Bernardo Dal Seno
    """Is this PV allocatable?
2192 59726e15 Bernardo Dal Seno

2193 59726e15 Bernardo Dal Seno
    """
2194 59726e15 Bernardo Dal Seno
    return ("a" in self.attributes)