Statistics
| Branch: | Tag: | Revision:

root / lib / utils / __init__.py @ 94ab995a

History | View | Annotate | Download (24.1 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 4fd029cf Michael Hanselmann
# Copyright (C) 2006, 2007, 2010, 2011 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 58885d79 Iustin Pop
"""Ganeti utility module.
23 58885d79 Iustin Pop

24 58885d79 Iustin Pop
This module holds functions that can be used in both daemons (all) and
25 58885d79 Iustin Pop
the command line scripts.
26 899d2a81 Michael Hanselmann

27 a8083063 Iustin Pop
"""
28 a8083063 Iustin Pop
29 b459a848 Andrea Spadaccini
# Allow wildcard import in pylint: disable=W0401
30 a8083063 Iustin Pop
31 a8083063 Iustin Pop
import os
32 a8083063 Iustin Pop
import re
33 4ca1b175 Alexander Schreiber
import errno
34 2f8b60b3 Iustin Pop
import pwd
35 f8326fca Andrea Spadaccini
import time
36 78feb6fb Guido Trotter
import itertools
37 9c233417 Iustin Pop
import select
38 bb698c1f Iustin Pop
import logging
39 de499029 Michael Hanselmann
import signal
40 a8083063 Iustin Pop
41 a8083063 Iustin Pop
from ganeti import errors
42 3aecd2c7 Iustin Pop
from ganeti import constants
43 716a32cb Guido Trotter
from ganeti import compat
44 111a7d04 Michael Hanselmann
from ganeti import pathutils
45 a8083063 Iustin Pop
46 63fc4229 Michael Hanselmann
from ganeti.utils.algo import *
47 63fc4229 Michael Hanselmann
from ganeti.utils.filelock import *
48 63fc4229 Michael Hanselmann
from ganeti.utils.hash import *
49 63fc4229 Michael Hanselmann
from ganeti.utils.io import *
50 63fc4229 Michael Hanselmann
from ganeti.utils.log import *
51 59726e15 Bernardo Dal Seno
from ganeti.utils.lvm import *
52 8dc76d54 Guido Trotter
from ganeti.utils.mlock import *
53 63fc4229 Michael Hanselmann
from ganeti.utils.nodesetup import *
54 63fc4229 Michael Hanselmann
from ganeti.utils.process import *
55 63fc4229 Michael Hanselmann
from ganeti.utils.retry import *
56 59ef0f15 Helga Velroyen
from ganeti.utils.storage import *
57 63fc4229 Michael Hanselmann
from ganeti.utils.text import *
58 63fc4229 Michael Hanselmann
from ganeti.utils.wrapper import *
59 1eda3dd3 Klaus Aehlig
from ganeti.utils.version import *
60 63fc4229 Michael Hanselmann
from ganeti.utils.x509 import *
61 16abfbc2 Alexander Schreiber
62 58885d79 Iustin Pop
63 28f34048 Michael Hanselmann
_VALID_SERVICE_NAME_RE = re.compile("^[-_.a-zA-Z0-9]{1,128}$")
64 28f34048 Michael Hanselmann
65 80a0546b Michele Tartara
UUID_RE = re.compile(constants.UUID_REGEX)
66 05636402 Guido Trotter
67 7c0d6283 Michael Hanselmann
68 a5728081 Guido Trotter
def ForceDictType(target, key_types, allowed_values=None):
69 a5728081 Guido Trotter
  """Force the values of a dict to have certain types.
70 a5728081 Guido Trotter

71 a5728081 Guido Trotter
  @type target: dict
72 a5728081 Guido Trotter
  @param target: the dict to update
73 a5728081 Guido Trotter
  @type key_types: dict
74 a5728081 Guido Trotter
  @param key_types: dict mapping target dict keys to types
75 a5728081 Guido Trotter
                    in constants.ENFORCEABLE_TYPES
76 a5728081 Guido Trotter
  @type allowed_values: list
77 a5728081 Guido Trotter
  @keyword allowed_values: list of specially allowed values
78 a5728081 Guido Trotter

79 a5728081 Guido Trotter
  """
80 a5728081 Guido Trotter
  if allowed_values is None:
81 a5728081 Guido Trotter
    allowed_values = []
82 a5728081 Guido Trotter
83 8b46606c Guido Trotter
  if not isinstance(target, dict):
84 8b46606c Guido Trotter
    msg = "Expected dictionary, got '%s'" % target
85 8b46606c Guido Trotter
    raise errors.TypeEnforcementError(msg)
86 8b46606c Guido Trotter
87 a5728081 Guido Trotter
  for key in target:
88 a5728081 Guido Trotter
    if key not in key_types:
89 58a59652 Iustin Pop
      msg = "Unknown parameter '%s'" % key
90 a5728081 Guido Trotter
      raise errors.TypeEnforcementError(msg)
91 a5728081 Guido Trotter
92 a5728081 Guido Trotter
    if target[key] in allowed_values:
93 a5728081 Guido Trotter
      continue
94 a5728081 Guido Trotter
95 29921401 Iustin Pop
    ktype = key_types[key]
96 29921401 Iustin Pop
    if ktype not in constants.ENFORCEABLE_TYPES:
97 29921401 Iustin Pop
      msg = "'%s' has non-enforceable type %s" % (key, ktype)
98 a5728081 Guido Trotter
      raise errors.ProgrammerError(msg)
99 a5728081 Guido Trotter
100 59525e1f Michael Hanselmann
    if ktype in (constants.VTYPE_STRING, constants.VTYPE_MAYBE_STRING):
101 59525e1f Michael Hanselmann
      if target[key] is None and ktype == constants.VTYPE_MAYBE_STRING:
102 7eed4433 Michele Tartara
        msg = "'None' is not a valid Maybe value. Use 'VALUE_HS_NOTHING'"
103 1cc324f0 Michele Tartara
        logging.warning(msg)
104 7eed4433 Michele Tartara
      elif (target[key] == constants.VALUE_HS_NOTHING
105 7eed4433 Michele Tartara
            and ktype == constants.VTYPE_MAYBE_STRING):
106 59525e1f Michael Hanselmann
        pass
107 59525e1f Michael Hanselmann
      elif not isinstance(target[key], basestring):
108 a5728081 Guido Trotter
        if isinstance(target[key], bool) and not target[key]:
109 d0c8c01d Iustin Pop
          target[key] = ""
110 a5728081 Guido Trotter
        else:
111 a5728081 Guido Trotter
          msg = "'%s' (value %s) is not a valid string" % (key, target[key])
112 a5728081 Guido Trotter
          raise errors.TypeEnforcementError(msg)
113 29921401 Iustin Pop
    elif ktype == constants.VTYPE_BOOL:
114 a5728081 Guido Trotter
      if isinstance(target[key], basestring) and target[key]:
115 a5728081 Guido Trotter
        if target[key].lower() == constants.VALUE_FALSE:
116 a5728081 Guido Trotter
          target[key] = False
117 a5728081 Guido Trotter
        elif target[key].lower() == constants.VALUE_TRUE:
118 a5728081 Guido Trotter
          target[key] = True
119 a5728081 Guido Trotter
        else:
120 a5728081 Guido Trotter
          msg = "'%s' (value %s) is not a valid boolean" % (key, target[key])
121 a5728081 Guido Trotter
          raise errors.TypeEnforcementError(msg)
122 a5728081 Guido Trotter
      elif target[key]:
123 a5728081 Guido Trotter
        target[key] = True
124 a5728081 Guido Trotter
      else:
125 a5728081 Guido Trotter
        target[key] = False
126 29921401 Iustin Pop
    elif ktype == constants.VTYPE_SIZE:
127 a5728081 Guido Trotter
      try:
128 a5728081 Guido Trotter
        target[key] = ParseUnit(target[key])
129 a5728081 Guido Trotter
      except errors.UnitParseError, err:
130 a5728081 Guido Trotter
        msg = "'%s' (value %s) is not a valid size. error: %s" % \
131 a5728081 Guido Trotter
              (key, target[key], err)
132 a5728081 Guido Trotter
        raise errors.TypeEnforcementError(msg)
133 29921401 Iustin Pop
    elif ktype == constants.VTYPE_INT:
134 a5728081 Guido Trotter
      try:
135 a5728081 Guido Trotter
        target[key] = int(target[key])
136 a5728081 Guido Trotter
      except (ValueError, TypeError):
137 a5728081 Guido Trotter
        msg = "'%s' (value %s) is not a valid integer" % (key, target[key])
138 a5728081 Guido Trotter
        raise errors.TypeEnforcementError(msg)
139 a5728081 Guido Trotter
140 a5728081 Guido Trotter
141 28f34048 Michael Hanselmann
def ValidateServiceName(name):
142 28f34048 Michael Hanselmann
  """Validate the given service name.
143 28f34048 Michael Hanselmann

144 28f34048 Michael Hanselmann
  @type name: number or string
145 28f34048 Michael Hanselmann
  @param name: Service name or port specification
146 28f34048 Michael Hanselmann

147 28f34048 Michael Hanselmann
  """
148 28f34048 Michael Hanselmann
  try:
149 28f34048 Michael Hanselmann
    numport = int(name)
150 28f34048 Michael Hanselmann
  except (ValueError, TypeError):
151 28f34048 Michael Hanselmann
    # Non-numeric service name
152 28f34048 Michael Hanselmann
    valid = _VALID_SERVICE_NAME_RE.match(name)
153 28f34048 Michael Hanselmann
  else:
154 28f34048 Michael Hanselmann
    # Numeric port (protocols other than TCP or UDP might need adjustments
155 28f34048 Michael Hanselmann
    # here)
156 28f34048 Michael Hanselmann
    valid = (numport >= 0 and numport < (1 << 16))
157 28f34048 Michael Hanselmann
158 28f34048 Michael Hanselmann
  if not valid:
159 28f34048 Michael Hanselmann
    raise errors.OpPrereqError("Invalid service name '%s'" % name,
160 28f34048 Michael Hanselmann
                               errors.ECODE_INVAL)
161 28f34048 Michael Hanselmann
162 28f34048 Michael Hanselmann
  return name
163 28f34048 Michael Hanselmann
164 28f34048 Michael Hanselmann
165 32be86da Renรฉ Nussbaumer
def _ComputeMissingKeys(key_path, options, defaults):
166 32be86da Renรฉ Nussbaumer
  """Helper functions to compute which keys a invalid.
167 32be86da Renรฉ Nussbaumer

168 32be86da Renรฉ Nussbaumer
  @param key_path: The current key path (if any)
169 32be86da Renรฉ Nussbaumer
  @param options: The user provided options
170 32be86da Renรฉ Nussbaumer
  @param defaults: The default dictionary
171 32be86da Renรฉ Nussbaumer
  @return: A list of invalid keys
172 32be86da Renรฉ Nussbaumer

173 32be86da Renรฉ Nussbaumer
  """
174 32be86da Renรฉ Nussbaumer
  defaults_keys = frozenset(defaults.keys())
175 32be86da Renรฉ Nussbaumer
  invalid = []
176 32be86da Renรฉ Nussbaumer
  for key, value in options.items():
177 32be86da Renรฉ Nussbaumer
    if key_path:
178 32be86da Renรฉ Nussbaumer
      new_path = "%s/%s" % (key_path, key)
179 32be86da Renรฉ Nussbaumer
    else:
180 32be86da Renรฉ Nussbaumer
      new_path = key
181 32be86da Renรฉ Nussbaumer
182 32be86da Renรฉ Nussbaumer
    if key not in defaults_keys:
183 32be86da Renรฉ Nussbaumer
      invalid.append(new_path)
184 32be86da Renรฉ Nussbaumer
    elif isinstance(value, dict):
185 32be86da Renรฉ Nussbaumer
      invalid.extend(_ComputeMissingKeys(new_path, value, defaults[key]))
186 32be86da Renรฉ Nussbaumer
187 32be86da Renรฉ Nussbaumer
  return invalid
188 32be86da Renรฉ Nussbaumer
189 32be86da Renรฉ Nussbaumer
190 32be86da Renรฉ Nussbaumer
def VerifyDictOptions(options, defaults):
191 32be86da Renรฉ Nussbaumer
  """Verify a dict has only keys set which also are in the defaults dict.
192 32be86da Renรฉ Nussbaumer

193 32be86da Renรฉ Nussbaumer
  @param options: The user provided options
194 32be86da Renรฉ Nussbaumer
  @param defaults: The default dictionary
195 32be86da Renรฉ Nussbaumer
  @raise error.OpPrereqError: If one of the keys is not supported
196 32be86da Renรฉ Nussbaumer

197 32be86da Renรฉ Nussbaumer
  """
198 32be86da Renรฉ Nussbaumer
  invalid = _ComputeMissingKeys("", options, defaults)
199 32be86da Renรฉ Nussbaumer
200 32be86da Renรฉ Nussbaumer
  if invalid:
201 32be86da Renรฉ Nussbaumer
    raise errors.OpPrereqError("Provided option keys not supported: %s" %
202 32be86da Renรฉ Nussbaumer
                               CommaJoin(invalid), errors.ECODE_INVAL)
203 32be86da Renรฉ Nussbaumer
204 32be86da Renรฉ Nussbaumer
205 a8083063 Iustin Pop
def ListVolumeGroups():
206 a8083063 Iustin Pop
  """List volume groups and their size
207 a8083063 Iustin Pop

208 58885d79 Iustin Pop
  @rtype: dict
209 58885d79 Iustin Pop
  @return:
210 58885d79 Iustin Pop
       Dictionary with keys volume name and values
211 58885d79 Iustin Pop
       the size of the volume
212 a8083063 Iustin Pop

213 a8083063 Iustin Pop
  """
214 a8083063 Iustin Pop
  command = "vgs --noheadings --units m --nosuffix -o name,size"
215 a8083063 Iustin Pop
  result = RunCmd(command)
216 a8083063 Iustin Pop
  retval = {}
217 a8083063 Iustin Pop
  if result.failed:
218 a8083063 Iustin Pop
    return retval
219 a8083063 Iustin Pop
220 a8083063 Iustin Pop
  for line in result.stdout.splitlines():
221 a8083063 Iustin Pop
    try:
222 a8083063 Iustin Pop
      name, size = line.split()
223 a8083063 Iustin Pop
      size = int(float(size))
224 a8083063 Iustin Pop
    except (IndexError, ValueError), err:
225 bb698c1f Iustin Pop
      logging.error("Invalid output from vgs (%s): %s", err, line)
226 a8083063 Iustin Pop
      continue
227 a8083063 Iustin Pop
228 a8083063 Iustin Pop
    retval[name] = size
229 a8083063 Iustin Pop
230 a8083063 Iustin Pop
  return retval
231 a8083063 Iustin Pop
232 a8083063 Iustin Pop
233 a8083063 Iustin Pop
def BridgeExists(bridge):
234 a8083063 Iustin Pop
  """Check whether the given bridge exists in the system
235 a8083063 Iustin Pop

236 58885d79 Iustin Pop
  @type bridge: str
237 58885d79 Iustin Pop
  @param bridge: the bridge name to check
238 58885d79 Iustin Pop
  @rtype: boolean
239 58885d79 Iustin Pop
  @return: True if it does
240 a8083063 Iustin Pop

241 a8083063 Iustin Pop
  """
242 a8083063 Iustin Pop
  return os.path.isdir("/sys/class/net/%s/bridge" % bridge)
243 a8083063 Iustin Pop
244 a8083063 Iustin Pop
245 a8083063 Iustin Pop
def TryConvert(fn, val):
246 a8083063 Iustin Pop
  """Try to convert a value ignoring errors.
247 a8083063 Iustin Pop

248 58885d79 Iustin Pop
  This function tries to apply function I{fn} to I{val}. If no
249 58885d79 Iustin Pop
  C{ValueError} or C{TypeError} exceptions are raised, it will return
250 58885d79 Iustin Pop
  the result, else it will return the original value. Any other
251 58885d79 Iustin Pop
  exceptions are propagated to the caller.
252 58885d79 Iustin Pop

253 58885d79 Iustin Pop
  @type fn: callable
254 58885d79 Iustin Pop
  @param fn: function to apply to the value
255 58885d79 Iustin Pop
  @param val: the value to be converted
256 58885d79 Iustin Pop
  @return: The converted value if the conversion was successful,
257 58885d79 Iustin Pop
      otherwise the original value.
258 a8083063 Iustin Pop

259 a8083063 Iustin Pop
  """
260 a8083063 Iustin Pop
  try:
261 a8083063 Iustin Pop
    nv = fn(val)
262 7c4d6c7b Michael Hanselmann
  except (ValueError, TypeError):
263 a8083063 Iustin Pop
    nv = val
264 a8083063 Iustin Pop
  return nv
265 a8083063 Iustin Pop
266 a8083063 Iustin Pop
267 31155d60 Balazs Lecz
def ParseCpuMask(cpu_mask):
268 31155d60 Balazs Lecz
  """Parse a CPU mask definition and return the list of CPU IDs.
269 31155d60 Balazs Lecz

270 31155d60 Balazs Lecz
  CPU mask format: comma-separated list of CPU IDs
271 31155d60 Balazs Lecz
  or dash-separated ID ranges
272 31155d60 Balazs Lecz
  Example: "0-2,5" -> "0,1,2,5"
273 31155d60 Balazs Lecz

274 31155d60 Balazs Lecz
  @type cpu_mask: str
275 31155d60 Balazs Lecz
  @param cpu_mask: CPU mask definition
276 31155d60 Balazs Lecz
  @rtype: list of int
277 31155d60 Balazs Lecz
  @return: list of CPU IDs
278 31155d60 Balazs Lecz

279 31155d60 Balazs Lecz
  """
280 31155d60 Balazs Lecz
  if not cpu_mask:
281 31155d60 Balazs Lecz
    return []
282 31155d60 Balazs Lecz
  cpu_list = []
283 31155d60 Balazs Lecz
  for range_def in cpu_mask.split(","):
284 31155d60 Balazs Lecz
    boundaries = range_def.split("-")
285 31155d60 Balazs Lecz
    n_elements = len(boundaries)
286 31155d60 Balazs Lecz
    if n_elements > 2:
287 31155d60 Balazs Lecz
      raise errors.ParseError("Invalid CPU ID range definition"
288 31155d60 Balazs Lecz
                              " (only one hyphen allowed): %s" % range_def)
289 31155d60 Balazs Lecz
    try:
290 31155d60 Balazs Lecz
      lower = int(boundaries[0])
291 31155d60 Balazs Lecz
    except (ValueError, TypeError), err:
292 31155d60 Balazs Lecz
      raise errors.ParseError("Invalid CPU ID value for lower boundary of"
293 31155d60 Balazs Lecz
                              " CPU ID range: %s" % str(err))
294 31155d60 Balazs Lecz
    try:
295 31155d60 Balazs Lecz
      higher = int(boundaries[-1])
296 31155d60 Balazs Lecz
    except (ValueError, TypeError), err:
297 31155d60 Balazs Lecz
      raise errors.ParseError("Invalid CPU ID value for higher boundary of"
298 31155d60 Balazs Lecz
                              " CPU ID range: %s" % str(err))
299 31155d60 Balazs Lecz
    if lower > higher:
300 31155d60 Balazs Lecz
      raise errors.ParseError("Invalid CPU ID range definition"
301 31155d60 Balazs Lecz
                              " (%d > %d): %s" % (lower, higher, range_def))
302 31155d60 Balazs Lecz
    cpu_list.extend(range(lower, higher + 1))
303 31155d60 Balazs Lecz
  return cpu_list
304 31155d60 Balazs Lecz
305 31155d60 Balazs Lecz
306 538ca33a Tsachy Shacham
def ParseMultiCpuMask(cpu_mask):
307 538ca33a Tsachy Shacham
  """Parse a multiple CPU mask definition and return the list of CPU IDs.
308 538ca33a Tsachy Shacham

309 538ca33a Tsachy Shacham
  CPU mask format: colon-separated list of comma-separated list of CPU IDs
310 538ca33a Tsachy Shacham
  or dash-separated ID ranges, with optional "all" as CPU value
311 538ca33a Tsachy Shacham
  Example: "0-2,5:all:1,5,6:2" -> [ [ 0,1,2,5 ], [ -1 ], [ 1, 5, 6 ], [ 2 ] ]
312 538ca33a Tsachy Shacham

313 538ca33a Tsachy Shacham
  @type cpu_mask: str
314 538ca33a Tsachy Shacham
  @param cpu_mask: multiple CPU mask definition
315 538ca33a Tsachy Shacham
  @rtype: list of lists of int
316 538ca33a Tsachy Shacham
  @return: list of lists of CPU IDs
317 538ca33a Tsachy Shacham

318 538ca33a Tsachy Shacham
  """
319 538ca33a Tsachy Shacham
  if not cpu_mask:
320 538ca33a Tsachy Shacham
    return []
321 538ca33a Tsachy Shacham
  cpu_list = []
322 538ca33a Tsachy Shacham
  for range_def in cpu_mask.split(constants.CPU_PINNING_SEP):
323 538ca33a Tsachy Shacham
    if range_def == constants.CPU_PINNING_ALL:
324 538ca33a Tsachy Shacham
      cpu_list.append([constants.CPU_PINNING_ALL_VAL, ])
325 538ca33a Tsachy Shacham
    else:
326 538ca33a Tsachy Shacham
      # Uniquify and sort the list before adding
327 538ca33a Tsachy Shacham
      cpu_list.append(sorted(set(ParseCpuMask(range_def))))
328 538ca33a Tsachy Shacham
329 538ca33a Tsachy Shacham
  return cpu_list
330 538ca33a Tsachy Shacham
331 538ca33a Tsachy Shacham
332 257f4c0a Iustin Pop
def GetHomeDir(user, default=None):
333 257f4c0a Iustin Pop
  """Try to get the homedir of the given user.
334 257f4c0a Iustin Pop

335 257f4c0a Iustin Pop
  The user can be passed either as a string (denoting the name) or as
336 257f4c0a Iustin Pop
  an integer (denoting the user id). If the user is not found, the
337 3ccb3a64 Michael Hanselmann
  C{default} argument is returned, which defaults to C{None}.
338 2f8b60b3 Iustin Pop

339 2f8b60b3 Iustin Pop
  """
340 2f8b60b3 Iustin Pop
  try:
341 257f4c0a Iustin Pop
    if isinstance(user, basestring):
342 257f4c0a Iustin Pop
      result = pwd.getpwnam(user)
343 257f4c0a Iustin Pop
    elif isinstance(user, (int, long)):
344 257f4c0a Iustin Pop
      result = pwd.getpwuid(user)
345 257f4c0a Iustin Pop
    else:
346 257f4c0a Iustin Pop
      raise errors.ProgrammerError("Invalid type passed to GetHomeDir (%s)" %
347 257f4c0a Iustin Pop
                                   type(user))
348 2f8b60b3 Iustin Pop
  except KeyError:
349 2f8b60b3 Iustin Pop
    return default
350 2f8b60b3 Iustin Pop
  return result.pw_dir
351 59072e7e Michael Hanselmann
352 59072e7e Michael Hanselmann
353 7b4126b7 Iustin Pop
def FirstFree(seq, base=0):
354 7b4126b7 Iustin Pop
  """Returns the first non-existing integer from seq.
355 7b4126b7 Iustin Pop

356 7b4126b7 Iustin Pop
  The seq argument should be a sorted list of positive integers. The
357 7b4126b7 Iustin Pop
  first time the index of an element is smaller than the element
358 7b4126b7 Iustin Pop
  value, the index will be returned.
359 7b4126b7 Iustin Pop

360 7b4126b7 Iustin Pop
  The base argument is used to start at a different offset,
361 58885d79 Iustin Pop
  i.e. C{[3, 4, 6]} with I{offset=3} will return 5.
362 58885d79 Iustin Pop

363 58885d79 Iustin Pop
  Example: C{[0, 1, 3]} will return I{2}.
364 7b4126b7 Iustin Pop

365 58885d79 Iustin Pop
  @type seq: sequence
366 58885d79 Iustin Pop
  @param seq: the sequence to be analyzed.
367 58885d79 Iustin Pop
  @type base: int
368 58885d79 Iustin Pop
  @param base: use this value as the base index of the sequence
369 58885d79 Iustin Pop
  @rtype: int
370 58885d79 Iustin Pop
  @return: the first non-used index in the sequence
371 7b4126b7 Iustin Pop

372 7b4126b7 Iustin Pop
  """
373 7b4126b7 Iustin Pop
  for idx, elem in enumerate(seq):
374 7b4126b7 Iustin Pop
    assert elem >= base, "Passed element is higher than base offset"
375 7b4126b7 Iustin Pop
    if elem > idx + base:
376 7b4126b7 Iustin Pop
      # idx is not used
377 7b4126b7 Iustin Pop
      return idx + base
378 7b4126b7 Iustin Pop
  return None
379 7b4126b7 Iustin Pop
380 7b4126b7 Iustin Pop
381 dfdc4060 Guido Trotter
def SingleWaitForFdCondition(fdobj, event, timeout):
382 dcd511c8 Guido Trotter
  """Waits for a condition to occur on the socket.
383 dcd511c8 Guido Trotter

384 dfdc4060 Guido Trotter
  Immediately returns at the first interruption.
385 dfdc4060 Guido Trotter

386 dfdc4060 Guido Trotter
  @type fdobj: integer or object supporting a fileno() method
387 dfdc4060 Guido Trotter
  @param fdobj: entity to wait for events on
388 dfdc4060 Guido Trotter
  @type event: integer
389 dcd511c8 Guido Trotter
  @param event: ORed condition (see select module)
390 dcd511c8 Guido Trotter
  @type timeout: float or None
391 dcd511c8 Guido Trotter
  @param timeout: Timeout in seconds
392 dcd511c8 Guido Trotter
  @rtype: int or None
393 dcd511c8 Guido Trotter
  @return: None for timeout, otherwise occured conditions
394 dcd511c8 Guido Trotter

395 dcd511c8 Guido Trotter
  """
396 dcd511c8 Guido Trotter
  check = (event | select.POLLPRI |
397 dcd511c8 Guido Trotter
           select.POLLNVAL | select.POLLHUP | select.POLLERR)
398 dcd511c8 Guido Trotter
399 dcd511c8 Guido Trotter
  if timeout is not None:
400 dcd511c8 Guido Trotter
    # Poller object expects milliseconds
401 dcd511c8 Guido Trotter
    timeout *= 1000
402 dcd511c8 Guido Trotter
403 dcd511c8 Guido Trotter
  poller = select.poll()
404 dfdc4060 Guido Trotter
  poller.register(fdobj, event)
405 dcd511c8 Guido Trotter
  try:
406 dfdc4060 Guido Trotter
    # TODO: If the main thread receives a signal and we have no timeout, we
407 dfdc4060 Guido Trotter
    # could wait forever. This should check a global "quit" flag or something
408 dfdc4060 Guido Trotter
    # every so often.
409 dfdc4060 Guido Trotter
    io_events = poller.poll(timeout)
410 dfdc4060 Guido Trotter
  except select.error, err:
411 dfdc4060 Guido Trotter
    if err[0] != errno.EINTR:
412 dfdc4060 Guido Trotter
      raise
413 dfdc4060 Guido Trotter
    io_events = []
414 dfdc4060 Guido Trotter
  if io_events and io_events[0][1] & check:
415 dfdc4060 Guido Trotter
    return io_events[0][1]
416 dfdc4060 Guido Trotter
  else:
417 dfdc4060 Guido Trotter
    return None
418 dfdc4060 Guido Trotter
419 dfdc4060 Guido Trotter
420 dfdc4060 Guido Trotter
class FdConditionWaiterHelper(object):
421 dfdc4060 Guido Trotter
  """Retry helper for WaitForFdCondition.
422 dfdc4060 Guido Trotter

423 dfdc4060 Guido Trotter
  This class contains the retried and wait functions that make sure
424 dfdc4060 Guido Trotter
  WaitForFdCondition can continue waiting until the timeout is actually
425 dfdc4060 Guido Trotter
  expired.
426 dfdc4060 Guido Trotter

427 dfdc4060 Guido Trotter
  """
428 dfdc4060 Guido Trotter
429 dfdc4060 Guido Trotter
  def __init__(self, timeout):
430 dfdc4060 Guido Trotter
    self.timeout = timeout
431 dfdc4060 Guido Trotter
432 dfdc4060 Guido Trotter
  def Poll(self, fdobj, event):
433 dfdc4060 Guido Trotter
    result = SingleWaitForFdCondition(fdobj, event, self.timeout)
434 dfdc4060 Guido Trotter
    if result is None:
435 dfdc4060 Guido Trotter
      raise RetryAgain()
436 dfdc4060 Guido Trotter
    else:
437 dfdc4060 Guido Trotter
      return result
438 dfdc4060 Guido Trotter
439 dfdc4060 Guido Trotter
  def UpdateTimeout(self, timeout):
440 dfdc4060 Guido Trotter
    self.timeout = timeout
441 dfdc4060 Guido Trotter
442 dfdc4060 Guido Trotter
443 dfdc4060 Guido Trotter
def WaitForFdCondition(fdobj, event, timeout):
444 dfdc4060 Guido Trotter
  """Waits for a condition to occur on the socket.
445 dfdc4060 Guido Trotter

446 dfdc4060 Guido Trotter
  Retries until the timeout is expired, even if interrupted.
447 dfdc4060 Guido Trotter

448 dfdc4060 Guido Trotter
  @type fdobj: integer or object supporting a fileno() method
449 dfdc4060 Guido Trotter
  @param fdobj: entity to wait for events on
450 dfdc4060 Guido Trotter
  @type event: integer
451 dfdc4060 Guido Trotter
  @param event: ORed condition (see select module)
452 dfdc4060 Guido Trotter
  @type timeout: float or None
453 dfdc4060 Guido Trotter
  @param timeout: Timeout in seconds
454 dfdc4060 Guido Trotter
  @rtype: int or None
455 dfdc4060 Guido Trotter
  @return: None for timeout, otherwise occured conditions
456 dfdc4060 Guido Trotter

457 dfdc4060 Guido Trotter
  """
458 dfdc4060 Guido Trotter
  if timeout is not None:
459 dfdc4060 Guido Trotter
    retrywaiter = FdConditionWaiterHelper(timeout)
460 1b429e2a Iustin Pop
    try:
461 1b429e2a Iustin Pop
      result = Retry(retrywaiter.Poll, RETRY_REMAINING_TIME, timeout,
462 1b429e2a Iustin Pop
                     args=(fdobj, event), wait_fn=retrywaiter.UpdateTimeout)
463 1b429e2a Iustin Pop
    except RetryTimeout:
464 1b429e2a Iustin Pop
      result = None
465 dfdc4060 Guido Trotter
  else:
466 dfdc4060 Guido Trotter
    result = None
467 dfdc4060 Guido Trotter
    while result is None:
468 dfdc4060 Guido Trotter
      result = SingleWaitForFdCondition(fdobj, event, timeout)
469 dfdc4060 Guido Trotter
  return result
470 2de64672 Iustin Pop
471 2de64672 Iustin Pop
472 2826b361 Guido Trotter
def EnsureDaemon(name):
473 2826b361 Guido Trotter
  """Check for and start daemon if not alive.
474 2826b361 Guido Trotter

475 2826b361 Guido Trotter
  """
476 111a7d04 Michael Hanselmann
  result = RunCmd([pathutils.DAEMON_UTIL, "check-and-start", name])
477 2826b361 Guido Trotter
  if result.failed:
478 2826b361 Guido Trotter
    logging.error("Can't start daemon '%s', failure %s, output: %s",
479 2826b361 Guido Trotter
                  name, result.fail_reason, result.output)
480 2826b361 Guido Trotter
    return False
481 2826b361 Guido Trotter
482 2826b361 Guido Trotter
  return True
483 b330ac0b Guido Trotter
484 b330ac0b Guido Trotter
485 db147305 Tom Limoncelli
def StopDaemon(name):
486 db147305 Tom Limoncelli
  """Stop daemon
487 db147305 Tom Limoncelli

488 db147305 Tom Limoncelli
  """
489 111a7d04 Michael Hanselmann
  result = RunCmd([pathutils.DAEMON_UTIL, "stop", name])
490 db147305 Tom Limoncelli
  if result.failed:
491 db147305 Tom Limoncelli
    logging.error("Can't stop daemon '%s', failure %s, output: %s",
492 db147305 Tom Limoncelli
                  name, result.fail_reason, result.output)
493 db147305 Tom Limoncelli
    return False
494 db147305 Tom Limoncelli
495 db147305 Tom Limoncelli
  return True
496 db147305 Tom Limoncelli
497 db147305 Tom Limoncelli
498 45bc5e4a Michael Hanselmann
def SplitTime(value):
499 739be818 Michael Hanselmann
  """Splits time as floating point number into a tuple.
500 739be818 Michael Hanselmann

501 45bc5e4a Michael Hanselmann
  @param value: Time in seconds
502 45bc5e4a Michael Hanselmann
  @type value: int or float
503 45bc5e4a Michael Hanselmann
  @return: Tuple containing (seconds, microseconds)
504 739be818 Michael Hanselmann

505 739be818 Michael Hanselmann
  """
506 45bc5e4a Michael Hanselmann
  (seconds, microseconds) = divmod(int(value * 1000000), 1000000)
507 45bc5e4a Michael Hanselmann
508 45bc5e4a Michael Hanselmann
  assert 0 <= seconds, \
509 45bc5e4a Michael Hanselmann
    "Seconds must be larger than or equal to 0, but are %s" % seconds
510 45bc5e4a Michael Hanselmann
  assert 0 <= microseconds <= 999999, \
511 45bc5e4a Michael Hanselmann
    "Microseconds must be 0-999999, but are %s" % microseconds
512 45bc5e4a Michael Hanselmann
513 45bc5e4a Michael Hanselmann
  return (int(seconds), int(microseconds))
514 739be818 Michael Hanselmann
515 739be818 Michael Hanselmann
516 739be818 Michael Hanselmann
def MergeTime(timetuple):
517 739be818 Michael Hanselmann
  """Merges a tuple into time as a floating point number.
518 739be818 Michael Hanselmann

519 45bc5e4a Michael Hanselmann
  @param timetuple: Time as tuple, (seconds, microseconds)
520 739be818 Michael Hanselmann
  @type timetuple: tuple
521 739be818 Michael Hanselmann
  @return: Time as a floating point number expressed in seconds
522 739be818 Michael Hanselmann

523 739be818 Michael Hanselmann
  """
524 45bc5e4a Michael Hanselmann
  (seconds, microseconds) = timetuple
525 739be818 Michael Hanselmann
526 45bc5e4a Michael Hanselmann
  assert 0 <= seconds, \
527 45bc5e4a Michael Hanselmann
    "Seconds must be larger than or equal to 0, but are %s" % seconds
528 45bc5e4a Michael Hanselmann
  assert 0 <= microseconds <= 999999, \
529 45bc5e4a Michael Hanselmann
    "Microseconds must be 0-999999, but are %s" % microseconds
530 739be818 Michael Hanselmann
531 45bc5e4a Michael Hanselmann
  return float(seconds) + (float(microseconds) * 0.000001)
532 739be818 Michael Hanselmann
533 739be818 Michael Hanselmann
534 c28911dd Michele Tartara
def EpochNano():
535 c28911dd Michele Tartara
  """Return the current timestamp expressed as number of nanoseconds since the
536 c28911dd Michele Tartara
  unix epoch
537 c28911dd Michele Tartara

538 c28911dd Michele Tartara
  @return: nanoseconds since the Unix epoch
539 c28911dd Michele Tartara

540 c28911dd Michele Tartara
  """
541 c28911dd Michele Tartara
  return int(time.time() * 1000000000)
542 c28911dd Michele Tartara
543 c28911dd Michele Tartara
544 691c81b7 Michael Hanselmann
def FindMatch(data, name):
545 691c81b7 Michael Hanselmann
  """Tries to find an item in a dictionary matching a name.
546 691c81b7 Michael Hanselmann

547 691c81b7 Michael Hanselmann
  Callers have to ensure the data names aren't contradictory (e.g. a regexp
548 691c81b7 Michael Hanselmann
  that matches a string). If the name isn't a direct key, all regular
549 691c81b7 Michael Hanselmann
  expression objects in the dictionary are matched against it.
550 691c81b7 Michael Hanselmann

551 691c81b7 Michael Hanselmann
  @type data: dict
552 691c81b7 Michael Hanselmann
  @param data: Dictionary containing data
553 691c81b7 Michael Hanselmann
  @type name: string
554 691c81b7 Michael Hanselmann
  @param name: Name to look for
555 691c81b7 Michael Hanselmann
  @rtype: tuple; (value in dictionary, matched groups as list)
556 691c81b7 Michael Hanselmann

557 691c81b7 Michael Hanselmann
  """
558 691c81b7 Michael Hanselmann
  if name in data:
559 691c81b7 Michael Hanselmann
    return (data[name], [])
560 691c81b7 Michael Hanselmann
561 691c81b7 Michael Hanselmann
  for key, value in data.items():
562 691c81b7 Michael Hanselmann
    # Regex objects
563 691c81b7 Michael Hanselmann
    if hasattr(key, "match"):
564 691c81b7 Michael Hanselmann
      m = key.match(name)
565 691c81b7 Michael Hanselmann
      if m:
566 691c81b7 Michael Hanselmann
        return (value, list(m.groups()))
567 691c81b7 Michael Hanselmann
568 691c81b7 Michael Hanselmann
  return None
569 691c81b7 Michael Hanselmann
570 691c81b7 Michael Hanselmann
571 1b045f5d Balazs Lecz
def GetMounts(filename=constants.PROC_MOUNTS):
572 1b045f5d Balazs Lecz
  """Returns the list of mounted filesystems.
573 1b045f5d Balazs Lecz

574 1b045f5d Balazs Lecz
  This function is Linux-specific.
575 1b045f5d Balazs Lecz

576 1b045f5d Balazs Lecz
  @param filename: path of mounts file (/proc/mounts by default)
577 1b045f5d Balazs Lecz
  @rtype: list of tuples
578 1b045f5d Balazs Lecz
  @return: list of mount entries (device, mountpoint, fstype, options)
579 1b045f5d Balazs Lecz

580 1b045f5d Balazs Lecz
  """
581 1b045f5d Balazs Lecz
  # TODO(iustin): investigate non-Linux options (e.g. via mount output)
582 1b045f5d Balazs Lecz
  data = []
583 1b045f5d Balazs Lecz
  mountlines = ReadFile(filename).splitlines()
584 1b045f5d Balazs Lecz
  for line in mountlines:
585 1b045f5d Balazs Lecz
    device, mountpoint, fstype, options, _ = line.split(None, 4)
586 1b045f5d Balazs Lecz
    data.append((device, mountpoint, fstype, options))
587 1b045f5d Balazs Lecz
588 1b045f5d Balazs Lecz
  return data
589 1b045f5d Balazs Lecz
590 1b045f5d Balazs Lecz
591 451575de Guido Trotter
def SignalHandled(signums):
592 451575de Guido Trotter
  """Signal Handled decoration.
593 451575de Guido Trotter

594 451575de Guido Trotter
  This special decorator installs a signal handler and then calls the target
595 451575de Guido Trotter
  function. The function must accept a 'signal_handlers' keyword argument,
596 451575de Guido Trotter
  which will contain a dict indexed by signal number, with SignalHandler
597 451575de Guido Trotter
  objects as values.
598 451575de Guido Trotter

599 451575de Guido Trotter
  The decorator can be safely stacked with iself, to handle multiple signals
600 451575de Guido Trotter
  with different handlers.
601 451575de Guido Trotter

602 451575de Guido Trotter
  @type signums: list
603 451575de Guido Trotter
  @param signums: signals to intercept
604 451575de Guido Trotter

605 451575de Guido Trotter
  """
606 451575de Guido Trotter
  def wrap(fn):
607 451575de Guido Trotter
    def sig_function(*args, **kwargs):
608 d0c8c01d Iustin Pop
      assert "signal_handlers" not in kwargs or \
609 d0c8c01d Iustin Pop
             kwargs["signal_handlers"] is None or \
610 d0c8c01d Iustin Pop
             isinstance(kwargs["signal_handlers"], dict), \
611 451575de Guido Trotter
             "Wrong signal_handlers parameter in original function call"
612 d0c8c01d Iustin Pop
      if "signal_handlers" in kwargs and kwargs["signal_handlers"] is not None:
613 d0c8c01d Iustin Pop
        signal_handlers = kwargs["signal_handlers"]
614 451575de Guido Trotter
      else:
615 451575de Guido Trotter
        signal_handlers = {}
616 d0c8c01d Iustin Pop
        kwargs["signal_handlers"] = signal_handlers
617 451575de Guido Trotter
      sighandler = SignalHandler(signums)
618 451575de Guido Trotter
      try:
619 451575de Guido Trotter
        for sig in signums:
620 451575de Guido Trotter
          signal_handlers[sig] = sighandler
621 451575de Guido Trotter
        return fn(*args, **kwargs)
622 451575de Guido Trotter
      finally:
623 451575de Guido Trotter
        sighandler.Reset()
624 451575de Guido Trotter
    return sig_function
625 451575de Guido Trotter
  return wrap
626 451575de Guido Trotter
627 451575de Guido Trotter
628 f8326fca Andrea Spadaccini
def TimeoutExpired(epoch, timeout, _time_fn=time.time):
629 f8326fca Andrea Spadaccini
  """Checks whether a timeout has expired.
630 f8326fca Andrea Spadaccini

631 f8326fca Andrea Spadaccini
  """
632 f8326fca Andrea Spadaccini
  return _time_fn() > (epoch + timeout)
633 f8326fca Andrea Spadaccini
634 f8326fca Andrea Spadaccini
635 b9768937 Michael Hanselmann
class SignalWakeupFd(object):
636 b9768937 Michael Hanselmann
  try:
637 b9768937 Michael Hanselmann
    # This is only supported in Python 2.5 and above (some distributions
638 b9768937 Michael Hanselmann
    # backported it to Python 2.4)
639 b9768937 Michael Hanselmann
    _set_wakeup_fd_fn = signal.set_wakeup_fd
640 b9768937 Michael Hanselmann
  except AttributeError:
641 b9768937 Michael Hanselmann
    # Not supported
642 3c286190 Dimitris Aragiorgis
643 b459a848 Andrea Spadaccini
    def _SetWakeupFd(self, _): # pylint: disable=R0201
644 b9768937 Michael Hanselmann
      return -1
645 b9768937 Michael Hanselmann
  else:
646 3c286190 Dimitris Aragiorgis
647 b9768937 Michael Hanselmann
    def _SetWakeupFd(self, fd):
648 b9768937 Michael Hanselmann
      return self._set_wakeup_fd_fn(fd)
649 b9768937 Michael Hanselmann
650 b9768937 Michael Hanselmann
  def __init__(self):
651 b9768937 Michael Hanselmann
    """Initializes this class.
652 b9768937 Michael Hanselmann

653 b9768937 Michael Hanselmann
    """
654 b9768937 Michael Hanselmann
    (read_fd, write_fd) = os.pipe()
655 b9768937 Michael Hanselmann
656 b9768937 Michael Hanselmann
    # Once these succeeded, the file descriptors will be closed automatically.
657 b9768937 Michael Hanselmann
    # Buffer size 0 is important, otherwise .read() with a specified length
658 b9768937 Michael Hanselmann
    # might buffer data and the file descriptors won't be marked readable.
659 b9768937 Michael Hanselmann
    self._read_fh = os.fdopen(read_fd, "r", 0)
660 b9768937 Michael Hanselmann
    self._write_fh = os.fdopen(write_fd, "w", 0)
661 b9768937 Michael Hanselmann
662 b9768937 Michael Hanselmann
    self._previous = self._SetWakeupFd(self._write_fh.fileno())
663 b9768937 Michael Hanselmann
664 b9768937 Michael Hanselmann
    # Utility functions
665 b9768937 Michael Hanselmann
    self.fileno = self._read_fh.fileno
666 b9768937 Michael Hanselmann
    self.read = self._read_fh.read
667 b9768937 Michael Hanselmann
668 b9768937 Michael Hanselmann
  def Reset(self):
669 b9768937 Michael Hanselmann
    """Restores the previous wakeup file descriptor.
670 b9768937 Michael Hanselmann

671 b9768937 Michael Hanselmann
    """
672 b9768937 Michael Hanselmann
    if hasattr(self, "_previous") and self._previous is not None:
673 b9768937 Michael Hanselmann
      self._SetWakeupFd(self._previous)
674 b9768937 Michael Hanselmann
      self._previous = None
675 b9768937 Michael Hanselmann
676 b9768937 Michael Hanselmann
  def Notify(self):
677 b9768937 Michael Hanselmann
    """Notifies the wakeup file descriptor.
678 b9768937 Michael Hanselmann

679 b9768937 Michael Hanselmann
    """
680 edada04b Michele Tartara
    self._write_fh.write(chr(0))
681 b9768937 Michael Hanselmann
682 b9768937 Michael Hanselmann
  def __del__(self):
683 b9768937 Michael Hanselmann
    """Called before object deletion.
684 b9768937 Michael Hanselmann

685 b9768937 Michael Hanselmann
    """
686 b9768937 Michael Hanselmann
    self.Reset()
687 b9768937 Michael Hanselmann
688 b9768937 Michael Hanselmann
689 de499029 Michael Hanselmann
class SignalHandler(object):
690 de499029 Michael Hanselmann
  """Generic signal handler class.
691 de499029 Michael Hanselmann

692 58885d79 Iustin Pop
  It automatically restores the original handler when deconstructed or
693 58885d79 Iustin Pop
  when L{Reset} is called. You can either pass your own handler
694 58885d79 Iustin Pop
  function in or query the L{called} attribute to detect whether the
695 58885d79 Iustin Pop
  signal was sent.
696 58885d79 Iustin Pop

697 58885d79 Iustin Pop
  @type signum: list
698 58885d79 Iustin Pop
  @ivar signum: the signals we handle
699 58885d79 Iustin Pop
  @type called: boolean
700 58885d79 Iustin Pop
  @ivar called: tracks whether any of the signals have been raised
701 de499029 Michael Hanselmann

702 de499029 Michael Hanselmann
  """
703 b9768937 Michael Hanselmann
  def __init__(self, signum, handler_fn=None, wakeup=None):
704 de499029 Michael Hanselmann
    """Constructs a new SignalHandler instance.
705 de499029 Michael Hanselmann

706 58885d79 Iustin Pop
    @type signum: int or list of ints
707 de499029 Michael Hanselmann
    @param signum: Single signal number or set of signal numbers
708 92b61ec7 Michael Hanselmann
    @type handler_fn: callable
709 92b61ec7 Michael Hanselmann
    @param handler_fn: Signal handling function
710 de499029 Michael Hanselmann

711 de499029 Michael Hanselmann
    """
712 92b61ec7 Michael Hanselmann
    assert handler_fn is None or callable(handler_fn)
713 92b61ec7 Michael Hanselmann
714 6c52849e Guido Trotter
    self.signum = set(signum)
715 de499029 Michael Hanselmann
    self.called = False
716 de499029 Michael Hanselmann
717 92b61ec7 Michael Hanselmann
    self._handler_fn = handler_fn
718 b9768937 Michael Hanselmann
    self._wakeup = wakeup
719 92b61ec7 Michael Hanselmann
720 de499029 Michael Hanselmann
    self._previous = {}
721 de499029 Michael Hanselmann
    try:
722 de499029 Michael Hanselmann
      for signum in self.signum:
723 de499029 Michael Hanselmann
        # Setup handler
724 de499029 Michael Hanselmann
        prev_handler = signal.signal(signum, self._HandleSignal)
725 de499029 Michael Hanselmann
        try:
726 de499029 Michael Hanselmann
          self._previous[signum] = prev_handler
727 de499029 Michael Hanselmann
        except:
728 de499029 Michael Hanselmann
          # Restore previous handler
729 de499029 Michael Hanselmann
          signal.signal(signum, prev_handler)
730 de499029 Michael Hanselmann
          raise
731 de499029 Michael Hanselmann
    except:
732 de499029 Michael Hanselmann
      # Reset all handlers
733 de499029 Michael Hanselmann
      self.Reset()
734 de499029 Michael Hanselmann
      # Here we have a race condition: a handler may have already been called,
735 de499029 Michael Hanselmann
      # but there's not much we can do about it at this point.
736 de499029 Michael Hanselmann
      raise
737 de499029 Michael Hanselmann
738 de499029 Michael Hanselmann
  def __del__(self):
739 de499029 Michael Hanselmann
    self.Reset()
740 de499029 Michael Hanselmann
741 de499029 Michael Hanselmann
  def Reset(self):
742 de499029 Michael Hanselmann
    """Restore previous handler.
743 de499029 Michael Hanselmann

744 58885d79 Iustin Pop
    This will reset all the signals to their previous handlers.
745 58885d79 Iustin Pop

746 de499029 Michael Hanselmann
    """
747 de499029 Michael Hanselmann
    for signum, prev_handler in self._previous.items():
748 de499029 Michael Hanselmann
      signal.signal(signum, prev_handler)
749 de499029 Michael Hanselmann
      # If successful, remove from dict
750 de499029 Michael Hanselmann
      del self._previous[signum]
751 de499029 Michael Hanselmann
752 de499029 Michael Hanselmann
  def Clear(self):
753 58885d79 Iustin Pop
    """Unsets the L{called} flag.
754 de499029 Michael Hanselmann

755 de499029 Michael Hanselmann
    This function can be used in case a signal may arrive several times.
756 de499029 Michael Hanselmann

757 de499029 Michael Hanselmann
    """
758 de499029 Michael Hanselmann
    self.called = False
759 de499029 Michael Hanselmann
760 92b61ec7 Michael Hanselmann
  def _HandleSignal(self, signum, frame):
761 de499029 Michael Hanselmann
    """Actual signal handling function.
762 de499029 Michael Hanselmann

763 de499029 Michael Hanselmann
    """
764 de499029 Michael Hanselmann
    # This is not nice and not absolutely atomic, but it appears to be the only
765 de499029 Michael Hanselmann
    # solution in Python -- there are no atomic types.
766 de499029 Michael Hanselmann
    self.called = True
767 a2d2e1a7 Iustin Pop
768 b9768937 Michael Hanselmann
    if self._wakeup:
769 b9768937 Michael Hanselmann
      # Notify whoever is interested in signals
770 b9768937 Michael Hanselmann
      self._wakeup.Notify()
771 b9768937 Michael Hanselmann
772 92b61ec7 Michael Hanselmann
    if self._handler_fn:
773 92b61ec7 Michael Hanselmann
      self._handler_fn(signum, frame)
774 92b61ec7 Michael Hanselmann
775 a2d2e1a7 Iustin Pop
776 a2d2e1a7 Iustin Pop
class FieldSet(object):
777 a2d2e1a7 Iustin Pop
  """A simple field set.
778 a2d2e1a7 Iustin Pop

779 a2d2e1a7 Iustin Pop
  Among the features are:
780 a2d2e1a7 Iustin Pop
    - checking if a string is among a list of static string or regex objects
781 a2d2e1a7 Iustin Pop
    - checking if a whole list of string matches
782 a2d2e1a7 Iustin Pop
    - returning the matching groups from a regex match
783 a2d2e1a7 Iustin Pop

784 a2d2e1a7 Iustin Pop
  Internally, all fields are held as regular expression objects.
785 a2d2e1a7 Iustin Pop

786 a2d2e1a7 Iustin Pop
  """
787 a2d2e1a7 Iustin Pop
  def __init__(self, *items):
788 a2d2e1a7 Iustin Pop
    self.items = [re.compile("^%s$" % value) for value in items]
789 a2d2e1a7 Iustin Pop
790 a2d2e1a7 Iustin Pop
  def Extend(self, other_set):
791 a2d2e1a7 Iustin Pop
    """Extend the field set with the items from another one"""
792 a2d2e1a7 Iustin Pop
    self.items.extend(other_set.items)
793 a2d2e1a7 Iustin Pop
794 a2d2e1a7 Iustin Pop
  def Matches(self, field):
795 a2d2e1a7 Iustin Pop
    """Checks if a field matches the current set
796 a2d2e1a7 Iustin Pop

797 a2d2e1a7 Iustin Pop
    @type field: str
798 a2d2e1a7 Iustin Pop
    @param field: the string to match
799 6c881c52 Iustin Pop
    @return: either None or a regular expression match object
800 a2d2e1a7 Iustin Pop

801 a2d2e1a7 Iustin Pop
    """
802 a2d2e1a7 Iustin Pop
    for m in itertools.ifilter(None, (val.match(field) for val in self.items)):
803 a2d2e1a7 Iustin Pop
      return m
804 6c881c52 Iustin Pop
    return None
805 a2d2e1a7 Iustin Pop
806 a2d2e1a7 Iustin Pop
  def NonMatching(self, items):
807 a2d2e1a7 Iustin Pop
    """Returns the list of fields not matching the current set
808 a2d2e1a7 Iustin Pop

809 a2d2e1a7 Iustin Pop
    @type items: list
810 a2d2e1a7 Iustin Pop
    @param items: the list of fields to check
811 a2d2e1a7 Iustin Pop
    @rtype: list
812 a2d2e1a7 Iustin Pop
    @return: list of non-matching fields
813 a2d2e1a7 Iustin Pop

814 a2d2e1a7 Iustin Pop
    """
815 a2d2e1a7 Iustin Pop
    return [val for val in items if not self.Matches(val)]
816 651cc3e2 Christos Stavrakakis
817 651cc3e2 Christos Stavrakakis
818 651cc3e2 Christos Stavrakakis
def ValidateDeviceNames(kind, container):
819 651cc3e2 Christos Stavrakakis
  """Validate instance device names.
820 651cc3e2 Christos Stavrakakis

821 651cc3e2 Christos Stavrakakis
  Check that a device container contains only unique and valid names.
822 651cc3e2 Christos Stavrakakis

823 651cc3e2 Christos Stavrakakis
  @type kind: string
824 651cc3e2 Christos Stavrakakis
  @param kind: One-word item description
825 651cc3e2 Christos Stavrakakis
  @type container: list
826 651cc3e2 Christos Stavrakakis
  @param container: Container containing the devices
827 651cc3e2 Christos Stavrakakis

828 651cc3e2 Christos Stavrakakis
  """
829 651cc3e2 Christos Stavrakakis
830 651cc3e2 Christos Stavrakakis
  valid = []
831 651cc3e2 Christos Stavrakakis
  for device in container:
832 651cc3e2 Christos Stavrakakis
    if isinstance(device, dict):
833 651cc3e2 Christos Stavrakakis
      if kind == "NIC":
834 651cc3e2 Christos Stavrakakis
        name = device.get(constants.INIC_NAME, None)
835 651cc3e2 Christos Stavrakakis
      elif kind == "disk":
836 651cc3e2 Christos Stavrakakis
        name = device.get(constants.IDISK_NAME, None)
837 651cc3e2 Christos Stavrakakis
      else:
838 651cc3e2 Christos Stavrakakis
        raise errors.OpPrereqError("Invalid container kind '%s'" % kind,
839 651cc3e2 Christos Stavrakakis
                                   errors.ECODE_INVAL)
840 651cc3e2 Christos Stavrakakis
    else:
841 651cc3e2 Christos Stavrakakis
      name = device.name
842 651cc3e2 Christos Stavrakakis
      # Check that a device name is not the UUID of another device
843 651cc3e2 Christos Stavrakakis
      valid.append(device.uuid)
844 651cc3e2 Christos Stavrakakis
845 651cc3e2 Christos Stavrakakis
    try:
846 651cc3e2 Christos Stavrakakis
      int(name)
847 651cc3e2 Christos Stavrakakis
    except (ValueError, TypeError):
848 651cc3e2 Christos Stavrakakis
      pass
849 651cc3e2 Christos Stavrakakis
    else:
850 651cc3e2 Christos Stavrakakis
      raise errors.OpPrereqError("Invalid name '%s'. Purely numeric %s names"
851 651cc3e2 Christos Stavrakakis
                                 " are not allowed" % (name, kind),
852 651cc3e2 Christos Stavrakakis
                                 errors.ECODE_INVAL)
853 651cc3e2 Christos Stavrakakis
854 651cc3e2 Christos Stavrakakis
    if name is not None and name.lower() != constants.VALUE_NONE:
855 651cc3e2 Christos Stavrakakis
      if name in valid:
856 651cc3e2 Christos Stavrakakis
        raise errors.OpPrereqError("%s name '%s' already used" % (kind, name),
857 651cc3e2 Christos Stavrakakis
                                   errors.ECODE_NOTUNIQUE)
858 651cc3e2 Christos Stavrakakis
      else:
859 651cc3e2 Christos Stavrakakis
        valid.append(name)