Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 178ad717

History | View | Annotate | Download (65.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 e4236bbd Santi Raffa
      if k in ret_dict:
79 e11ddf13 Iustin Pop
        del ret_dict[k]
80 29921401 Iustin Pop
  return ret_dict
81 a8083063 Iustin Pop
82 6e34b628 Guido Trotter
83 da5f09ef Bernardo Dal Seno
def FillIPolicy(default_ipolicy, custom_ipolicy):
84 2cc673a3 Iustin Pop
  """Fills an instance policy with defaults.
85 918eb80b Agata Murawska

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

214 adf385c7 Iustin Pop
    """
215 415feb2e Renรฉ Nussbaumer
216 ff9c047c Iustin Pop
  def ToDict(self):
217 ff9c047c Iustin Pop
    """Convert to a dict holding only standard python types.
218 ff9c047c Iustin Pop

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

225 ff9c047c Iustin Pop
    """
226 4c14965f Guido Trotter
    result = {}
227 32683096 Renรฉ Nussbaumer
    for name in self.GetAllSlots():
228 4c14965f Guido Trotter
      value = getattr(self, name, None)
229 4c14965f Guido Trotter
      if value is not None:
230 4c14965f Guido Trotter
        result[name] = value
231 4c14965f Guido Trotter
    return result
232 4c14965f Guido Trotter
233 4c14965f Guido Trotter
  __getstate__ = ToDict
234 ff9c047c Iustin Pop
235 ff9c047c Iustin Pop
  @classmethod
236 ff9c047c Iustin Pop
  def FromDict(cls, val):
237 ff9c047c Iustin Pop
    """Create an object from a dictionary.
238 ff9c047c Iustin Pop

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

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

247 ff9c047c Iustin Pop
    """
248 ff9c047c Iustin Pop
    if not isinstance(val, dict):
249 ff9c047c Iustin Pop
      raise errors.ConfigurationError("Invalid object passed to FromDict:"
250 ff9c047c Iustin Pop
                                      " expected dict, got %s" % type(val))
251 319856a9 Michael Hanselmann
    val_str = dict([(str(k), v) for k, v in val.iteritems()])
252 b459a848 Andrea Spadaccini
    obj = cls(**val_str) # pylint: disable=W0142
253 ff9c047c Iustin Pop
    return obj
254 ff9c047c Iustin Pop
255 e8d563f3 Iustin Pop
  def Copy(self):
256 e8d563f3 Iustin Pop
    """Makes a deep copy of the current object and its children.
257 e8d563f3 Iustin Pop

258 e8d563f3 Iustin Pop
    """
259 e8d563f3 Iustin Pop
    dict_form = self.ToDict()
260 e8d563f3 Iustin Pop
    clone_obj = self.__class__.FromDict(dict_form)
261 e8d563f3 Iustin Pop
    return clone_obj
262 e8d563f3 Iustin Pop
263 ff9c047c Iustin Pop
  def __repr__(self):
264 ff9c047c Iustin Pop
    """Implement __repr__ for ConfigObjects."""
265 ff9c047c Iustin Pop
    return repr(self.ToDict())
266 ff9c047c Iustin Pop
267 19830e88 Thomas Thrainer
  def __eq__(self, other):
268 19830e88 Thomas Thrainer
    """Implement __eq__ for ConfigObjects."""
269 19830e88 Thomas Thrainer
    return isinstance(other, self.__class__) and self.ToDict() == other.ToDict()
270 19830e88 Thomas Thrainer
271 560428be Guido Trotter
  def UpgradeConfig(self):
272 560428be Guido Trotter
    """Fill defaults for missing configuration values.
273 560428be Guido Trotter

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

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

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

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

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

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

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

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

339 ff9c047c Iustin Pop
    This replaces the tags set with a list.
340 ff9c047c Iustin Pop

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

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

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

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

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

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

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

423 cd3b4ff4 Helga Velroyen
    @type dev_type: L{constants.DTS_BLOCK}
424 51cb1581 Luca Bigliardi
    @param dev_type: the type to look for
425 51cb1581 Luca Bigliardi
    @rtype: boolean
426 51cb1581 Luca Bigliardi
    @return: boolean indicating if a disk of the given type was found or not
427 51cb1581 Luca Bigliardi

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

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

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

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

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

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

535 e51db2a6 Iustin Pop
    @warning: The path returned is not a normalized pathname; callers
536 e51db2a6 Iustin Pop
        should check that it is a valid path.
537 e51db2a6 Iustin Pop

538 222f2dd5 Iustin Pop
    """
539 cd3b4ff4 Helga Velroyen
    if self.dev_type == constants.DT_PLAIN:
540 222f2dd5 Iustin Pop
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
541 cd3b4ff4 Helga Velroyen
    elif self.dev_type == constants.DT_BLOCK:
542 b6135bbc Apollon Oikonomopoulos
      return self.logical_id[1]
543 cd3b4ff4 Helga Velroyen
    elif self.dev_type == constants.DT_RBD:
544 7181fba0 Constantinos Venetsanopoulos
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
545 222f2dd5 Iustin Pop
    return None
546 222f2dd5 Iustin Pop
547 fc1dc9d7 Iustin Pop
  def ChildrenNeeded(self):
548 fc1dc9d7 Iustin Pop
    """Compute the needed number of children for activation.
549 fc1dc9d7 Iustin Pop

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

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

558 fc1dc9d7 Iustin Pop
    """
559 cd3b4ff4 Helga Velroyen
    if self.dev_type == constants.DT_DRBD8:
560 fc1dc9d7 Iustin Pop
      return 0
561 fc1dc9d7 Iustin Pop
    return -1
562 fc1dc9d7 Iustin Pop
563 51cb1581 Luca Bigliardi
  def IsBasedOnDiskType(self, dev_type):
564 51cb1581 Luca Bigliardi
    """Check if the disk or its children are based on the given type.
565 51cb1581 Luca Bigliardi

566 cd3b4ff4 Helga Velroyen
    @type dev_type: L{constants.DTS_BLOCK}
567 51cb1581 Luca Bigliardi
    @param dev_type: the type to look for
568 51cb1581 Luca Bigliardi
    @rtype: boolean
569 51cb1581 Luca Bigliardi
    @return: boolean indicating if a device of the given type was found or not
570 51cb1581 Luca Bigliardi

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

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

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

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

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

638 6d33a6eb Iustin Pop
    This only works for VG-based disks.
639 6d33a6eb Iustin Pop

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

645 6d33a6eb Iustin Pop
    """
646 cd3b4ff4 Helga Velroyen
    if self.dev_type == constants.DT_PLAIN:
647 6d33a6eb Iustin Pop
      return {self.logical_id[0]: amount}
648 cd3b4ff4 Helga Velroyen
    elif self.dev_type == constants.DT_DRBD8:
649 6d33a6eb Iustin Pop
      if self.children:
650 6d33a6eb Iustin Pop
        return self.children[0].ComputeGrowth(amount)
651 6d33a6eb Iustin Pop
      else:
652 6d33a6eb Iustin Pop
        return {}
653 6d33a6eb Iustin Pop
    else:
654 6d33a6eb Iustin Pop
      # Other disk types do not require VG space
655 6d33a6eb Iustin Pop
      return {}
656 6d33a6eb Iustin Pop
657 acec9d51 Iustin Pop
  def RecordGrow(self, amount):
658 acec9d51 Iustin Pop
    """Update the size of this disk after growth.
659 acec9d51 Iustin Pop

660 acec9d51 Iustin Pop
    This method recurses over the disks's children and updates their
661 acec9d51 Iustin Pop
    size correspondigly. The method needs to be kept in sync with the
662 acec9d51 Iustin Pop
    actual algorithms from bdev.
663 acec9d51 Iustin Pop

664 acec9d51 Iustin Pop
    """
665 cd3b4ff4 Helga Velroyen
    if self.dev_type in (constants.DT_PLAIN, constants.DT_FILE,
666 cd3b4ff4 Helga Velroyen
                         constants.DT_RBD, constants.DT_EXT,
667 8106dd64 Santi Raffa
                         constants.DT_SHARED_FILE, constants.DT_GLUSTER):
668 acec9d51 Iustin Pop
      self.size += amount
669 cd3b4ff4 Helga Velroyen
    elif self.dev_type == constants.DT_DRBD8:
670 acec9d51 Iustin Pop
      if self.children:
671 acec9d51 Iustin Pop
        self.children[0].RecordGrow(amount)
672 acec9d51 Iustin Pop
      self.size += amount
673 acec9d51 Iustin Pop
    else:
674 acec9d51 Iustin Pop
      raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
675 acec9d51 Iustin Pop
                                   " disk type %s" % self.dev_type)
676 acec9d51 Iustin Pop
677 b54ecf12 Bernardo Dal Seno
  def Update(self, size=None, mode=None, spindles=None):
678 b54ecf12 Bernardo Dal Seno
    """Apply changes to size, spindles and mode.
679 735e1318 Michael Hanselmann

680 735e1318 Michael Hanselmann
    """
681 cd3b4ff4 Helga Velroyen
    if self.dev_type == constants.DT_DRBD8:
682 735e1318 Michael Hanselmann
      if self.children:
683 735e1318 Michael Hanselmann
        self.children[0].Update(size=size, mode=mode)
684 735e1318 Michael Hanselmann
    else:
685 735e1318 Michael Hanselmann
      assert not self.children
686 735e1318 Michael Hanselmann
687 735e1318 Michael Hanselmann
    if size is not None:
688 735e1318 Michael Hanselmann
      self.size = size
689 735e1318 Michael Hanselmann
    if mode is not None:
690 735e1318 Michael Hanselmann
      self.mode = mode
691 b54ecf12 Bernardo Dal Seno
    if spindles is not None:
692 b54ecf12 Bernardo Dal Seno
      self.spindles = spindles
693 735e1318 Michael Hanselmann
694 a805ec18 Iustin Pop
  def UnsetSize(self):
695 a805ec18 Iustin Pop
    """Sets recursively the size to zero for the disk and its children.
696 a805ec18 Iustin Pop

697 a805ec18 Iustin Pop
    """
698 a805ec18 Iustin Pop
    if self.children:
699 a805ec18 Iustin Pop
      for child in self.children:
700 a805ec18 Iustin Pop
        child.UnsetSize()
701 a805ec18 Iustin Pop
    self.size = 0
702 a805ec18 Iustin Pop
703 0c3d9c7c Thomas Thrainer
  def UpdateDynamicDiskParams(self, target_node_uuid, nodes_ip):
704 0c3d9c7c Thomas Thrainer
    """Updates the dynamic disk params for the given node.
705 0402302c Iustin Pop

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

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

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

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

752 ff9c047c Iustin Pop
    This replaces the children lists of objects with lists of
753 ff9c047c Iustin Pop
    standard python types.
754 ff9c047c Iustin Pop

755 ff9c047c Iustin Pop
    """
756 ff9c047c Iustin Pop
    bo = super(Disk, self).ToDict()
757 a0d2a91e Thomas Thrainer
    if not include_dynamic_params and "dynamic_params" in bo:
758 a0d2a91e Thomas Thrainer
      del bo["dynamic_params"]
759 ff9c047c Iustin Pop
760 ff9c047c Iustin Pop
    for attr in ("children",):
761 ff9c047c Iustin Pop
      alist = bo.get(attr, None)
762 ff9c047c Iustin Pop
      if alist:
763 fe502d25 Iustin Pop
        bo[attr] = outils.ContainerToDicts(alist)
764 ff9c047c Iustin Pop
    return bo
765 ff9c047c Iustin Pop
766 ff9c047c Iustin Pop
  @classmethod
767 ff9c047c Iustin Pop
  def FromDict(cls, val):
768 ff9c047c Iustin Pop
    """Custom function for Disks
769 ff9c047c Iustin Pop

770 ff9c047c Iustin Pop
    """
771 ff9c047c Iustin Pop
    obj = super(Disk, cls).FromDict(val)
772 ff9c047c Iustin Pop
    if obj.children:
773 fe502d25 Iustin Pop
      obj.children = outils.ContainerFromDicts(obj.children, list, Disk)
774 ff9c047c Iustin Pop
    if obj.logical_id and isinstance(obj.logical_id, list):
775 ff9c047c Iustin Pop
      obj.logical_id = tuple(obj.logical_id)
776 66a37e7a Helga Velroyen
    if obj.dev_type in constants.DTS_DRBD:
777 f9518d38 Iustin Pop
      # we need a tuple of length six here
778 f9518d38 Iustin Pop
      if len(obj.logical_id) < 6:
779 f9518d38 Iustin Pop
        obj.logical_id += (None,) * (6 - len(obj.logical_id))
780 ff9c047c Iustin Pop
    return obj
781 ff9c047c Iustin Pop
782 65a15336 Iustin Pop
  def __str__(self):
783 65a15336 Iustin Pop
    """Custom str() formatter for disks.
784 65a15336 Iustin Pop

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

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

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

849 cd46491f Renรฉ Nussbaumer
    @type disk_template: string
850 cd46491f Renรฉ Nussbaumer
    @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
851 cd46491f Renรฉ Nussbaumer
    @type disk_params: dict
852 cd46491f Renรฉ Nussbaumer
    @param disk_params: disk template parameters;
853 cd46491f Renรฉ Nussbaumer
                        dict(template_name -> parameters
854 cd46491f Renรฉ Nussbaumer
    @rtype: list(dict)
855 cd46491f Renรฉ Nussbaumer
    @return: a list of dicts, one for each node of the disk hierarchy. Each dict
856 cd46491f Renรฉ Nussbaumer
      contains the LD parameters of the node. The tree is flattened in-order.
857 cd46491f Renรฉ Nussbaumer

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

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

910 ffa339ca Iustin Pop
  """
911 918eb80b Agata Murawska
  @classmethod
912 a2112db5 Helga Velroyen
  def UpgradeDiskTemplates(cls, ipolicy, enabled_disk_templates):
913 a2112db5 Helga Velroyen
    """Upgrades the ipolicy configuration."""
914 a2112db5 Helga Velroyen
    if constants.IPOLICY_DTS in ipolicy:
915 a2112db5 Helga Velroyen
      if not set(ipolicy[constants.IPOLICY_DTS]).issubset(
916 a2112db5 Helga Velroyen
        set(enabled_disk_templates)):
917 a2112db5 Helga Velroyen
        ipolicy[constants.IPOLICY_DTS] = list(
918 a2112db5 Helga Velroyen
          set(ipolicy[constants.IPOLICY_DTS]) & set(enabled_disk_templates))
919 a2112db5 Helga Velroyen
920 a2112db5 Helga Velroyen
  @classmethod
921 8b057218 Renรฉ Nussbaumer
  def CheckParameterSyntax(cls, ipolicy, check_std):
922 918eb80b Agata Murawska
    """ Check the instance policy for validity.
923 918eb80b Agata Murawska

924 da5f09ef Bernardo Dal Seno
    @type ipolicy: dict
925 da5f09ef Bernardo Dal Seno
    @param ipolicy: dictionary with min/max/std specs and policies
926 da5f09ef Bernardo Dal Seno
    @type check_std: bool
927 da5f09ef Bernardo Dal Seno
    @param check_std: Whether to check std value or just assume compliance
928 da5f09ef Bernardo Dal Seno
    @raise errors.ConfigurationError: when the policy is not legal
929 da5f09ef Bernardo Dal Seno

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

954 62fed51b Bernardo Dal Seno
    @type ipolicy: dict
955 62fed51b Bernardo Dal Seno
    @param ipolicy: dictionary with min/max/std specs
956 62fed51b Bernardo Dal Seno
    @type check_std: bool
957 62fed51b Bernardo Dal Seno
    @param check_std: Whether to check std value or just assume compliance
958 62fed51b Bernardo Dal Seno
    @raise errors.ConfigurationError: when specs are not valid
959 62fed51b Bernardo Dal Seno

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

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

999 da5f09ef Bernardo Dal Seno
    @type minmaxspecs: dict
1000 da5f09ef Bernardo Dal Seno
    @param minmaxspecs: dictionary with min and max instance spec
1001 da5f09ef Bernardo Dal Seno
    @type stdspec: dict
1002 da5f09ef Bernardo Dal Seno
    @param stdspec: dictionary with standard instance spec
1003 918eb80b Agata Murawska
    @type name: string
1004 918eb80b Agata Murawska
    @param name: what are the limits for
1005 8b057218 Renรฉ Nussbaumer
    @type check_std: bool
1006 8b057218 Renรฉ Nussbaumer
    @param check_std: Whether to check std value or just assume compliance
1007 b342c9dd Bernardo Dal Seno
    @rtype: bool
1008 b342c9dd Bernardo Dal Seno
    @return: C{True} when specs are valid, C{False} when standard spec for the
1009 b342c9dd Bernardo Dal Seno
        given name is not valid
1010 b342c9dd Bernardo Dal Seno
    @raise errors.ConfigurationError: when min/max specs for the given name
1011 b342c9dd Bernardo Dal Seno
        are not valid
1012 918eb80b Agata Murawska

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

1033 2cc673a3 Iustin Pop
    """
1034 ba5c6c6b Bernardo Dal Seno
    if not disk_templates:
1035 ba5c6c6b Bernardo Dal Seno
      raise errors.ConfigurationError("Instance policy must contain" +
1036 ba5c6c6b Bernardo Dal Seno
                                      " at least one disk template")
1037 2cc673a3 Iustin Pop
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1038 2cc673a3 Iustin Pop
    if wrong:
1039 2cc673a3 Iustin Pop
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1040 2cc673a3 Iustin Pop
                                      utils.CommaJoin(wrong))
1041 2cc673a3 Iustin Pop
1042 ff6c5e55 Iustin Pop
  @classmethod
1043 ff6c5e55 Iustin Pop
  def CheckParameter(cls, key, value):
1044 ff6c5e55 Iustin Pop
    """Checks a parameter.
1045 ff6c5e55 Iustin Pop

1046 ff6c5e55 Iustin Pop
    Currently we expect all parameters to be float values.
1047 ff6c5e55 Iustin Pop

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

1078 cfcc5c6d Iustin Pop
    This is a simple wrapper over _ComputeAllNodes.
1079 cfcc5c6d Iustin Pop

1080 cfcc5c6d Iustin Pop
    """
1081 cfcc5c6d Iustin Pop
    all_nodes = set(self._ComputeAllNodes())
1082 cfcc5c6d Iustin Pop
    all_nodes.discard(self.primary_node)
1083 cfcc5c6d Iustin Pop
    return tuple(all_nodes)
1084 cfcc5c6d Iustin Pop
1085 cfcc5c6d Iustin Pop
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1086 05325a35 Bernardo Dal Seno
                             "List of names of secondary nodes")
1087 cfcc5c6d Iustin Pop
1088 cfcc5c6d Iustin Pop
  def _ComputeAllNodes(self):
1089 cfcc5c6d Iustin Pop
    """Compute the list of all nodes.
1090 cfcc5c6d Iustin Pop

1091 a8083063 Iustin Pop
    Since the data is already there (in the drbd disks), keeping it as
1092 a8083063 Iustin Pop
    a separate normal attribute is redundant and if not properly
1093 a8083063 Iustin Pop
    synchronised can cause problems. Thus it's better to compute it
1094 a8083063 Iustin Pop
    dynamically.
1095 a8083063 Iustin Pop

1096 a8083063 Iustin Pop
    """
1097 cfcc5c6d Iustin Pop
    def _Helper(nodes, device):
1098 cfcc5c6d Iustin Pop
      """Recursively computes nodes given a top device."""
1099 66a37e7a Helga Velroyen
      if device.dev_type in constants.DTS_DRBD:
1100 cfcc5c6d Iustin Pop
        nodea, nodeb = device.logical_id[:2]
1101 cfcc5c6d Iustin Pop
        nodes.add(nodea)
1102 cfcc5c6d Iustin Pop
        nodes.add(nodeb)
1103 a8083063 Iustin Pop
      if device.children:
1104 a8083063 Iustin Pop
        for child in device.children:
1105 cfcc5c6d Iustin Pop
          _Helper(nodes, child)
1106 a8083063 Iustin Pop
1107 cfcc5c6d Iustin Pop
    all_nodes = set()
1108 99c7b2a1 Iustin Pop
    all_nodes.add(self.primary_node)
1109 a8083063 Iustin Pop
    for device in self.disks:
1110 cfcc5c6d Iustin Pop
      _Helper(all_nodes, device)
1111 cfcc5c6d Iustin Pop
    return tuple(all_nodes)
1112 a8083063 Iustin Pop
1113 cfcc5c6d Iustin Pop
  all_nodes = property(_ComputeAllNodes, None, None,
1114 05325a35 Bernardo Dal Seno
                       "List of names of all the nodes of the instance")
1115 a8083063 Iustin Pop
1116 843094ad Thomas Thrainer
  def MapLVsByNode(self, lvmap=None, devs=None, node_uuid=None):
1117 a8083063 Iustin Pop
    """Provide a mapping of nodes to LVs this instance owns.
1118 a8083063 Iustin Pop

1119 c41eea6e Iustin Pop
    This function figures out what logical volumes should belong on
1120 c41eea6e Iustin Pop
    which nodes, recursing through a device tree.
1121 a8083063 Iustin Pop

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

1136 a8083063 Iustin Pop
    """
1137 843094ad Thomas Thrainer
    if node_uuid is None:
1138 843094ad Thomas Thrainer
      node_uuid = self.primary_node
1139 a8083063 Iustin Pop
1140 a8083063 Iustin Pop
    if lvmap is None:
1141 e687ec01 Michael Hanselmann
      lvmap = {
1142 843094ad Thomas Thrainer
        node_uuid: [],
1143 e687ec01 Michael Hanselmann
        }
1144 a8083063 Iustin Pop
      ret = lvmap
1145 a8083063 Iustin Pop
    else:
1146 843094ad Thomas Thrainer
      if not node_uuid in lvmap:
1147 843094ad Thomas Thrainer
        lvmap[node_uuid] = []
1148 a8083063 Iustin Pop
      ret = None
1149 a8083063 Iustin Pop
1150 a8083063 Iustin Pop
    if not devs:
1151 a8083063 Iustin Pop
      devs = self.disks
1152 a8083063 Iustin Pop
1153 a8083063 Iustin Pop
    for dev in devs:
1154 cd3b4ff4 Helga Velroyen
      if dev.dev_type == constants.DT_PLAIN:
1155 843094ad Thomas Thrainer
        lvmap[node_uuid].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1156 a8083063 Iustin Pop
1157 66a37e7a Helga Velroyen
      elif dev.dev_type in constants.DTS_DRBD:
1158 a8083063 Iustin Pop
        if dev.children:
1159 a8083063 Iustin Pop
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1160 a8083063 Iustin Pop
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1161 a8083063 Iustin Pop
1162 a8083063 Iustin Pop
      elif dev.children:
1163 843094ad Thomas Thrainer
        self.MapLVsByNode(lvmap, dev.children, node_uuid)
1164 a8083063 Iustin Pop
1165 a8083063 Iustin Pop
    return ret
1166 a8083063 Iustin Pop
1167 ad24e046 Iustin Pop
  def FindDisk(self, idx):
1168 ad24e046 Iustin Pop
    """Find a disk given having a specified index.
1169 644eeef9 Iustin Pop

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

1172 ad24e046 Iustin Pop
    @type idx: int
1173 ad24e046 Iustin Pop
    @param idx: the disk index
1174 ad24e046 Iustin Pop
    @rtype: L{Disk}
1175 ad24e046 Iustin Pop
    @return: the corresponding disk
1176 ad24e046 Iustin Pop
    @raise errors.OpPrereqError: when the given index is not valid
1177 644eeef9 Iustin Pop

1178 ad24e046 Iustin Pop
    """
1179 ad24e046 Iustin Pop
    try:
1180 ad24e046 Iustin Pop
      idx = int(idx)
1181 ad24e046 Iustin Pop
      return self.disks[idx]
1182 691744c4 Iustin Pop
    except (TypeError, ValueError), err:
1183 debac808 Iustin Pop
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1184 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
1185 ad24e046 Iustin Pop
    except IndexError:
1186 ad24e046 Iustin Pop
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1187 daa55b04 Michael Hanselmann
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1188 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
1189 644eeef9 Iustin Pop
1190 ff9c047c Iustin Pop
  def ToDict(self):
1191 ff9c047c Iustin Pop
    """Instance-specific conversion to standard python types.
1192 ff9c047c Iustin Pop

1193 ff9c047c Iustin Pop
    This replaces the children lists of objects with lists of standard
1194 ff9c047c Iustin Pop
    python types.
1195 ff9c047c Iustin Pop

1196 ff9c047c Iustin Pop
    """
1197 ff9c047c Iustin Pop
    bo = super(Instance, self).ToDict()
1198 ff9c047c Iustin Pop
1199 ff9c047c Iustin Pop
    for attr in "nics", "disks":
1200 ff9c047c Iustin Pop
      alist = bo.get(attr, None)
1201 ff9c047c Iustin Pop
      if alist:
1202 fe502d25 Iustin Pop
        nlist = outils.ContainerToDicts(alist)
1203 ff9c047c Iustin Pop
      else:
1204 ff9c047c Iustin Pop
        nlist = []
1205 ff9c047c Iustin Pop
      bo[attr] = nlist
1206 ff9c047c Iustin Pop
    return bo
1207 ff9c047c Iustin Pop
1208 ff9c047c Iustin Pop
  @classmethod
1209 ff9c047c Iustin Pop
  def FromDict(cls, val):
1210 ff9c047c Iustin Pop
    """Custom function for instances.
1211 ff9c047c Iustin Pop

1212 ff9c047c Iustin Pop
    """
1213 9ca8a7c5 Agata Murawska
    if "admin_state" not in val:
1214 9ca8a7c5 Agata Murawska
      if val.get("admin_up", False):
1215 9ca8a7c5 Agata Murawska
        val["admin_state"] = constants.ADMINST_UP
1216 9ca8a7c5 Agata Murawska
      else:
1217 9ca8a7c5 Agata Murawska
        val["admin_state"] = constants.ADMINST_DOWN
1218 9ca8a7c5 Agata Murawska
    if "admin_up" in val:
1219 9ca8a7c5 Agata Murawska
      del val["admin_up"]
1220 ff9c047c Iustin Pop
    obj = super(Instance, cls).FromDict(val)
1221 fe502d25 Iustin Pop
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1222 fe502d25 Iustin Pop
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1223 ff9c047c Iustin Pop
    return obj
1224 ff9c047c Iustin Pop
1225 90d726a8 Iustin Pop
  def UpgradeConfig(self):
1226 90d726a8 Iustin Pop
    """Fill defaults for missing configuration values.
1227 90d726a8 Iustin Pop

1228 90d726a8 Iustin Pop
    """
1229 90d726a8 Iustin Pop
    for nic in self.nics:
1230 90d726a8 Iustin Pop
      nic.UpgradeConfig()
1231 90d726a8 Iustin Pop
    for disk in self.disks:
1232 90d726a8 Iustin Pop
      disk.UpgradeConfig()
1233 7736a5f2 Iustin Pop
    if self.hvparams:
1234 7736a5f2 Iustin Pop
      for key in constants.HVC_GLOBALS:
1235 7736a5f2 Iustin Pop
        try:
1236 7736a5f2 Iustin Pop
          del self.hvparams[key]
1237 7736a5f2 Iustin Pop
        except KeyError:
1238 7736a5f2 Iustin Pop
          pass
1239 1bdcbbab Iustin Pop
    if self.osparams is None:
1240 1bdcbbab Iustin Pop
      self.osparams = {}
1241 8c72ab2b Guido Trotter
    UpgradeBeParams(self.beparams)
1242 a8e07057 Thomas Thrainer
    if self.disks_active is None:
1243 a8e07057 Thomas Thrainer
      self.disks_active = self.admin_state == constants.ADMINST_UP
1244 90d726a8 Iustin Pop
1245 a8083063 Iustin Pop
1246 a8083063 Iustin Pop
class OS(ConfigObject):
1247 b41b3516 Iustin Pop
  """Config object representing an operating system.
1248 b41b3516 Iustin Pop

1249 b41b3516 Iustin Pop
  @type supported_parameters: list
1250 b41b3516 Iustin Pop
  @ivar supported_parameters: a list of tuples, name and description,
1251 b41b3516 Iustin Pop
      containing the supported parameters by this OS
1252 b41b3516 Iustin Pop

1253 870dc44c Iustin Pop
  @type VARIANT_DELIM: string
1254 870dc44c Iustin Pop
  @cvar VARIANT_DELIM: the variant delimiter
1255 870dc44c Iustin Pop

1256 b41b3516 Iustin Pop
  """
1257 a8083063 Iustin Pop
  __slots__ = [
1258 a8083063 Iustin Pop
    "name",
1259 a8083063 Iustin Pop
    "path",
1260 082a7f91 Guido Trotter
    "api_versions",
1261 a8083063 Iustin Pop
    "create_script",
1262 a8083063 Iustin Pop
    "export_script",
1263 386b57af Iustin Pop
    "import_script",
1264 386b57af Iustin Pop
    "rename_script",
1265 b41b3516 Iustin Pop
    "verify_script",
1266 6d79896b Guido Trotter
    "supported_variants",
1267 b41b3516 Iustin Pop
    "supported_parameters",
1268 a8083063 Iustin Pop
    ]
1269 a8083063 Iustin Pop
1270 870dc44c Iustin Pop
  VARIANT_DELIM = "+"
1271 870dc44c Iustin Pop
1272 870dc44c Iustin Pop
  @classmethod
1273 870dc44c Iustin Pop
  def SplitNameVariant(cls, name):
1274 870dc44c Iustin Pop
    """Splits the name into the proper name and variant.
1275 870dc44c Iustin Pop

1276 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1277 870dc44c Iustin Pop
    @rtype: list
1278 870dc44c Iustin Pop
    @return: a list of two elements; if the original name didn't
1279 870dc44c Iustin Pop
        contain a variant, it's returned as an empty string
1280 870dc44c Iustin Pop

1281 870dc44c Iustin Pop
    """
1282 870dc44c Iustin Pop
    nv = name.split(cls.VARIANT_DELIM, 1)
1283 870dc44c Iustin Pop
    if len(nv) == 1:
1284 870dc44c Iustin Pop
      nv.append("")
1285 870dc44c Iustin Pop
    return nv
1286 870dc44c Iustin Pop
1287 870dc44c Iustin Pop
  @classmethod
1288 870dc44c Iustin Pop
  def GetName(cls, name):
1289 870dc44c Iustin Pop
    """Returns the proper name of the os (without the variant).
1290 870dc44c Iustin Pop

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

1293 870dc44c Iustin Pop
    """
1294 870dc44c Iustin Pop
    return cls.SplitNameVariant(name)[0]
1295 870dc44c Iustin Pop
1296 870dc44c Iustin Pop
  @classmethod
1297 870dc44c Iustin Pop
  def GetVariant(cls, name):
1298 870dc44c Iustin Pop
    """Returns the variant the os (without the base name).
1299 870dc44c Iustin Pop

1300 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1301 870dc44c Iustin Pop

1302 870dc44c Iustin Pop
    """
1303 870dc44c Iustin Pop
    return cls.SplitNameVariant(name)[1]
1304 870dc44c Iustin Pop
1305 7c0d6283 Michael Hanselmann
1306 376631d1 Constantinos Venetsanopoulos
class ExtStorage(ConfigObject):
1307 376631d1 Constantinos Venetsanopoulos
  """Config object representing an External Storage Provider.
1308 376631d1 Constantinos Venetsanopoulos

1309 376631d1 Constantinos Venetsanopoulos
  """
1310 376631d1 Constantinos Venetsanopoulos
  __slots__ = [
1311 376631d1 Constantinos Venetsanopoulos
    "name",
1312 376631d1 Constantinos Venetsanopoulos
    "path",
1313 376631d1 Constantinos Venetsanopoulos
    "create_script",
1314 376631d1 Constantinos Venetsanopoulos
    "remove_script",
1315 376631d1 Constantinos Venetsanopoulos
    "grow_script",
1316 376631d1 Constantinos Venetsanopoulos
    "attach_script",
1317 376631d1 Constantinos Venetsanopoulos
    "detach_script",
1318 376631d1 Constantinos Venetsanopoulos
    "setinfo_script",
1319 938adc87 Constantinos Venetsanopoulos
    "verify_script",
1320 938adc87 Constantinos Venetsanopoulos
    "supported_parameters",
1321 376631d1 Constantinos Venetsanopoulos
    ]
1322 376631d1 Constantinos Venetsanopoulos
1323 376631d1 Constantinos Venetsanopoulos
1324 5f06ce5e Michael Hanselmann
class NodeHvState(ConfigObject):
1325 5f06ce5e Michael Hanselmann
  """Hypvervisor state on a node.
1326 5f06ce5e Michael Hanselmann

1327 5f06ce5e Michael Hanselmann
  @ivar mem_total: Total amount of memory
1328 5f06ce5e Michael Hanselmann
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1329 5f06ce5e Michael Hanselmann
    available)
1330 5f06ce5e Michael Hanselmann
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1331 5f06ce5e Michael Hanselmann
    rounding
1332 5f06ce5e Michael Hanselmann
  @ivar mem_inst: Memory used by instances living on node
1333 5f06ce5e Michael Hanselmann
  @ivar cpu_total: Total node CPU core count
1334 5f06ce5e Michael Hanselmann
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1335 5f06ce5e Michael Hanselmann

1336 5f06ce5e Michael Hanselmann
  """
1337 5f06ce5e Michael Hanselmann
  __slots__ = [
1338 5f06ce5e Michael Hanselmann
    "mem_total",
1339 5f06ce5e Michael Hanselmann
    "mem_node",
1340 5f06ce5e Michael Hanselmann
    "mem_hv",
1341 5f06ce5e Michael Hanselmann
    "mem_inst",
1342 5f06ce5e Michael Hanselmann
    "cpu_total",
1343 5f06ce5e Michael Hanselmann
    "cpu_node",
1344 5f06ce5e Michael Hanselmann
    ] + _TIMESTAMPS
1345 5f06ce5e Michael Hanselmann
1346 5f06ce5e Michael Hanselmann
1347 5f06ce5e Michael Hanselmann
class NodeDiskState(ConfigObject):
1348 5f06ce5e Michael Hanselmann
  """Disk state on a node.
1349 5f06ce5e Michael Hanselmann

1350 5f06ce5e Michael Hanselmann
  """
1351 5f06ce5e Michael Hanselmann
  __slots__ = [
1352 5f06ce5e Michael Hanselmann
    "total",
1353 5f06ce5e Michael Hanselmann
    "reserved",
1354 5f06ce5e Michael Hanselmann
    "overhead",
1355 5f06ce5e Michael Hanselmann
    ] + _TIMESTAMPS
1356 5f06ce5e Michael Hanselmann
1357 5f06ce5e Michael Hanselmann
1358 ec29fe40 Iustin Pop
class Node(TaggableObject):
1359 634d30f4 Michael Hanselmann
  """Config object representing a node.
1360 634d30f4 Michael Hanselmann

1361 634d30f4 Michael Hanselmann
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1362 634d30f4 Michael Hanselmann
  @ivar hv_state_static: Hypervisor state overriden by user
1363 634d30f4 Michael Hanselmann
  @ivar disk_state: Disk state (e.g. free space)
1364 634d30f4 Michael Hanselmann
  @ivar disk_state_static: Disk state overriden by user
1365 634d30f4 Michael Hanselmann

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

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

1413 5f06ce5e Michael Hanselmann
    """
1414 5f06ce5e Michael Hanselmann
    data = super(Node, self).ToDict()
1415 5f06ce5e Michael Hanselmann
1416 5f06ce5e Michael Hanselmann
    hv_state = data.get("hv_state", None)
1417 5f06ce5e Michael Hanselmann
    if hv_state is not None:
1418 fe502d25 Iustin Pop
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1419 5f06ce5e Michael Hanselmann
1420 5f06ce5e Michael Hanselmann
    disk_state = data.get("disk_state", None)
1421 5f06ce5e Michael Hanselmann
    if disk_state is not None:
1422 5f06ce5e Michael Hanselmann
      data["disk_state"] = \
1423 fe502d25 Iustin Pop
        dict((key, outils.ContainerToDicts(value))
1424 5f06ce5e Michael Hanselmann
             for (key, value) in disk_state.items())
1425 5f06ce5e Michael Hanselmann
1426 5f06ce5e Michael Hanselmann
    return data
1427 5f06ce5e Michael Hanselmann
1428 5f06ce5e Michael Hanselmann
  @classmethod
1429 5f06ce5e Michael Hanselmann
  def FromDict(cls, val):
1430 5f06ce5e Michael Hanselmann
    """Custom function for deserializing.
1431 5f06ce5e Michael Hanselmann

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

1465 c60abd62 Guido Trotter
    This discards the members object, which gets recalculated and is only kept
1466 c60abd62 Guido Trotter
    in memory.
1467 24a3707f Guido Trotter

1468 24a3707f Guido Trotter
    """
1469 24a3707f Guido Trotter
    mydict = super(NodeGroup, self).ToDict()
1470 24a3707f Guido Trotter
    del mydict["members"]
1471 24a3707f Guido Trotter
    return mydict
1472 24a3707f Guido Trotter
1473 24a3707f Guido Trotter
  @classmethod
1474 24a3707f Guido Trotter
  def FromDict(cls, val):
1475 24a3707f Guido Trotter
    """Custom function for nodegroup.
1476 24a3707f Guido Trotter

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

1479 24a3707f Guido Trotter
    """
1480 24a3707f Guido Trotter
    obj = super(NodeGroup, cls).FromDict(val)
1481 24a3707f Guido Trotter
    obj.members = []
1482 24a3707f Guido Trotter
    return obj
1483 24a3707f Guido Trotter
1484 095e71aa Renรฉ Nussbaumer
  def UpgradeConfig(self):
1485 095e71aa Renรฉ Nussbaumer
    """Fill defaults for missing configuration values.
1486 095e71aa Renรฉ Nussbaumer

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

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

1517 095e71aa Renรฉ Nussbaumer
    """
1518 095e71aa Renรฉ Nussbaumer
    return self.SimpleFillND(node.ndparams)
1519 095e71aa Renรฉ Nussbaumer
1520 095e71aa Renรฉ Nussbaumer
  def SimpleFillND(self, ndparams):
1521 095e71aa Renรฉ Nussbaumer
    """Fill a given ndparams dict with defaults.
1522 095e71aa Renรฉ Nussbaumer

1523 095e71aa Renรฉ Nussbaumer
    @type ndparams: dict
1524 095e71aa Renรฉ Nussbaumer
    @param ndparams: the dict to fill
1525 095e71aa Renรฉ Nussbaumer
    @rtype: dict
1526 095e71aa Renรฉ Nussbaumer
    @return: a copy of the passed in ndparams with missing keys filled
1527 e6e88de6 Adeodato Simo
        from the node group defaults
1528 095e71aa Renรฉ Nussbaumer

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

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

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

1715 0fbedb7a Michael Hanselmann
    """
1716 0fbedb7a Michael Hanselmann
    return self.enabled_hypervisors[0]
1717 0fbedb7a Michael Hanselmann
1718 319856a9 Michael Hanselmann
  def ToDict(self):
1719 319856a9 Michael Hanselmann
    """Custom function for cluster.
1720 319856a9 Michael Hanselmann

1721 319856a9 Michael Hanselmann
    """
1722 b60ae2ca Iustin Pop
    mydict = super(Cluster, self).ToDict()
1723 4d36fbf4 Michael Hanselmann
1724 4d36fbf4 Michael Hanselmann
    if self.tcpudp_port_pool is None:
1725 4d36fbf4 Michael Hanselmann
      tcpudp_port_pool = []
1726 4d36fbf4 Michael Hanselmann
    else:
1727 4d36fbf4 Michael Hanselmann
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1728 4d36fbf4 Michael Hanselmann
1729 4d36fbf4 Michael Hanselmann
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1730 4d36fbf4 Michael Hanselmann
1731 319856a9 Michael Hanselmann
    return mydict
1732 319856a9 Michael Hanselmann
1733 319856a9 Michael Hanselmann
  @classmethod
1734 319856a9 Michael Hanselmann
  def FromDict(cls, val):
1735 319856a9 Michael Hanselmann
    """Custom function for cluster.
1736 319856a9 Michael Hanselmann

1737 319856a9 Michael Hanselmann
    """
1738 b60ae2ca Iustin Pop
    obj = super(Cluster, cls).FromDict(val)
1739 4d36fbf4 Michael Hanselmann
1740 4d36fbf4 Michael Hanselmann
    if obj.tcpudp_port_pool is None:
1741 4d36fbf4 Michael Hanselmann
      obj.tcpudp_port_pool = set()
1742 4d36fbf4 Michael Hanselmann
    elif not isinstance(obj.tcpudp_port_pool, set):
1743 319856a9 Michael Hanselmann
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1744 4d36fbf4 Michael Hanselmann
1745 319856a9 Michael Hanselmann
    return obj
1746 319856a9 Michael Hanselmann
1747 8a147bba Renรฉ Nussbaumer
  def SimpleFillDP(self, diskparams):
1748 8a147bba Renรฉ Nussbaumer
    """Fill a given diskparams dict with cluster defaults.
1749 8a147bba Renรฉ Nussbaumer

1750 8a147bba Renรฉ Nussbaumer
    @param diskparams: The diskparams
1751 8a147bba Renรฉ Nussbaumer
    @return: The defaults dict
1752 8a147bba Renรฉ Nussbaumer

1753 8a147bba Renรฉ Nussbaumer
    """
1754 8a147bba Renรฉ Nussbaumer
    return FillDiskParams(self.diskparams, diskparams)
1755 8a147bba Renรฉ Nussbaumer
1756 d63479b5 Iustin Pop
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1757 d63479b5 Iustin Pop
    """Get the default hypervisor parameters for the cluster.
1758 d63479b5 Iustin Pop

1759 d63479b5 Iustin Pop
    @param hypervisor: the hypervisor name
1760 d63479b5 Iustin Pop
    @param os_name: if specified, we'll also update the defaults for this OS
1761 d63479b5 Iustin Pop
    @param skip_keys: if passed, list of keys not to use
1762 d63479b5 Iustin Pop
    @return: the defaults dict
1763 d63479b5 Iustin Pop

1764 d63479b5 Iustin Pop
    """
1765 d63479b5 Iustin Pop
    if skip_keys is None:
1766 d63479b5 Iustin Pop
      skip_keys = []
1767 d63479b5 Iustin Pop
1768 d63479b5 Iustin Pop
    fill_stack = [self.hvparams.get(hypervisor, {})]
1769 d63479b5 Iustin Pop
    if os_name is not None:
1770 d63479b5 Iustin Pop
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1771 d63479b5 Iustin Pop
      fill_stack.append(os_hvp)
1772 d63479b5 Iustin Pop
1773 d63479b5 Iustin Pop
    ret_dict = {}
1774 d63479b5 Iustin Pop
    for o_dict in fill_stack:
1775 d63479b5 Iustin Pop
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1776 d63479b5 Iustin Pop
1777 d63479b5 Iustin Pop
    return ret_dict
1778 d63479b5 Iustin Pop
1779 73e0328b Iustin Pop
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1780 73e0328b Iustin Pop
    """Fill a given hvparams dict with cluster defaults.
1781 73e0328b Iustin Pop

1782 73e0328b Iustin Pop
    @type hv_name: string
1783 73e0328b Iustin Pop
    @param hv_name: the hypervisor to use
1784 73e0328b Iustin Pop
    @type os_name: string
1785 73e0328b Iustin Pop
    @param os_name: the OS to use for overriding the hypervisor defaults
1786 73e0328b Iustin Pop
    @type skip_globals: boolean
1787 73e0328b Iustin Pop
    @param skip_globals: if True, the global hypervisor parameters will
1788 73e0328b Iustin Pop
        not be filled
1789 73e0328b Iustin Pop
    @rtype: dict
1790 73e0328b Iustin Pop
    @return: a copy of the given hvparams with missing keys filled from
1791 73e0328b Iustin Pop
        the cluster defaults
1792 73e0328b Iustin Pop

1793 73e0328b Iustin Pop
    """
1794 73e0328b Iustin Pop
    if skip_globals:
1795 73e0328b Iustin Pop
      skip_keys = constants.HVC_GLOBALS
1796 73e0328b Iustin Pop
    else:
1797 73e0328b Iustin Pop
      skip_keys = []
1798 73e0328b Iustin Pop
1799 73e0328b Iustin Pop
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1800 73e0328b Iustin Pop
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1801 d63479b5 Iustin Pop
1802 7736a5f2 Iustin Pop
  def FillHV(self, instance, skip_globals=False):
1803 73e0328b Iustin Pop
    """Fill an instance's hvparams dict with cluster defaults.
1804 5bf7b5cf Iustin Pop

1805 a2a24f4c Guido Trotter
    @type instance: L{objects.Instance}
1806 5bf7b5cf Iustin Pop
    @param instance: the instance parameter to fill
1807 7736a5f2 Iustin Pop
    @type skip_globals: boolean
1808 7736a5f2 Iustin Pop
    @param skip_globals: if True, the global hypervisor parameters will
1809 7736a5f2 Iustin Pop
        not be filled
1810 5bf7b5cf Iustin Pop
    @rtype: dict
1811 5bf7b5cf Iustin Pop
    @return: a copy of the instance's hvparams with missing keys filled from
1812 5bf7b5cf Iustin Pop
        the cluster defaults
1813 5bf7b5cf Iustin Pop

1814 5bf7b5cf Iustin Pop
    """
1815 73e0328b Iustin Pop
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1816 73e0328b Iustin Pop
                             instance.hvparams, skip_globals)
1817 17463d22 Renรฉ Nussbaumer
1818 73e0328b Iustin Pop
  def SimpleFillBE(self, beparams):
1819 73e0328b Iustin Pop
    """Fill a given beparams dict with cluster defaults.
1820 73e0328b Iustin Pop

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

1827 73e0328b Iustin Pop
    """
1828 73e0328b Iustin Pop
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1829 5bf7b5cf Iustin Pop
1830 5bf7b5cf Iustin Pop
  def FillBE(self, instance):
1831 73e0328b Iustin Pop
    """Fill an instance's beparams dict with cluster defaults.
1832 5bf7b5cf Iustin Pop

1833 a2a24f4c Guido Trotter
    @type instance: L{objects.Instance}
1834 5bf7b5cf Iustin Pop
    @param instance: the instance parameter to fill
1835 5bf7b5cf Iustin Pop
    @rtype: dict
1836 5bf7b5cf Iustin Pop
    @return: a copy of the instance's beparams with missing keys filled from
1837 5bf7b5cf Iustin Pop
        the cluster defaults
1838 5bf7b5cf Iustin Pop

1839 5bf7b5cf Iustin Pop
    """
1840 73e0328b Iustin Pop
    return self.SimpleFillBE(instance.beparams)
1841 73e0328b Iustin Pop
1842 73e0328b Iustin Pop
  def SimpleFillNIC(self, nicparams):
1843 73e0328b Iustin Pop
    """Fill a given nicparams dict with cluster defaults.
1844 73e0328b Iustin Pop

1845 06596a60 Guido Trotter
    @type nicparams: dict
1846 06596a60 Guido Trotter
    @param nicparams: the dict to fill
1847 73e0328b Iustin Pop
    @rtype: dict
1848 73e0328b Iustin Pop
    @return: a copy of the passed in nicparams with missing keys filled
1849 73e0328b Iustin Pop
        from the cluster defaults
1850 73e0328b Iustin Pop

1851 73e0328b Iustin Pop
    """
1852 73e0328b Iustin Pop
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1853 5bf7b5cf Iustin Pop
1854 1bdcbbab Iustin Pop
  def SimpleFillOS(self, os_name, os_params):
1855 1bdcbbab Iustin Pop
    """Fill an instance's osparams dict with cluster defaults.
1856 1bdcbbab Iustin Pop

1857 1bdcbbab Iustin Pop
    @type os_name: string
1858 1bdcbbab Iustin Pop
    @param os_name: the OS name to use
1859 1bdcbbab Iustin Pop
    @type os_params: dict
1860 1bdcbbab Iustin Pop
    @param os_params: the dict to fill with default values
1861 1bdcbbab Iustin Pop
    @rtype: dict
1862 1bdcbbab Iustin Pop
    @return: a copy of the instance's osparams with missing keys filled from
1863 1bdcbbab Iustin Pop
        the cluster defaults
1864 1bdcbbab Iustin Pop

1865 1bdcbbab Iustin Pop
    """
1866 1bdcbbab Iustin Pop
    name_only = os_name.split("+", 1)[0]
1867 1bdcbbab Iustin Pop
    # base OS
1868 1bdcbbab Iustin Pop
    result = self.osparams.get(name_only, {})
1869 1bdcbbab Iustin Pop
    # OS with variant
1870 1bdcbbab Iustin Pop
    result = FillDict(result, self.osparams.get(os_name, {}))
1871 1bdcbbab Iustin Pop
    # specified params
1872 1bdcbbab Iustin Pop
    return FillDict(result, os_params)
1873 1bdcbbab Iustin Pop
1874 2da9f556 Renรฉ Nussbaumer
  @staticmethod
1875 2da9f556 Renรฉ Nussbaumer
  def SimpleFillHvState(hv_state):
1876 2da9f556 Renรฉ Nussbaumer
    """Fill an hv_state sub dict with cluster defaults.
1877 2da9f556 Renรฉ Nussbaumer

1878 2da9f556 Renรฉ Nussbaumer
    """
1879 2da9f556 Renรฉ Nussbaumer
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1880 2da9f556 Renรฉ Nussbaumer
1881 2da9f556 Renรฉ Nussbaumer
  @staticmethod
1882 2da9f556 Renรฉ Nussbaumer
  def SimpleFillDiskState(disk_state):
1883 2da9f556 Renรฉ Nussbaumer
    """Fill an disk_state sub dict with cluster defaults.
1884 2da9f556 Renรฉ Nussbaumer

1885 2da9f556 Renรฉ Nussbaumer
    """
1886 2da9f556 Renรฉ Nussbaumer
    return FillDict(constants.DS_DEFAULTS, disk_state)
1887 2da9f556 Renรฉ Nussbaumer
1888 095e71aa Renรฉ Nussbaumer
  def FillND(self, node, nodegroup):
1889 ce523de1 Michael Hanselmann
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1890 095e71aa Renรฉ Nussbaumer

1891 095e71aa Renรฉ Nussbaumer
    @type node: L{objects.Node}
1892 095e71aa Renรฉ Nussbaumer
    @param node: A Node object to fill
1893 095e71aa Renรฉ Nussbaumer
    @type nodegroup: L{objects.NodeGroup}
1894 095e71aa Renรฉ Nussbaumer
    @param nodegroup: A Node object to fill
1895 095e71aa Renรฉ Nussbaumer
    @return a copy of the node's ndparams with defaults filled
1896 095e71aa Renรฉ Nussbaumer

1897 095e71aa Renรฉ Nussbaumer
    """
1898 095e71aa Renรฉ Nussbaumer
    return self.SimpleFillND(nodegroup.FillND(node))
1899 095e71aa Renรฉ Nussbaumer
1900 6b2a2942 Petr Pudlak
  def FillNDGroup(self, nodegroup):
1901 6b2a2942 Petr Pudlak
    """Return filled out ndparams for just L{objects.NodeGroup}
1902 6b2a2942 Petr Pudlak

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

1907 6b2a2942 Petr Pudlak
    """
1908 6b2a2942 Petr Pudlak
    return self.SimpleFillND(nodegroup.SimpleFillND({}))
1909 6b2a2942 Petr Pudlak
1910 095e71aa Renรฉ Nussbaumer
  def SimpleFillND(self, ndparams):
1911 095e71aa Renรฉ Nussbaumer
    """Fill a given ndparams dict with defaults.
1912 095e71aa Renรฉ Nussbaumer

1913 095e71aa Renรฉ Nussbaumer
    @type ndparams: dict
1914 095e71aa Renรฉ Nussbaumer
    @param ndparams: the dict to fill
1915 095e71aa Renรฉ Nussbaumer
    @rtype: dict
1916 095e71aa Renรฉ Nussbaumer
    @return: a copy of the passed in ndparams with missing keys filled
1917 095e71aa Renรฉ Nussbaumer
        from the cluster defaults
1918 095e71aa Renรฉ Nussbaumer

1919 095e71aa Renรฉ Nussbaumer
    """
1920 095e71aa Renรฉ Nussbaumer
    return FillDict(self.ndparams, ndparams)
1921 095e71aa Renรฉ Nussbaumer
1922 918eb80b Agata Murawska
  def SimpleFillIPolicy(self, ipolicy):
1923 918eb80b Agata Murawska
    """ Fill instance policy dict with defaults.
1924 918eb80b Agata Murawska

1925 918eb80b Agata Murawska
    @type ipolicy: dict
1926 918eb80b Agata Murawska
    @param ipolicy: the dict to fill
1927 918eb80b Agata Murawska
    @rtype: dict
1928 918eb80b Agata Murawska
    @return: a copy of passed ipolicy with missing keys filled from
1929 918eb80b Agata Murawska
      the cluster defaults
1930 918eb80b Agata Murawska

1931 918eb80b Agata Murawska
    """
1932 2cc673a3 Iustin Pop
    return FillIPolicy(self.ipolicy, ipolicy)
1933 918eb80b Agata Murawska
1934 ebe93784 Helga Velroyen
  def IsDiskTemplateEnabled(self, disk_template):
1935 ebe93784 Helga Velroyen
    """Checks if a particular disk template is enabled.
1936 ebe93784 Helga Velroyen

1937 ebe93784 Helga Velroyen
    """
1938 ebe93784 Helga Velroyen
    return utils.storage.IsDiskTemplateEnabled(
1939 ebe93784 Helga Velroyen
        disk_template, self.enabled_disk_templates)
1940 ebe93784 Helga Velroyen
1941 ebe93784 Helga Velroyen
  def IsFileStorageEnabled(self):
1942 ebe93784 Helga Velroyen
    """Checks if file storage is enabled.
1943 ebe93784 Helga Velroyen

1944 ebe93784 Helga Velroyen
    """
1945 ebe93784 Helga Velroyen
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
1946 ebe93784 Helga Velroyen
1947 ebe93784 Helga Velroyen
  def IsSharedFileStorageEnabled(self):
1948 ebe93784 Helga Velroyen
    """Checks if shared file storage is enabled.
1949 ebe93784 Helga Velroyen

1950 ebe93784 Helga Velroyen
    """
1951 ebe93784 Helga Velroyen
    return utils.storage.IsSharedFileStorageEnabled(
1952 ebe93784 Helga Velroyen
        self.enabled_disk_templates)
1953 ebe93784 Helga Velroyen
1954 5c947f38 Iustin Pop
1955 96acbc09 Michael Hanselmann
class BlockDevStatus(ConfigObject):
1956 96acbc09 Michael Hanselmann
  """Config object representing the status of a block device."""
1957 96acbc09 Michael Hanselmann
  __slots__ = [
1958 96acbc09 Michael Hanselmann
    "dev_path",
1959 96acbc09 Michael Hanselmann
    "major",
1960 96acbc09 Michael Hanselmann
    "minor",
1961 96acbc09 Michael Hanselmann
    "sync_percent",
1962 96acbc09 Michael Hanselmann
    "estimated_time",
1963 96acbc09 Michael Hanselmann
    "is_degraded",
1964 f208978a Michael Hanselmann
    "ldisk_status",
1965 96acbc09 Michael Hanselmann
    ]
1966 96acbc09 Michael Hanselmann
1967 96acbc09 Michael Hanselmann
1968 2d76b580 Michael Hanselmann
class ImportExportStatus(ConfigObject):
1969 2d76b580 Michael Hanselmann
  """Config object representing the status of an import or export."""
1970 2d76b580 Michael Hanselmann
  __slots__ = [
1971 2d76b580 Michael Hanselmann
    "recent_output",
1972 2d76b580 Michael Hanselmann
    "listen_port",
1973 2d76b580 Michael Hanselmann
    "connected",
1974 c08d76f5 Michael Hanselmann
    "progress_mbytes",
1975 c08d76f5 Michael Hanselmann
    "progress_throughput",
1976 c08d76f5 Michael Hanselmann
    "progress_eta",
1977 c08d76f5 Michael Hanselmann
    "progress_percent",
1978 2d76b580 Michael Hanselmann
    "exit_status",
1979 2d76b580 Michael Hanselmann
    "error_message",
1980 2d76b580 Michael Hanselmann
    ] + _TIMESTAMPS
1981 2d76b580 Michael Hanselmann
1982 2d76b580 Michael Hanselmann
1983 eb630f50 Michael Hanselmann
class ImportExportOptions(ConfigObject):
1984 eb630f50 Michael Hanselmann
  """Options for import/export daemon
1985 eb630f50 Michael Hanselmann

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

1993 eb630f50 Michael Hanselmann
  """
1994 eb630f50 Michael Hanselmann
  __slots__ = [
1995 eb630f50 Michael Hanselmann
    "key_name",
1996 eb630f50 Michael Hanselmann
    "ca_pem",
1997 a5310c2a Michael Hanselmann
    "compress",
1998 af1d39b1 Michael Hanselmann
    "magic",
1999 855d2fc7 Michael Hanselmann
    "ipv6",
2000 4478301b Michael Hanselmann
    "connect_timeout",
2001 eb630f50 Michael Hanselmann
    ]
2002 eb630f50 Michael Hanselmann
2003 eb630f50 Michael Hanselmann
2004 18d750b9 Guido Trotter
class ConfdRequest(ConfigObject):
2005 18d750b9 Guido Trotter
  """Object holding a confd request.
2006 18d750b9 Guido Trotter

2007 18d750b9 Guido Trotter
  @ivar protocol: confd protocol version
2008 18d750b9 Guido Trotter
  @ivar type: confd query type
2009 18d750b9 Guido Trotter
  @ivar query: query request
2010 18d750b9 Guido Trotter
  @ivar rsalt: requested reply salt
2011 18d750b9 Guido Trotter

2012 18d750b9 Guido Trotter
  """
2013 18d750b9 Guido Trotter
  __slots__ = [
2014 18d750b9 Guido Trotter
    "protocol",
2015 18d750b9 Guido Trotter
    "type",
2016 18d750b9 Guido Trotter
    "query",
2017 18d750b9 Guido Trotter
    "rsalt",
2018 18d750b9 Guido Trotter
    ]
2019 18d750b9 Guido Trotter
2020 18d750b9 Guido Trotter
2021 18d750b9 Guido Trotter
class ConfdReply(ConfigObject):
2022 18d750b9 Guido Trotter
  """Object holding a confd reply.
2023 18d750b9 Guido Trotter

2024 18d750b9 Guido Trotter
  @ivar protocol: confd protocol version
2025 18d750b9 Guido Trotter
  @ivar status: reply status code (ok, error)
2026 18d750b9 Guido Trotter
  @ivar answer: confd query reply
2027 18d750b9 Guido Trotter
  @ivar serial: configuration serial number
2028 18d750b9 Guido Trotter

2029 18d750b9 Guido Trotter
  """
2030 18d750b9 Guido Trotter
  __slots__ = [
2031 18d750b9 Guido Trotter
    "protocol",
2032 18d750b9 Guido Trotter
    "status",
2033 18d750b9 Guido Trotter
    "answer",
2034 18d750b9 Guido Trotter
    "serial",
2035 18d750b9 Guido Trotter
    ]
2036 18d750b9 Guido Trotter
2037 18d750b9 Guido Trotter
2038 707f23b5 Michael Hanselmann
class QueryFieldDefinition(ConfigObject):
2039 707f23b5 Michael Hanselmann
  """Object holding a query field definition.
2040 707f23b5 Michael Hanselmann

2041 24d6d3e2 Michael Hanselmann
  @ivar name: Field name
2042 707f23b5 Michael Hanselmann
  @ivar title: Human-readable title
2043 707f23b5 Michael Hanselmann
  @ivar kind: Field type
2044 1ae17369 Michael Hanselmann
  @ivar doc: Human-readable description
2045 707f23b5 Michael Hanselmann

2046 707f23b5 Michael Hanselmann
  """
2047 707f23b5 Michael Hanselmann
  __slots__ = [
2048 707f23b5 Michael Hanselmann
    "name",
2049 707f23b5 Michael Hanselmann
    "title",
2050 707f23b5 Michael Hanselmann
    "kind",
2051 1ae17369 Michael Hanselmann
    "doc",
2052 707f23b5 Michael Hanselmann
    ]
2053 707f23b5 Michael Hanselmann
2054 707f23b5 Michael Hanselmann
2055 0538c375 Michael Hanselmann
class _QueryResponseBase(ConfigObject):
2056 0538c375 Michael Hanselmann
  __slots__ = [
2057 0538c375 Michael Hanselmann
    "fields",
2058 0538c375 Michael Hanselmann
    ]
2059 0538c375 Michael Hanselmann
2060 0538c375 Michael Hanselmann
  def ToDict(self):
2061 0538c375 Michael Hanselmann
    """Custom function for serializing.
2062 0538c375 Michael Hanselmann

2063 0538c375 Michael Hanselmann
    """
2064 0538c375 Michael Hanselmann
    mydict = super(_QueryResponseBase, self).ToDict()
2065 fe502d25 Iustin Pop
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2066 0538c375 Michael Hanselmann
    return mydict
2067 0538c375 Michael Hanselmann
2068 0538c375 Michael Hanselmann
  @classmethod
2069 0538c375 Michael Hanselmann
  def FromDict(cls, val):
2070 0538c375 Michael Hanselmann
    """Custom function for de-serializing.
2071 0538c375 Michael Hanselmann

2072 0538c375 Michael Hanselmann
    """
2073 0538c375 Michael Hanselmann
    obj = super(_QueryResponseBase, cls).FromDict(val)
2074 473ab806 Michael Hanselmann
    obj.fields = \
2075 fe502d25 Iustin Pop
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2076 0538c375 Michael Hanselmann
    return obj
2077 0538c375 Michael Hanselmann
2078 0538c375 Michael Hanselmann
2079 0538c375 Michael Hanselmann
class QueryResponse(_QueryResponseBase):
2080 24d6d3e2 Michael Hanselmann
  """Object holding the response to a query.
2081 24d6d3e2 Michael Hanselmann

2082 24d6d3e2 Michael Hanselmann
  @ivar fields: List of L{QueryFieldDefinition} objects
2083 24d6d3e2 Michael Hanselmann
  @ivar data: Requested data
2084 24d6d3e2 Michael Hanselmann

2085 24d6d3e2 Michael Hanselmann
  """
2086 24d6d3e2 Michael Hanselmann
  __slots__ = [
2087 24d6d3e2 Michael Hanselmann
    "data",
2088 24d6d3e2 Michael Hanselmann
    ]
2089 24d6d3e2 Michael Hanselmann
2090 24d6d3e2 Michael Hanselmann
2091 24d6d3e2 Michael Hanselmann
class QueryFieldsRequest(ConfigObject):
2092 24d6d3e2 Michael Hanselmann
  """Object holding a request for querying available fields.
2093 24d6d3e2 Michael Hanselmann

2094 24d6d3e2 Michael Hanselmann
  """
2095 24d6d3e2 Michael Hanselmann
  __slots__ = [
2096 24d6d3e2 Michael Hanselmann
    "what",
2097 24d6d3e2 Michael Hanselmann
    "fields",
2098 24d6d3e2 Michael Hanselmann
    ]
2099 24d6d3e2 Michael Hanselmann
2100 24d6d3e2 Michael Hanselmann
2101 0538c375 Michael Hanselmann
class QueryFieldsResponse(_QueryResponseBase):
2102 24d6d3e2 Michael Hanselmann
  """Object holding the response to a query for fields.
2103 24d6d3e2 Michael Hanselmann

2104 24d6d3e2 Michael Hanselmann
  @ivar fields: List of L{QueryFieldDefinition} objects
2105 24d6d3e2 Michael Hanselmann

2106 24d6d3e2 Michael Hanselmann
  """
2107 5ae4945a Iustin Pop
  __slots__ = []
2108 24d6d3e2 Michael Hanselmann
2109 24d6d3e2 Michael Hanselmann
2110 6a1434d7 Andrea Spadaccini
class MigrationStatus(ConfigObject):
2111 6a1434d7 Andrea Spadaccini
  """Object holding the status of a migration.
2112 6a1434d7 Andrea Spadaccini

2113 6a1434d7 Andrea Spadaccini
  """
2114 6a1434d7 Andrea Spadaccini
  __slots__ = [
2115 6a1434d7 Andrea Spadaccini
    "status",
2116 6a1434d7 Andrea Spadaccini
    "transferred_ram",
2117 6a1434d7 Andrea Spadaccini
    "total_ram",
2118 6a1434d7 Andrea Spadaccini
    ]
2119 6a1434d7 Andrea Spadaccini
2120 6a1434d7 Andrea Spadaccini
2121 25ce3ec4 Michael Hanselmann
class InstanceConsole(ConfigObject):
2122 25ce3ec4 Michael Hanselmann
  """Object describing how to access the console of an instance.
2123 25ce3ec4 Michael Hanselmann

2124 25ce3ec4 Michael Hanselmann
  """
2125 25ce3ec4 Michael Hanselmann
  __slots__ = [
2126 25ce3ec4 Michael Hanselmann
    "instance",
2127 25ce3ec4 Michael Hanselmann
    "kind",
2128 25ce3ec4 Michael Hanselmann
    "message",
2129 25ce3ec4 Michael Hanselmann
    "host",
2130 25ce3ec4 Michael Hanselmann
    "port",
2131 25ce3ec4 Michael Hanselmann
    "user",
2132 25ce3ec4 Michael Hanselmann
    "command",
2133 25ce3ec4 Michael Hanselmann
    "display",
2134 25ce3ec4 Michael Hanselmann
    ]
2135 25ce3ec4 Michael Hanselmann
2136 25ce3ec4 Michael Hanselmann
  def Validate(self):
2137 25ce3ec4 Michael Hanselmann
    """Validates contents of this object.
2138 25ce3ec4 Michael Hanselmann

2139 25ce3ec4 Michael Hanselmann
    """
2140 25ce3ec4 Michael Hanselmann
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2141 25ce3ec4 Michael Hanselmann
    assert self.instance, "Missing instance name"
2142 4d2cdb5a Andrea Spadaccini
    assert self.message or self.kind in [constants.CONS_SSH,
2143 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2144 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_VNC]
2145 25ce3ec4 Michael Hanselmann
    assert self.host or self.kind == constants.CONS_MESSAGE
2146 25ce3ec4 Michael Hanselmann
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2147 25ce3ec4 Michael Hanselmann
                                      constants.CONS_SSH]
2148 25ce3ec4 Michael Hanselmann
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2149 4d2cdb5a Andrea Spadaccini
                                      constants.CONS_SPICE,
2150 25ce3ec4 Michael Hanselmann
                                      constants.CONS_VNC]
2151 25ce3ec4 Michael Hanselmann
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2152 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2153 25ce3ec4 Michael Hanselmann
                                         constants.CONS_VNC]
2154 25ce3ec4 Michael Hanselmann
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2155 4d2cdb5a Andrea Spadaccini
                                         constants.CONS_SPICE,
2156 25ce3ec4 Michael Hanselmann
                                         constants.CONS_SSH]
2157 25ce3ec4 Michael Hanselmann
    return True
2158 25ce3ec4 Michael Hanselmann
2159 25ce3ec4 Michael Hanselmann
2160 8140e24f Dimitris Aragiorgis
class Network(TaggableObject):
2161 eaa4c57c Dimitris Aragiorgis
  """Object representing a network definition for ganeti.
2162 eaa4c57c Dimitris Aragiorgis

2163 eaa4c57c Dimitris Aragiorgis
  """
2164 eaa4c57c Dimitris Aragiorgis
  __slots__ = [
2165 eaa4c57c Dimitris Aragiorgis
    "name",
2166 eaa4c57c Dimitris Aragiorgis
    "serial_no",
2167 eaa4c57c Dimitris Aragiorgis
    "mac_prefix",
2168 eaa4c57c Dimitris Aragiorgis
    "network",
2169 eaa4c57c Dimitris Aragiorgis
    "network6",
2170 eaa4c57c Dimitris Aragiorgis
    "gateway",
2171 eaa4c57c Dimitris Aragiorgis
    "gateway6",
2172 eaa4c57c Dimitris Aragiorgis
    "reservations",
2173 eaa4c57c Dimitris Aragiorgis
    "ext_reservations",
2174 eaa4c57c Dimitris Aragiorgis
    ] + _TIMESTAMPS + _UUID
2175 eaa4c57c Dimitris Aragiorgis
2176 7e8f03e3 Dimitris Aragiorgis
  def HooksDict(self, prefix=""):
2177 d89168ff Guido Trotter
    """Export a dictionary used by hooks with a network's information.
2178 d89168ff Guido Trotter

2179 d89168ff Guido Trotter
    @type prefix: String
2180 d89168ff Guido Trotter
    @param prefix: Prefix to prepend to the dict entries
2181 d89168ff Guido Trotter

2182 d89168ff Guido Trotter
    """
2183 d89168ff Guido Trotter
    result = {
2184 7e8f03e3 Dimitris Aragiorgis
      "%sNETWORK_NAME" % prefix: self.name,
2185 d89168ff Guido Trotter
      "%sNETWORK_UUID" % prefix: self.uuid,
2186 5a76adf7 Dimitris Aragiorgis
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2187 d89168ff Guido Trotter
    }
2188 d89168ff Guido Trotter
    if self.network:
2189 d89168ff Guido Trotter
      result["%sNETWORK_SUBNET" % prefix] = self.network
2190 d89168ff Guido Trotter
    if self.gateway:
2191 d89168ff Guido Trotter
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2192 d89168ff Guido Trotter
    if self.network6:
2193 d89168ff Guido Trotter
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2194 d89168ff Guido Trotter
    if self.gateway6:
2195 d89168ff Guido Trotter
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2196 d89168ff Guido Trotter
    if self.mac_prefix:
2197 d89168ff Guido Trotter
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2198 d89168ff Guido Trotter
2199 d89168ff Guido Trotter
    return result
2200 d89168ff Guido Trotter
2201 5cfa6c37 Dimitris Aragiorgis
  @classmethod
2202 5cfa6c37 Dimitris Aragiorgis
  def FromDict(cls, val):
2203 5cfa6c37 Dimitris Aragiorgis
    """Custom function for networks.
2204 5cfa6c37 Dimitris Aragiorgis

2205 48616625 Dimitris Aragiorgis
    Remove deprecated network_type and family.
2206 5cfa6c37 Dimitris Aragiorgis

2207 5cfa6c37 Dimitris Aragiorgis
    """
2208 5cfa6c37 Dimitris Aragiorgis
    if "network_type" in val:
2209 5cfa6c37 Dimitris Aragiorgis
      del val["network_type"]
2210 48616625 Dimitris Aragiorgis
    if "family" in val:
2211 48616625 Dimitris Aragiorgis
      del val["family"]
2212 5cfa6c37 Dimitris Aragiorgis
    obj = super(Network, cls).FromDict(val)
2213 5cfa6c37 Dimitris Aragiorgis
    return obj
2214 5cfa6c37 Dimitris Aragiorgis
2215 eaa4c57c Dimitris Aragiorgis
2216 a8083063 Iustin Pop
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2217 a8083063 Iustin Pop
  """Simple wrapper over ConfigParse that allows serialization.
2218 a8083063 Iustin Pop

2219 a8083063 Iustin Pop
  This class is basically ConfigParser.SafeConfigParser with two
2220 a8083063 Iustin Pop
  additional methods that allow it to serialize/unserialize to/from a
2221 a8083063 Iustin Pop
  buffer.
2222 a8083063 Iustin Pop

2223 a8083063 Iustin Pop
  """
2224 a8083063 Iustin Pop
  def Dumps(self):
2225 a8083063 Iustin Pop
    """Dump this instance and return the string representation."""
2226 a8083063 Iustin Pop
    buf = StringIO()
2227 a8083063 Iustin Pop
    self.write(buf)
2228 a8083063 Iustin Pop
    return buf.getvalue()
2229 a8083063 Iustin Pop
2230 b39bf4bb Guido Trotter
  @classmethod
2231 b39bf4bb Guido Trotter
  def Loads(cls, data):
2232 a8083063 Iustin Pop
    """Load data from a string."""
2233 a8083063 Iustin Pop
    buf = StringIO(data)
2234 b39bf4bb Guido Trotter
    cfp = cls()
2235 a8083063 Iustin Pop
    cfp.readfp(buf)
2236 a8083063 Iustin Pop
    return cfp
2237 59726e15 Bernardo Dal Seno
2238 59726e15 Bernardo Dal Seno
2239 59726e15 Bernardo Dal Seno
class LvmPvInfo(ConfigObject):
2240 59726e15 Bernardo Dal Seno
  """Information about an LVM physical volume (PV).
2241 59726e15 Bernardo Dal Seno

2242 59726e15 Bernardo Dal Seno
  @type name: string
2243 59726e15 Bernardo Dal Seno
  @ivar name: name of the PV
2244 59726e15 Bernardo Dal Seno
  @type vg_name: string
2245 59726e15 Bernardo Dal Seno
  @ivar vg_name: name of the volume group containing the PV
2246 59726e15 Bernardo Dal Seno
  @type size: float
2247 59726e15 Bernardo Dal Seno
  @ivar size: size of the PV in MiB
2248 59726e15 Bernardo Dal Seno
  @type free: float
2249 59726e15 Bernardo Dal Seno
  @ivar free: free space in the PV, in MiB
2250 59726e15 Bernardo Dal Seno
  @type attributes: string
2251 59726e15 Bernardo Dal Seno
  @ivar attributes: PV attributes
2252 b496abdb Bernardo Dal Seno
  @type lv_list: list of strings
2253 b496abdb Bernardo Dal Seno
  @ivar lv_list: names of the LVs hosted on the PV
2254 59726e15 Bernardo Dal Seno
  """
2255 59726e15 Bernardo Dal Seno
  __slots__ = [
2256 59726e15 Bernardo Dal Seno
    "name",
2257 59726e15 Bernardo Dal Seno
    "vg_name",
2258 59726e15 Bernardo Dal Seno
    "size",
2259 59726e15 Bernardo Dal Seno
    "free",
2260 59726e15 Bernardo Dal Seno
    "attributes",
2261 b496abdb Bernardo Dal Seno
    "lv_list"
2262 59726e15 Bernardo Dal Seno
    ]
2263 59726e15 Bernardo Dal Seno
2264 59726e15 Bernardo Dal Seno
  def IsEmpty(self):
2265 59726e15 Bernardo Dal Seno
    """Is this PV empty?
2266 59726e15 Bernardo Dal Seno

2267 59726e15 Bernardo Dal Seno
    """
2268 59726e15 Bernardo Dal Seno
    return self.size <= (self.free + 1)
2269 59726e15 Bernardo Dal Seno
2270 59726e15 Bernardo Dal Seno
  def IsAllocatable(self):
2271 59726e15 Bernardo Dal Seno
    """Is this PV allocatable?
2272 59726e15 Bernardo Dal Seno

2273 59726e15 Bernardo Dal Seno
    """
2274 59726e15 Bernardo Dal Seno
    return ("a" in self.attributes)