Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 510f672f

History | View | Annotate | Download (66.3 kB)

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

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

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

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

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

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

102 af9fb4cc René Nussbaumer
  @see: L{FillDict} for parameters and return value
103 57987785 René Nussbaumer

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

341 ff9c047c Iustin Pop
    This replaces the tags set with a list.
342 ff9c047c Iustin Pop

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

859 cd46491f René Nussbaumer
    """
860 cd46491f René Nussbaumer
    if disk_template not in constants.DISK_TEMPLATES:
861 cd46491f René Nussbaumer
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
862 cd46491f René Nussbaumer
863 cd46491f René Nussbaumer
    assert disk_template in disk_params
864 cd46491f René Nussbaumer
865 cd46491f René Nussbaumer
    result = list()
866 cd46491f René Nussbaumer
    dt_params = disk_params[disk_template]
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 52f93ffd Michael Hanselmann
    elif disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
895 6da90c0a Helga Velroyen
      result.append(constants.DISK_LD_DEFAULTS[disk_template])
896 cd46491f René Nussbaumer
897 cd46491f René Nussbaumer
    elif disk_template == constants.DT_PLAIN:
898 6da90c0a Helga Velroyen
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
899 cd46491f René Nussbaumer
        constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
900 52f93ffd Michael Hanselmann
        }))
901 cd46491f René Nussbaumer
902 cd46491f René Nussbaumer
    elif disk_template == constants.DT_BLOCK:
903 6da90c0a Helga Velroyen
      result.append(constants.DISK_LD_DEFAULTS[constants.DT_BLOCK])
904 cd46491f René Nussbaumer
905 cd46491f René Nussbaumer
    elif disk_template == constants.DT_RBD:
906 6da90c0a Helga Velroyen
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_RBD], {
907 3c286190 Dimitris Aragiorgis
        constants.LDP_POOL: dt_params[constants.RBD_POOL],
908 9b9e088c Raffa Santi
        constants.LDP_ACCESS: dt_params[constants.RBD_ACCESS],
909 52f93ffd Michael Hanselmann
        }))
910 cd46491f René Nussbaumer
911 938adc87 Constantinos Venetsanopoulos
    elif disk_template == constants.DT_EXT:
912 6da90c0a Helga Velroyen
      result.append(constants.DISK_LD_DEFAULTS[constants.DT_EXT])
913 938adc87 Constantinos Venetsanopoulos
914 cd46491f René Nussbaumer
    return result
915 cd46491f René Nussbaumer
916 a8083063 Iustin Pop
917 918eb80b Agata Murawska
class InstancePolicy(ConfigObject):
918 ffa339ca Iustin Pop
  """Config object representing instance policy limits dictionary.
919 918eb80b Agata Murawska

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

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

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

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

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

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

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

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

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

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

1059 ff6c5e55 Iustin Pop
    Currently we expect all parameters to be float values.
1060 ff6c5e55 Iustin Pop

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1263 b41b3516 Iustin Pop
  @type supported_parameters: list
1264 b41b3516 Iustin Pop
  @ivar supported_parameters: a list of tuples, name and description,
1265 b41b3516 Iustin Pop
      containing the supported parameters by this OS
1266 b41b3516 Iustin Pop

1267 870dc44c Iustin Pop
  @type VARIANT_DELIM: string
1268 870dc44c Iustin Pop
  @cvar VARIANT_DELIM: the variant delimiter
1269 870dc44c Iustin Pop

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

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

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

1305 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1306 870dc44c Iustin Pop

1307 870dc44c Iustin Pop
    """
1308 870dc44c Iustin Pop
    return cls.SplitNameVariant(name)[0]
1309 870dc44c Iustin Pop
1310 870dc44c Iustin Pop
  @classmethod
1311 870dc44c Iustin Pop
  def GetVariant(cls, name):
1312 870dc44c Iustin Pop
    """Returns the variant the os (without the base name).
1313 870dc44c Iustin Pop

1314 870dc44c Iustin Pop
    @param name: the OS (unprocessed) name
1315 870dc44c Iustin Pop

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

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

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

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

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

1375 634d30f4 Michael Hanselmann
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1376 634d30f4 Michael Hanselmann
  @ivar hv_state_static: Hypervisor state overriden by user
1377 634d30f4 Michael Hanselmann
  @ivar disk_state: Disk state (e.g. free space)
1378 634d30f4 Michael Hanselmann
  @ivar disk_state_static: Disk state overriden by user
1379 634d30f4 Michael Hanselmann

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

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

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

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

1479 c60abd62 Guido Trotter
    This discards the members object, which gets recalculated and is only kept
1480 c60abd62 Guido Trotter
    in memory.
1481 24a3707f Guido Trotter

1482 24a3707f Guido Trotter
    """
1483 24a3707f Guido Trotter
    mydict = super(NodeGroup, self).ToDict()
1484 24a3707f Guido Trotter
    del mydict["members"]
1485 24a3707f Guido Trotter
    return mydict
1486 24a3707f Guido Trotter
1487 24a3707f Guido Trotter
  @classmethod
1488 24a3707f Guido Trotter
  def FromDict(cls, val):
1489 24a3707f Guido Trotter
    """Custom function for nodegroup.
1490 24a3707f Guido Trotter

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

1493 24a3707f Guido Trotter
    """
1494 24a3707f Guido Trotter
    obj = super(NodeGroup, cls).FromDict(val)
1495 24a3707f Guido Trotter
    obj.members = []
1496 24a3707f Guido Trotter
    return obj
1497 24a3707f Guido Trotter
1498 095e71aa René Nussbaumer
  def UpgradeConfig(self):
1499 095e71aa René Nussbaumer
    """Fill defaults for missing configuration values.
1500 095e71aa René Nussbaumer

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

1527 095e71aa René Nussbaumer
    @type node: L{objects.Node}
1528 095e71aa René Nussbaumer
    @param node: A Node object to fill
1529 095e71aa René Nussbaumer
    @return a copy of the node's ndparams with defaults filled
1530 095e71aa René Nussbaumer

1531 095e71aa René Nussbaumer
    """
1532 095e71aa René Nussbaumer
    return self.SimpleFillND(node.ndparams)
1533 095e71aa René Nussbaumer
1534 095e71aa René Nussbaumer
  def SimpleFillND(self, ndparams):
1535 095e71aa René Nussbaumer
    """Fill a given ndparams dict with defaults.
1536 095e71aa René Nussbaumer

1537 095e71aa René Nussbaumer
    @type ndparams: dict
1538 095e71aa René Nussbaumer
    @param ndparams: the dict to fill
1539 095e71aa René Nussbaumer
    @rtype: dict
1540 095e71aa René Nussbaumer
    @return: a copy of the passed in ndparams with missing keys filled
1541 e6e88de6 Adeodato Simo
        from the node group defaults
1542 095e71aa René Nussbaumer

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

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

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

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

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

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

1751 8a147bba René Nussbaumer
    @param diskparams: The diskparams
1752 8a147bba René Nussbaumer
    @return: The defaults dict
1753 8a147bba René Nussbaumer

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1898 095e71aa René Nussbaumer
    """
1899 095e71aa René Nussbaumer
    return self.SimpleFillND(nodegroup.FillND(node))
1900 095e71aa René Nussbaumer
1901 095e71aa René Nussbaumer
  def SimpleFillND(self, ndparams):
1902 095e71aa René Nussbaumer
    """Fill a given ndparams dict with defaults.
1903 095e71aa René Nussbaumer

1904 095e71aa René Nussbaumer
    @type ndparams: dict
1905 095e71aa René Nussbaumer
    @param ndparams: the dict to fill
1906 095e71aa René Nussbaumer
    @rtype: dict
1907 095e71aa René Nussbaumer
    @return: a copy of the passed in ndparams with missing keys filled
1908 095e71aa René Nussbaumer
        from the cluster defaults
1909 095e71aa René Nussbaumer

1910 095e71aa René Nussbaumer
    """
1911 095e71aa René Nussbaumer
    return FillDict(self.ndparams, ndparams)
1912 095e71aa René Nussbaumer
1913 918eb80b Agata Murawska
  def SimpleFillIPolicy(self, ipolicy):
1914 918eb80b Agata Murawska
    """ Fill instance policy dict with defaults.
1915 918eb80b Agata Murawska

1916 918eb80b Agata Murawska
    @type ipolicy: dict
1917 918eb80b Agata Murawska
    @param ipolicy: the dict to fill
1918 918eb80b Agata Murawska
    @rtype: dict
1919 918eb80b Agata Murawska
    @return: a copy of passed ipolicy with missing keys filled from
1920 918eb80b Agata Murawska
      the cluster defaults
1921 918eb80b Agata Murawska

1922 918eb80b Agata Murawska
    """
1923 2cc673a3 Iustin Pop
    return FillIPolicy(self.ipolicy, ipolicy)
1924 918eb80b Agata Murawska
1925 ebe93784 Helga Velroyen
  def IsDiskTemplateEnabled(self, disk_template):
1926 ebe93784 Helga Velroyen
    """Checks if a particular disk template is enabled.
1927 ebe93784 Helga Velroyen

1928 ebe93784 Helga Velroyen
    """
1929 ebe93784 Helga Velroyen
    return utils.storage.IsDiskTemplateEnabled(
1930 ebe93784 Helga Velroyen
        disk_template, self.enabled_disk_templates)
1931 ebe93784 Helga Velroyen
1932 ebe93784 Helga Velroyen
  def IsFileStorageEnabled(self):
1933 ebe93784 Helga Velroyen
    """Checks if file storage is enabled.
1934 ebe93784 Helga Velroyen

1935 ebe93784 Helga Velroyen
    """
1936 ebe93784 Helga Velroyen
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
1937 ebe93784 Helga Velroyen
1938 ebe93784 Helga Velroyen
  def IsSharedFileStorageEnabled(self):
1939 ebe93784 Helga Velroyen
    """Checks if shared file storage is enabled.
1940 ebe93784 Helga Velroyen

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

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

1984 eb630f50 Michael Hanselmann
  """
1985 eb630f50 Michael Hanselmann
  __slots__ = [
1986 eb630f50 Michael Hanselmann
    "key_name",
1987 eb630f50 Michael Hanselmann
    "ca_pem",
1988 a5310c2a Michael Hanselmann
    "compress",
1989 af1d39b1 Michael Hanselmann
    "magic",
1990 855d2fc7 Michael Hanselmann
    "ipv6",
1991 4478301b Michael Hanselmann
    "connect_timeout",
1992 eb630f50 Michael Hanselmann
    ]
1993 eb630f50 Michael Hanselmann
1994 eb630f50 Michael Hanselmann
1995 18d750b9 Guido Trotter
class ConfdRequest(ConfigObject):
1996 18d750b9 Guido Trotter
  """Object holding a confd request.
1997 18d750b9 Guido Trotter

1998 18d750b9 Guido Trotter
  @ivar protocol: confd protocol version
1999 18d750b9 Guido Trotter
  @ivar type: confd query type
2000 18d750b9 Guido Trotter
  @ivar query: query request
2001 18d750b9 Guido Trotter
  @ivar rsalt: requested reply salt
2002 18d750b9 Guido Trotter

2003 18d750b9 Guido Trotter
  """
2004 18d750b9 Guido Trotter
  __slots__ = [
2005 18d750b9 Guido Trotter
    "protocol",
2006 18d750b9 Guido Trotter
    "type",
2007 18d750b9 Guido Trotter
    "query",
2008 18d750b9 Guido Trotter
    "rsalt",
2009 18d750b9 Guido Trotter
    ]
2010 18d750b9 Guido Trotter
2011 18d750b9 Guido Trotter
2012 18d750b9 Guido Trotter
class ConfdReply(ConfigObject):
2013 18d750b9 Guido Trotter
  """Object holding a confd reply.
2014 18d750b9 Guido Trotter

2015 18d750b9 Guido Trotter
  @ivar protocol: confd protocol version
2016 18d750b9 Guido Trotter
  @ivar status: reply status code (ok, error)
2017 18d750b9 Guido Trotter
  @ivar answer: confd query reply
2018 18d750b9 Guido Trotter
  @ivar serial: configuration serial number
2019 18d750b9 Guido Trotter

2020 18d750b9 Guido Trotter
  """
2021 18d750b9 Guido Trotter
  __slots__ = [
2022 18d750b9 Guido Trotter
    "protocol",
2023 18d750b9 Guido Trotter
    "status",
2024 18d750b9 Guido Trotter
    "answer",
2025 18d750b9 Guido Trotter
    "serial",
2026 18d750b9 Guido Trotter
    ]
2027 18d750b9 Guido Trotter
2028 18d750b9 Guido Trotter
2029 707f23b5 Michael Hanselmann
class QueryFieldDefinition(ConfigObject):
2030 707f23b5 Michael Hanselmann
  """Object holding a query field definition.
2031 707f23b5 Michael Hanselmann

2032 24d6d3e2 Michael Hanselmann
  @ivar name: Field name
2033 707f23b5 Michael Hanselmann
  @ivar title: Human-readable title
2034 707f23b5 Michael Hanselmann
  @ivar kind: Field type
2035 1ae17369 Michael Hanselmann
  @ivar doc: Human-readable description
2036 707f23b5 Michael Hanselmann

2037 707f23b5 Michael Hanselmann
  """
2038 707f23b5 Michael Hanselmann
  __slots__ = [
2039 707f23b5 Michael Hanselmann
    "name",
2040 707f23b5 Michael Hanselmann
    "title",
2041 707f23b5 Michael Hanselmann
    "kind",
2042 1ae17369 Michael Hanselmann
    "doc",
2043 707f23b5 Michael Hanselmann
    ]
2044 707f23b5 Michael Hanselmann
2045 707f23b5 Michael Hanselmann
2046 0538c375 Michael Hanselmann
class _QueryResponseBase(ConfigObject):
2047 0538c375 Michael Hanselmann
  __slots__ = [
2048 0538c375 Michael Hanselmann
    "fields",
2049 0538c375 Michael Hanselmann
    ]
2050 0538c375 Michael Hanselmann
2051 0538c375 Michael Hanselmann
  def ToDict(self):
2052 0538c375 Michael Hanselmann
    """Custom function for serializing.
2053 0538c375 Michael Hanselmann

2054 0538c375 Michael Hanselmann
    """
2055 0538c375 Michael Hanselmann
    mydict = super(_QueryResponseBase, self).ToDict()
2056 fe502d25 Iustin Pop
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2057 0538c375 Michael Hanselmann
    return mydict
2058 0538c375 Michael Hanselmann
2059 0538c375 Michael Hanselmann
  @classmethod
2060 0538c375 Michael Hanselmann
  def FromDict(cls, val):
2061 0538c375 Michael Hanselmann
    """Custom function for de-serializing.
2062 0538c375 Michael Hanselmann

2063 0538c375 Michael Hanselmann
    """
2064 0538c375 Michael Hanselmann
    obj = super(_QueryResponseBase, cls).FromDict(val)
2065 473ab806 Michael Hanselmann
    obj.fields = \
2066 fe502d25 Iustin Pop
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2067 0538c375 Michael Hanselmann
    return obj
2068 0538c375 Michael Hanselmann
2069 0538c375 Michael Hanselmann
2070 0538c375 Michael Hanselmann
class QueryResponse(_QueryResponseBase):
2071 24d6d3e2 Michael Hanselmann
  """Object holding the response to a query.
2072 24d6d3e2 Michael Hanselmann

2073 24d6d3e2 Michael Hanselmann
  @ivar fields: List of L{QueryFieldDefinition} objects
2074 24d6d3e2 Michael Hanselmann
  @ivar data: Requested data
2075 24d6d3e2 Michael Hanselmann

2076 24d6d3e2 Michael Hanselmann
  """
2077 24d6d3e2 Michael Hanselmann
  __slots__ = [
2078 24d6d3e2 Michael Hanselmann
    "data",
2079 24d6d3e2 Michael Hanselmann
    ]
2080 24d6d3e2 Michael Hanselmann
2081 24d6d3e2 Michael Hanselmann
2082 24d6d3e2 Michael Hanselmann
class QueryFieldsRequest(ConfigObject):
2083 24d6d3e2 Michael Hanselmann
  """Object holding a request for querying available fields.
2084 24d6d3e2 Michael Hanselmann

2085 24d6d3e2 Michael Hanselmann
  """
2086 24d6d3e2 Michael Hanselmann
  __slots__ = [
2087 24d6d3e2 Michael Hanselmann
    "what",
2088 24d6d3e2 Michael Hanselmann
    "fields",
2089 24d6d3e2 Michael Hanselmann
    ]
2090 24d6d3e2 Michael Hanselmann
2091 24d6d3e2 Michael Hanselmann
2092 0538c375 Michael Hanselmann
class QueryFieldsResponse(_QueryResponseBase):
2093 24d6d3e2 Michael Hanselmann
  """Object holding the response to a query for fields.
2094 24d6d3e2 Michael Hanselmann

2095 24d6d3e2 Michael Hanselmann
  @ivar fields: List of L{QueryFieldDefinition} objects
2096 24d6d3e2 Michael Hanselmann

2097 24d6d3e2 Michael Hanselmann
  """
2098 5ae4945a Iustin Pop
  __slots__ = []
2099 24d6d3e2 Michael Hanselmann
2100 24d6d3e2 Michael Hanselmann
2101 6a1434d7 Andrea Spadaccini
class MigrationStatus(ConfigObject):
2102 6a1434d7 Andrea Spadaccini
  """Object holding the status of a migration.
2103 6a1434d7 Andrea Spadaccini

2104 6a1434d7 Andrea Spadaccini
  """
2105 6a1434d7 Andrea Spadaccini
  __slots__ = [
2106 6a1434d7 Andrea Spadaccini
    "status",
2107 6a1434d7 Andrea Spadaccini
    "transferred_ram",
2108 6a1434d7 Andrea Spadaccini
    "total_ram",
2109 6a1434d7 Andrea Spadaccini
    ]
2110 6a1434d7 Andrea Spadaccini
2111 6a1434d7 Andrea Spadaccini
2112 25ce3ec4 Michael Hanselmann
class InstanceConsole(ConfigObject):
2113 25ce3ec4 Michael Hanselmann
  """Object describing how to access the console of an instance.
2114 25ce3ec4 Michael Hanselmann

2115 25ce3ec4 Michael Hanselmann
  """
2116 25ce3ec4 Michael Hanselmann
  __slots__ = [
2117 25ce3ec4 Michael Hanselmann
    "instance",
2118 25ce3ec4 Michael Hanselmann
    "kind",
2119 25ce3ec4 Michael Hanselmann
    "message",
2120 25ce3ec4 Michael Hanselmann
    "host",
2121 25ce3ec4 Michael Hanselmann
    "port",
2122 25ce3ec4 Michael Hanselmann
    "user",
2123 25ce3ec4 Michael Hanselmann
    "command",
2124 25ce3ec4 Michael Hanselmann
    "display",
2125 25ce3ec4 Michael Hanselmann
    ]
2126 25ce3ec4 Michael Hanselmann
2127 25ce3ec4 Michael Hanselmann
  def Validate(self):
2128 25ce3ec4 Michael Hanselmann
    """Validates contents of this object.
2129 25ce3ec4 Michael Hanselmann

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

2154 eaa4c57c Dimitris Aragiorgis
  """
2155 eaa4c57c Dimitris Aragiorgis
  __slots__ = [
2156 eaa4c57c Dimitris Aragiorgis
    "name",
2157 eaa4c57c Dimitris Aragiorgis
    "serial_no",
2158 eaa4c57c Dimitris Aragiorgis
    "mac_prefix",
2159 eaa4c57c Dimitris Aragiorgis
    "network",
2160 eaa4c57c Dimitris Aragiorgis
    "network6",
2161 eaa4c57c Dimitris Aragiorgis
    "gateway",
2162 eaa4c57c Dimitris Aragiorgis
    "gateway6",
2163 eaa4c57c Dimitris Aragiorgis
    "reservations",
2164 eaa4c57c Dimitris Aragiorgis
    "ext_reservations",
2165 eaa4c57c Dimitris Aragiorgis
    ] + _TIMESTAMPS + _UUID
2166 eaa4c57c Dimitris Aragiorgis
2167 7e8f03e3 Dimitris Aragiorgis
  def HooksDict(self, prefix=""):
2168 d89168ff Guido Trotter
    """Export a dictionary used by hooks with a network's information.
2169 d89168ff Guido Trotter

2170 d89168ff Guido Trotter
    @type prefix: String
2171 d89168ff Guido Trotter
    @param prefix: Prefix to prepend to the dict entries
2172 d89168ff Guido Trotter

2173 d89168ff Guido Trotter
    """
2174 d89168ff Guido Trotter
    result = {
2175 7e8f03e3 Dimitris Aragiorgis
      "%sNETWORK_NAME" % prefix: self.name,
2176 d89168ff Guido Trotter
      "%sNETWORK_UUID" % prefix: self.uuid,
2177 5a76adf7 Dimitris Aragiorgis
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2178 d89168ff Guido Trotter
    }
2179 d89168ff Guido Trotter
    if self.network:
2180 d89168ff Guido Trotter
      result["%sNETWORK_SUBNET" % prefix] = self.network
2181 d89168ff Guido Trotter
    if self.gateway:
2182 d89168ff Guido Trotter
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2183 d89168ff Guido Trotter
    if self.network6:
2184 d89168ff Guido Trotter
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2185 d89168ff Guido Trotter
    if self.gateway6:
2186 d89168ff Guido Trotter
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2187 d89168ff Guido Trotter
    if self.mac_prefix:
2188 d89168ff Guido Trotter
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2189 d89168ff Guido Trotter
2190 d89168ff Guido Trotter
    return result
2191 d89168ff Guido Trotter
2192 5cfa6c37 Dimitris Aragiorgis
  @classmethod
2193 5cfa6c37 Dimitris Aragiorgis
  def FromDict(cls, val):
2194 5cfa6c37 Dimitris Aragiorgis
    """Custom function for networks.
2195 5cfa6c37 Dimitris Aragiorgis

2196 48616625 Dimitris Aragiorgis
    Remove deprecated network_type and family.
2197 5cfa6c37 Dimitris Aragiorgis

2198 5cfa6c37 Dimitris Aragiorgis
    """
2199 5cfa6c37 Dimitris Aragiorgis
    if "network_type" in val:
2200 5cfa6c37 Dimitris Aragiorgis
      del val["network_type"]
2201 48616625 Dimitris Aragiorgis
    if "family" in val:
2202 48616625 Dimitris Aragiorgis
      del val["family"]
2203 5cfa6c37 Dimitris Aragiorgis
    obj = super(Network, cls).FromDict(val)
2204 5cfa6c37 Dimitris Aragiorgis
    return obj
2205 5cfa6c37 Dimitris Aragiorgis
2206 eaa4c57c Dimitris Aragiorgis
2207 523170de Dimitris Aragiorgis
# need to inherit object in order to use super()
2208 523170de Dimitris Aragiorgis
class SerializableConfigParser(ConfigParser.SafeConfigParser, object):
2209 a8083063 Iustin Pop
  """Simple wrapper over ConfigParse that allows serialization.
2210 a8083063 Iustin Pop

2211 a8083063 Iustin Pop
  This class is basically ConfigParser.SafeConfigParser with two
2212 a8083063 Iustin Pop
  additional methods that allow it to serialize/unserialize to/from a
2213 a8083063 Iustin Pop
  buffer.
2214 a8083063 Iustin Pop

2215 a8083063 Iustin Pop
  """
2216 a8083063 Iustin Pop
  def Dumps(self):
2217 a8083063 Iustin Pop
    """Dump this instance and return the string representation."""
2218 a8083063 Iustin Pop
    buf = StringIO()
2219 a8083063 Iustin Pop
    self.write(buf)
2220 a8083063 Iustin Pop
    return buf.getvalue()
2221 a8083063 Iustin Pop
2222 b39bf4bb Guido Trotter
  @classmethod
2223 b39bf4bb Guido Trotter
  def Loads(cls, data):
2224 a8083063 Iustin Pop
    """Load data from a string."""
2225 a8083063 Iustin Pop
    buf = StringIO(data)
2226 b39bf4bb Guido Trotter
    cfp = cls()
2227 a8083063 Iustin Pop
    cfp.readfp(buf)
2228 a8083063 Iustin Pop
    return cfp
2229 59726e15 Bernardo Dal Seno
2230 523170de Dimitris Aragiorgis
  def get(self, section, option, **kwargs):
2231 523170de Dimitris Aragiorgis
    value = None
2232 523170de Dimitris Aragiorgis
    try:
2233 523170de Dimitris Aragiorgis
      value = super(SerializableConfigParser, self).get(section, option,
2234 523170de Dimitris Aragiorgis
                                                        **kwargs)
2235 523170de Dimitris Aragiorgis
      if value.lower() == constants.VALUE_NONE:
2236 523170de Dimitris Aragiorgis
        value = None
2237 523170de Dimitris Aragiorgis
    except ConfigParser.NoOptionError:
2238 ad55b2d4 Klaus Aehlig
      r = re.compile(r"(disk|nic)\d+_name|nic\d+_(network|vlan)")
2239 523170de Dimitris Aragiorgis
      match = r.match(option)
2240 523170de Dimitris Aragiorgis
      if match:
2241 523170de Dimitris Aragiorgis
        pass
2242 523170de Dimitris Aragiorgis
      else:
2243 523170de Dimitris Aragiorgis
        raise
2244 523170de Dimitris Aragiorgis
2245 523170de Dimitris Aragiorgis
    return value
2246 523170de Dimitris Aragiorgis
2247 59726e15 Bernardo Dal Seno
2248 59726e15 Bernardo Dal Seno
class LvmPvInfo(ConfigObject):
2249 59726e15 Bernardo Dal Seno
  """Information about an LVM physical volume (PV).
2250 59726e15 Bernardo Dal Seno

2251 59726e15 Bernardo Dal Seno
  @type name: string
2252 59726e15 Bernardo Dal Seno
  @ivar name: name of the PV
2253 59726e15 Bernardo Dal Seno
  @type vg_name: string
2254 59726e15 Bernardo Dal Seno
  @ivar vg_name: name of the volume group containing the PV
2255 59726e15 Bernardo Dal Seno
  @type size: float
2256 59726e15 Bernardo Dal Seno
  @ivar size: size of the PV in MiB
2257 59726e15 Bernardo Dal Seno
  @type free: float
2258 59726e15 Bernardo Dal Seno
  @ivar free: free space in the PV, in MiB
2259 59726e15 Bernardo Dal Seno
  @type attributes: string
2260 59726e15 Bernardo Dal Seno
  @ivar attributes: PV attributes
2261 b496abdb Bernardo Dal Seno
  @type lv_list: list of strings
2262 b496abdb Bernardo Dal Seno
  @ivar lv_list: names of the LVs hosted on the PV
2263 59726e15 Bernardo Dal Seno
  """
2264 59726e15 Bernardo Dal Seno
  __slots__ = [
2265 59726e15 Bernardo Dal Seno
    "name",
2266 59726e15 Bernardo Dal Seno
    "vg_name",
2267 59726e15 Bernardo Dal Seno
    "size",
2268 59726e15 Bernardo Dal Seno
    "free",
2269 59726e15 Bernardo Dal Seno
    "attributes",
2270 b496abdb Bernardo Dal Seno
    "lv_list"
2271 59726e15 Bernardo Dal Seno
    ]
2272 59726e15 Bernardo Dal Seno
2273 59726e15 Bernardo Dal Seno
  def IsEmpty(self):
2274 59726e15 Bernardo Dal Seno
    """Is this PV empty?
2275 59726e15 Bernardo Dal Seno

2276 59726e15 Bernardo Dal Seno
    """
2277 59726e15 Bernardo Dal Seno
    return self.size <= (self.free + 1)
2278 59726e15 Bernardo Dal Seno
2279 59726e15 Bernardo Dal Seno
  def IsAllocatable(self):
2280 59726e15 Bernardo Dal Seno
    """Is this PV allocatable?
2281 59726e15 Bernardo Dal Seno

2282 59726e15 Bernardo Dal Seno
    """
2283 59726e15 Bernardo Dal Seno
    return ("a" in self.attributes)