Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 2ef21e6e

History | View | Annotate | Download (62.8 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 1b02d7ef Helga Velroyen
    self._UpgradeEnabledDiskTemplates()
481 c66d8987 Helga Velroyen
482 1b02d7ef Helga Velroyen
  def _UpgradeEnabledDiskTemplates(self):
483 1b02d7ef Helga Velroyen
    """Upgrade the cluster's enabled disk templates by inspecting the currently
484 1b02d7ef Helga Velroyen
       enabled and/or used disk templates.
485 c66d8987 Helga Velroyen

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1701 8a147bba René Nussbaumer
    @param diskparams: The diskparams
1702 8a147bba René Nussbaumer
    @return: The defaults dict
1703 8a147bba René Nussbaumer

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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