utils.py 76.7 KB
Newer Older
Iustin Pop's avatar
Iustin Pop committed
1
#
Iustin Pop's avatar
Iustin Pop committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#

# Copyright (C) 2006, 2007 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


22 23 24 25
"""Ganeti utility module.

This module holds functions that can be used in both daemons (all) and
the command line scripts.
26

Iustin Pop's avatar
Iustin Pop committed
27 28 29 30 31
"""


import os
import time
32
import subprocess
Iustin Pop's avatar
Iustin Pop committed
33 34 35 36
import re
import socket
import tempfile
import shutil
37
import errno
38
import pwd
Guido Trotter's avatar
Guido Trotter committed
39
import itertools
40 41
import select
import fcntl
42
import resource
43
import logging
44
import logging.handlers
Michael Hanselmann's avatar
Michael Hanselmann committed
45
import signal
46 47
import datetime
import calendar
48 49

from cStringIO import StringIO
Iustin Pop's avatar
Iustin Pop committed
50

51 52 53 54 55 56
try:
  from hashlib import sha1
except ImportError:
  import sha
  sha1 = sha.new

Iustin Pop's avatar
Iustin Pop committed
57
from ganeti import errors
Iustin Pop's avatar
Iustin Pop committed
58
from ganeti import constants
Iustin Pop's avatar
Iustin Pop committed
59

60

Iustin Pop's avatar
Iustin Pop committed
61 62 63
_locksheld = []
_re_shell_unquoted = re.compile('^[-.,=:/_+@A-Za-z0-9]+$')

64
debug_locks = False
65 66

#: when set to True, L{RunCmd} is disabled
67
no_fork = False
68

69 70
_RANDOM_UUID_FILE = "/proc/sys/kernel/random/uuid"

71

Iustin Pop's avatar
Iustin Pop committed
72
class RunResult(object):
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
  """Holds the result of running external programs.

  @type exit_code: int
  @ivar exit_code: the exit code of the program, or None (if the program
      didn't exit())
  @type signal: int or None
  @ivar signal: the signal that caused the program to finish, or None
      (if the program wasn't terminated by a signal)
  @type stdout: str
  @ivar stdout: the standard output of the program
  @type stderr: str
  @ivar stderr: the standard error of the program
  @type failed: boolean
  @ivar failed: True in case the program was
      terminated by a signal or exited with a non-zero exit code
  @ivar fail_reason: a string detailing the termination reason
Iustin Pop's avatar
Iustin Pop committed
89 90 91 92 93 94

  """
  __slots__ = ["exit_code", "signal", "stdout", "stderr",
               "failed", "fail_reason", "cmd"]


Iustin Pop's avatar
Iustin Pop committed
95
  def __init__(self, exit_code, signal_, stdout, stderr, cmd):
Iustin Pop's avatar
Iustin Pop committed
96 97
    self.cmd = cmd
    self.exit_code = exit_code
Iustin Pop's avatar
Iustin Pop committed
98
    self.signal = signal_
Iustin Pop's avatar
Iustin Pop committed
99 100
    self.stdout = stdout
    self.stderr = stderr
Iustin Pop's avatar
Iustin Pop committed
101
    self.failed = (signal_ is not None or exit_code != 0)
Iustin Pop's avatar
Iustin Pop committed
102 103 104 105 106 107 108 109

    if self.signal is not None:
      self.fail_reason = "terminated by signal %s" % self.signal
    elif self.exit_code is not None:
      self.fail_reason = "exited with exit code %s" % self.exit_code
    else:
      self.fail_reason = "unable to determine termination reason"

110 111 112
    if self.failed:
      logging.debug("Command '%s' failed (%s); output: %s",
                    self.cmd, self.fail_reason, self.output)
113

Iustin Pop's avatar
Iustin Pop committed
114 115 116 117 118 119 120 121 122
  def _GetOutput(self):
    """Returns the combined stdout and stderr for easier usage.

    """
    return self.stdout + self.stderr

  output = property(_GetOutput, None, None, "Return full output")


Guido Trotter's avatar
Guido Trotter committed
123
def RunCmd(cmd, env=None, output=None, cwd='/', reset_env=False):
Iustin Pop's avatar
Iustin Pop committed
124 125 126 127 128
  """Execute a (shell) command.

  The command should not read from its standard input, as it will be
  closed.

Guido Trotter's avatar
Guido Trotter committed
129
  @type cmd: string or list
130
  @param cmd: Command to run
131
  @type env: dict
132
  @param env: Additional environment
133
  @type output: str
134
  @param output: if desired, the output of the command can be
135 136
      saved in a file instead of the RunResult instance; this
      parameter denotes the file name (if not None)
137 138 139
  @type cwd: string
  @param cwd: if specified, will be used as the working
      directory for the command; the default will be /
Guido Trotter's avatar
Guido Trotter committed
140 141
  @type reset_env: boolean
  @param reset_env: whether to reset or keep the default os environment
142
  @rtype: L{RunResult}
143
  @return: RunResult instance
Michael Hanselmann's avatar
Michael Hanselmann committed
144
  @raise errors.ProgrammerError: if we call this when forks are disabled
Iustin Pop's avatar
Iustin Pop committed
145 146

  """
147 148 149
  if no_fork:
    raise errors.ProgrammerError("utils.RunCmd() called with fork() disabled")

Iustin Pop's avatar
Iustin Pop committed
150 151
  if isinstance(cmd, list):
    cmd = [str(val) for val in cmd]
152 153 154 155 156
    strcmd = " ".join(cmd)
    shell = False
  else:
    strcmd = cmd
    shell = True
157
  logging.debug("RunCmd '%s'", strcmd)
158

Guido Trotter's avatar
Guido Trotter committed
159 160 161 162 163 164
  if not reset_env:
    cmd_env = os.environ.copy()
    cmd_env["LC_ALL"] = "C"
  else:
    cmd_env = {}

165 166 167
  if env is not None:
    cmd_env.update(env)

168 169 170 171 172 173 174 175 176 177 178 179
  try:
    if output is None:
      out, err, status = _RunCmdPipe(cmd, cmd_env, shell, cwd)
    else:
      status = _RunCmdFile(cmd, cmd_env, shell, output, cwd)
      out = err = ""
  except OSError, err:
    if err.errno == errno.ENOENT:
      raise errors.OpExecError("Can't execute '%s': not found (%s)" %
                               (strcmd, err))
    else:
      raise
180 181 182 183 184 185 186 187 188 189

  if status >= 0:
    exitcode = status
    signal_ = None
  else:
    exitcode = None
    signal_ = -status

  return RunResult(exitcode, signal_, out, err, strcmd)

190

191
def _RunCmdPipe(cmd, env, via_shell, cwd):
192 193 194 195 196 197 198 199
  """Run a command and return its output.

  @type  cmd: string or list
  @param cmd: Command to run
  @type env: dict
  @param env: The environment to use
  @type via_shell: bool
  @param via_shell: if we should run via the shell
200 201
  @type cwd: string
  @param cwd: the working directory for the program
202 203 204 205
  @rtype: tuple
  @return: (out, err, status)

  """
206
  poller = select.poll()
207
  child = subprocess.Popen(cmd, shell=via_shell,
208 209 210
                           stderr=subprocess.PIPE,
                           stdout=subprocess.PIPE,
                           stdin=subprocess.PIPE,
211 212
                           close_fds=True, env=env,
                           cwd=cwd)
213 214

  child.stdin.close()
215 216 217 218 219 220 221 222 223 224 225 226 227
  poller.register(child.stdout, select.POLLIN)
  poller.register(child.stderr, select.POLLIN)
  out = StringIO()
  err = StringIO()
  fdmap = {
    child.stdout.fileno(): (out, child.stdout),
    child.stderr.fileno(): (err, child.stderr),
    }
  for fd in fdmap:
    status = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, status | os.O_NONBLOCK)

  while fdmap:
228 229 230 231 232 233 234 235 236 237 238 239
    try:
      pollresult = poller.poll()
    except EnvironmentError, eerr:
      if eerr.errno == errno.EINTR:
        continue
      raise
    except select.error, serr:
      if serr[0] == errno.EINTR:
        continue
      raise

    for fd, event in pollresult:
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
      if event & select.POLLIN or event & select.POLLPRI:
        data = fdmap[fd][1].read()
        # no data from read signifies EOF (the same as POLLHUP)
        if not data:
          poller.unregister(fd)
          del fdmap[fd]
          continue
        fdmap[fd][0].write(data)
      if (event & select.POLLNVAL or event & select.POLLHUP or
          event & select.POLLERR):
        poller.unregister(fd)
        del fdmap[fd]

  out = out.getvalue()
  err = err.getvalue()
Iustin Pop's avatar
Iustin Pop committed
255 256

  status = child.wait()
257
  return out, err, status
Iustin Pop's avatar
Iustin Pop committed
258

259

260
def _RunCmdFile(cmd, env, via_shell, output, cwd):
261 262 263 264 265 266 267 268 269 270
  """Run a command and save its output to a file.

  @type  cmd: string or list
  @param cmd: Command to run
  @type env: dict
  @param env: The environment to use
  @type via_shell: bool
  @param via_shell: if we should run via the shell
  @type output: str
  @param output: the filename in which to save the output
271 272
  @type cwd: string
  @param cwd: the working directory for the program
273 274 275 276 277 278 279 280 281 282
  @rtype: int
  @return: the exit status

  """
  fh = open(output, "a")
  try:
    child = subprocess.Popen(cmd, shell=via_shell,
                             stderr=subprocess.STDOUT,
                             stdout=fh,
                             stdin=subprocess.PIPE,
283 284
                             close_fds=True, env=env,
                             cwd=cwd)
285 286 287 288 289 290

    child.stdin.close()
    status = child.wait()
  finally:
    fh.close()
  return status
Iustin Pop's avatar
Iustin Pop committed
291 292


293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
def RunParts(dir_name, env=None, reset_env=False):
  """Run Scripts or programs in a directory

  @type dir_name: string
  @param dir_name: absolute path to a directory
  @type env: dict
  @param env: The environment to use
  @type reset_env: boolean
  @param reset_env: whether to reset or keep the default os environment
  @rtype: list of tuples
  @return: list of (name, (one of RUNDIR_STATUS), RunResult)

  """
  rr = []

  try:
    dir_contents = ListVisibleFiles(dir_name)
  except OSError, err:
    logging.warning("RunParts: skipping %s (cannot list: %s)", dir_name, err)
    return rr

  for relname in sorted(dir_contents):
315
    fname = PathJoin(dir_name, relname)
316 317 318 319 320 321 322 323 324 325 326 327 328 329
    if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
            constants.EXT_PLUGIN_MASK.match(relname) is not None):
      rr.append((relname, constants.RUNPARTS_SKIP, None))
    else:
      try:
        result = RunCmd([fname], env=env, reset_env=reset_env)
      except Exception, err: # pylint: disable-msg=W0703
        rr.append((relname, constants.RUNPARTS_ERR, str(err)))
      else:
        rr.append((relname, constants.RUNPARTS_RUN, result))

  return rr


Iustin Pop's avatar
Iustin Pop committed
330 331 332 333 334 335
def RemoveFile(filename):
  """Remove a file ignoring some errors.

  Remove a file, ignoring non-existing ones or directories. Other
  errors are passed.

336 337 338
  @type filename: str
  @param filename: the file to be removed

Iustin Pop's avatar
Iustin Pop committed
339 340 341 342
  """
  try:
    os.unlink(filename)
  except OSError, err:
343
    if err.errno not in (errno.ENOENT, errno.EISDIR):
Iustin Pop's avatar
Iustin Pop committed
344 345 346
      raise


347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
def RenameFile(old, new, mkdir=False, mkdir_mode=0750):
  """Renames a file.

  @type old: string
  @param old: Original path
  @type new: string
  @param new: New path
  @type mkdir: bool
  @param mkdir: Whether to create target directory if it doesn't exist
  @type mkdir_mode: int
  @param mkdir_mode: Mode for newly created directories

  """
  try:
    return os.rename(old, new)
  except OSError, err:
    # In at least one use case of this function, the job queue, directory
    # creation is very rare. Checking for the directory before renaming is not
    # as efficient.
    if mkdir and err.errno == errno.ENOENT:
      # Create directory and try again
368 369 370 371 372 373 374 375 376
      dirname = os.path.dirname(new)
      try:
        os.makedirs(dirname, mode=mkdir_mode)
      except OSError, err:
        # Ignore EEXIST. This is only handled in os.makedirs as included in
        # Python 2.5 and above.
        if err.errno != errno.EEXIST or not os.path.exists(dirname):
          raise

377
      return os.rename(old, new)
378

379 380 381
    raise


382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
def ResetTempfileModule():
  """Resets the random name generator of the tempfile module.

  This function should be called after C{os.fork} in the child process to
  ensure it creates a newly seeded random generator. Otherwise it would
  generate the same random parts as the parent process. If several processes
  race for the creation of a temporary file, this could lead to one not getting
  a temporary name.

  """
  # pylint: disable-msg=W0212
  if hasattr(tempfile, "_once_lock") and hasattr(tempfile, "_name_sequence"):
    tempfile._once_lock.acquire()
    try:
      # Reset random name generator
      tempfile._name_sequence = None
    finally:
      tempfile._once_lock.release()
  else:
    logging.critical("The tempfile module misses at least one of the"
                     " '_once_lock' and '_name_sequence' attributes")


Iustin Pop's avatar
Iustin Pop committed
405 406 407 408 409 410
def _FingerprintFile(filename):
  """Compute the fingerprint of a file.

  If the file does not exist, a None will be returned
  instead.

411 412 413 414 415
  @type filename: str
  @param filename: the filename to checksum
  @rtype: str
  @return: the hex digest of the sha checksum of the contents
      of the file
Iustin Pop's avatar
Iustin Pop committed
416 417 418 419 420 421 422

  """
  if not (os.path.exists(filename) and os.path.isfile(filename)):
    return None

  f = open(filename)

423
  fp = sha1()
Iustin Pop's avatar
Iustin Pop committed
424 425 426 427 428 429 430 431 432 433 434 435 436
  while True:
    data = f.read(4096)
    if not data:
      break

    fp.update(data)

  return fp.hexdigest()


def FingerprintFiles(files):
  """Compute fingerprints for a list of files.

437 438 439 440 441
  @type files: list
  @param files: the list of filename to fingerprint
  @rtype: dict
  @return: a dictionary filename: fingerprint, holding only
      existing files
Iustin Pop's avatar
Iustin Pop committed
442 443 444 445 446 447 448 449 450 451 452 453

  """
  ret = {}

  for filename in files:
    cksum = _FingerprintFile(filename)
    if cksum:
      ret[filename] = cksum

  return ret


454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
def ForceDictType(target, key_types, allowed_values=None):
  """Force the values of a dict to have certain types.

  @type target: dict
  @param target: the dict to update
  @type key_types: dict
  @param key_types: dict mapping target dict keys to types
                    in constants.ENFORCEABLE_TYPES
  @type allowed_values: list
  @keyword allowed_values: list of specially allowed values

  """
  if allowed_values is None:
    allowed_values = []

469 470 471 472
  if not isinstance(target, dict):
    msg = "Expected dictionary, got '%s'" % target
    raise errors.TypeEnforcementError(msg)

473 474 475 476 477 478 479 480
  for key in target:
    if key not in key_types:
      msg = "Unknown key '%s'" % key
      raise errors.TypeEnforcementError(msg)

    if target[key] in allowed_values:
      continue

Iustin Pop's avatar
Iustin Pop committed
481 482 483
    ktype = key_types[key]
    if ktype not in constants.ENFORCEABLE_TYPES:
      msg = "'%s' has non-enforceable type %s" % (key, ktype)
484 485
      raise errors.ProgrammerError(msg)

Iustin Pop's avatar
Iustin Pop committed
486
    if ktype == constants.VTYPE_STRING:
487 488 489 490 491 492
      if not isinstance(target[key], basestring):
        if isinstance(target[key], bool) and not target[key]:
          target[key] = ''
        else:
          msg = "'%s' (value %s) is not a valid string" % (key, target[key])
          raise errors.TypeEnforcementError(msg)
Iustin Pop's avatar
Iustin Pop committed
493
    elif ktype == constants.VTYPE_BOOL:
494 495 496 497 498 499 500 501 502 503 504 505
      if isinstance(target[key], basestring) and target[key]:
        if target[key].lower() == constants.VALUE_FALSE:
          target[key] = False
        elif target[key].lower() == constants.VALUE_TRUE:
          target[key] = True
        else:
          msg = "'%s' (value %s) is not a valid boolean" % (key, target[key])
          raise errors.TypeEnforcementError(msg)
      elif target[key]:
        target[key] = True
      else:
        target[key] = False
Iustin Pop's avatar
Iustin Pop committed
506
    elif ktype == constants.VTYPE_SIZE:
507 508 509 510 511 512
      try:
        target[key] = ParseUnit(target[key])
      except errors.UnitParseError, err:
        msg = "'%s' (value %s) is not a valid size. error: %s" % \
              (key, target[key], err)
        raise errors.TypeEnforcementError(msg)
Iustin Pop's avatar
Iustin Pop committed
513
    elif ktype == constants.VTYPE_INT:
514 515 516 517 518 519 520
      try:
        target[key] = int(target[key])
      except (ValueError, TypeError):
        msg = "'%s' (value %s) is not a valid integer" % (key, target[key])
        raise errors.TypeEnforcementError(msg)


Iustin Pop's avatar
Iustin Pop committed
521 522 523
def IsProcessAlive(pid):
  """Check if a given pid exists on the system.

524 525
  @note: zombie status is not handled, so zombie processes
      will be returned as alive
526 527 528 529
  @type pid: int
  @param pid: the process ID to check
  @rtype: boolean
  @return: True if the process exists
Iustin Pop's avatar
Iustin Pop committed
530 531

  """
532 533 534
  if pid <= 0:
    return False

Iustin Pop's avatar
Iustin Pop committed
535
  try:
536 537 538
    os.stat("/proc/%d/status" % pid)
    return True
  except EnvironmentError, err:
539
    if err.errno in (errno.ENOENT, errno.ENOTDIR):
Iustin Pop's avatar
Iustin Pop committed
540
      return False
541
    raise
Iustin Pop's avatar
Iustin Pop committed
542 543


544
def ReadPidFile(pidfile):
545
  """Read a pid from a file.
546

547 548 549
  @type  pidfile: string
  @param pidfile: path to the file containing the pid
  @rtype: int
550
  @return: The process id, if the file exists and contains a valid PID,
551
           otherwise 0
552 553 554

  """
  try:
555
    raw_data = ReadFile(pidfile)
556 557
  except EnvironmentError, err:
    if err.errno != errno.ENOENT:
558
      logging.exception("Can't read pid file")
559
    return 0
560 561

  try:
562
    pid = int(raw_data)
563
  except (TypeError, ValueError), err:
564
    logging.info("Can't parse pid file contents", exc_info=True)
565
    return 0
566

567
  return pid
568 569


570
def MatchNameComponent(key, name_list, case_sensitive=True):
Iustin Pop's avatar
Iustin Pop committed
571 572 573
  """Try to match a name against a list.

  This function will try to match a name like test1 against a list
574 575 576 577
  like C{['test1.example.com', 'test2.example.com', ...]}. Against
  this list, I{'test1'} as well as I{'test1.example'} will match, but
  not I{'test1.ex'}. A multiple match will be considered as no match
  at all (e.g. I{'test1'} against C{['test1.example.com',
578 579
  'test1.example.org']}), except when the key fully matches an entry
  (e.g. I{'test1'} against C{['test1', 'test1.example.com']}).
Iustin Pop's avatar
Iustin Pop committed
580

581 582 583 584
  @type key: str
  @param key: the name to be searched
  @type name_list: list
  @param name_list: the list of strings against which to search the key
585 586
  @type case_sensitive: boolean
  @param case_sensitive: whether to provide a case-sensitive match
Iustin Pop's avatar
Iustin Pop committed
587

588 589 590
  @rtype: None or str
  @return: None if there is no match I{or} if there are multiple matches,
      otherwise the element from the list which matches
Iustin Pop's avatar
Iustin Pop committed
591 592

  """
593 594
  if key in name_list:
    return key
595 596 597 598

  re_flags = 0
  if not case_sensitive:
    re_flags |= re.IGNORECASE
599
    key = key.upper()
600 601 602 603 604 605
  mo = re.compile("^%s(\..*)?$" % re.escape(key), re_flags)
  names_filtered = []
  string_matches = []
  for name in name_list:
    if mo.match(name) is not None:
      names_filtered.append(name)
606
      if not case_sensitive and key == name.upper():
607 608 609 610 611 612 613
        string_matches.append(name)

  if len(string_matches) == 1:
    return string_matches[0]
  if len(names_filtered) == 1:
    return names_filtered[0]
  return None
Iustin Pop's avatar
Iustin Pop committed
614 615


616
class HostInfo:
617
  """Class implementing resolver and hostname functionality
618 619

  """
620 621
  _VALID_NAME_RE = re.compile("^[a-z0-9._-]{1,255}$")

622
  def __init__(self, name=None):
623 624
    """Initialize the host name object.

625 626
    If the name argument is not passed, it will use this system's
    name.
627 628

    """
629 630 631 632 633
    if name is None:
      name = self.SysName()

    self.query = name
    self.name, self.aliases, self.ipaddrs = self.LookupHostname(name)
634 635
    self.ip = self.ipaddrs[0]

636 637 638 639 640 641
  def ShortName(self):
    """Returns the hostname without domain.

    """
    return self.name.split('.')[0]

642 643 644
  @staticmethod
  def SysName():
    """Return the current system's name.
645

646
    This is simply a wrapper over C{socket.gethostname()}.
Iustin Pop's avatar
Iustin Pop committed
647

648 649
    """
    return socket.gethostname()
Iustin Pop's avatar
Iustin Pop committed
650

651 652 653
  @staticmethod
  def LookupHostname(hostname):
    """Look up hostname
Iustin Pop's avatar
Iustin Pop committed
654

655 656
    @type hostname: str
    @param hostname: hostname to look up
657

658 659 660 661
    @rtype: tuple
    @return: a tuple (name, aliases, ipaddrs) as returned by
        C{socket.gethostbyname_ex}
    @raise errors.ResolverError: in case of errors in resolving
662 663 664 665 666 667 668

    """
    try:
      result = socket.gethostbyname_ex(hostname)
    except socket.gaierror, err:
      # hostname not found in DNS
      raise errors.ResolverError(hostname, err.args[0], err.args[1])
Iustin Pop's avatar
Iustin Pop committed
669

670
    return result
Iustin Pop's avatar
Iustin Pop committed
671

672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
  @classmethod
  def NormalizeName(cls, hostname):
    """Validate and normalize the given hostname.

    @attention: the validation is a bit more relaxed than the standards
        require; most importantly, we allow underscores in names
    @raise errors.OpPrereqError: when the name is not valid

    """
    hostname = hostname.lower()
    if (not cls._VALID_NAME_RE.match(hostname) or
        # double-dots, meaning empty label
        ".." in hostname or
        # empty initial label
        hostname.startswith(".")):
      raise errors.OpPrereqError("Invalid hostname '%s'" % hostname,
                                 errors.ECODE_INVAL)
    if hostname.endswith("."):
      hostname = hostname.rstrip(".")
    return hostname

Iustin Pop's avatar
Iustin Pop committed
693

694 695 696 697 698 699 700 701 702 703
def GetHostInfo(name=None):
  """Lookup host name and raise an OpPrereqError for failures"""

  try:
    return HostInfo(name)
  except errors.ResolverError, err:
    raise errors.OpPrereqError("The given name (%s) does not resolve: %s" %
                               (err[0], err[2]), errors.ECODE_RESOLVER)


Iustin Pop's avatar
Iustin Pop committed
704 705 706
def ListVolumeGroups():
  """List volume groups and their size

707 708 709 710
  @rtype: dict
  @return:
       Dictionary with keys volume name and values
       the size of the volume
Iustin Pop's avatar
Iustin Pop committed
711 712 713 714 715 716 717 718 719 720 721 722 723

  """
  command = "vgs --noheadings --units m --nosuffix -o name,size"
  result = RunCmd(command)
  retval = {}
  if result.failed:
    return retval

  for line in result.stdout.splitlines():
    try:
      name, size = line.split()
      size = int(float(size))
    except (IndexError, ValueError), err:
724
      logging.error("Invalid output from vgs (%s): %s", err, line)
Iustin Pop's avatar
Iustin Pop committed
725 726 727 728 729 730 731 732 733 734
      continue

    retval[name] = size

  return retval


def BridgeExists(bridge):
  """Check whether the given bridge exists in the system

735 736 737 738
  @type bridge: str
  @param bridge: the bridge name to check
  @rtype: boolean
  @return: True if it does
Iustin Pop's avatar
Iustin Pop committed
739 740 741 742 743 744 745 746

  """
  return os.path.isdir("/sys/class/net/%s/bridge" % bridge)


def NiceSort(name_list):
  """Sort a list of strings based on digit and non-digit groupings.

747 748 749
  Given a list of names C{['a1', 'a10', 'a11', 'a2']} this function
  will sort the list in the logical order C{['a1', 'a2', 'a10',
  'a11']}.
Iustin Pop's avatar
Iustin Pop committed
750 751 752 753 754

  The sort algorithm breaks each name in groups of either only-digits
  or no-digits. Only the first eight such groups are considered, and
  after that we just use what's left of the string.

755 756 757 758
  @type name_list: list
  @param name_list: the names to be sorted
  @rtype: list
  @return: a copy of the name list sorted with our algorithm
Iustin Pop's avatar
Iustin Pop committed
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783

  """
  _SORTER_BASE = "(\D+|\d+)"
  _SORTER_FULL = "^%s%s?%s?%s?%s?%s?%s?%s?.*$" % (_SORTER_BASE, _SORTER_BASE,
                                                  _SORTER_BASE, _SORTER_BASE,
                                                  _SORTER_BASE, _SORTER_BASE,
                                                  _SORTER_BASE, _SORTER_BASE)
  _SORTER_RE = re.compile(_SORTER_FULL)
  _SORTER_NODIGIT = re.compile("^\D*$")
  def _TryInt(val):
    """Attempts to convert a variable to integer."""
    if val is None or _SORTER_NODIGIT.match(val):
      return val
    rval = int(val)
    return rval

  to_sort = [([_TryInt(grp) for grp in _SORTER_RE.match(name).groups()], name)
             for name in name_list]
  to_sort.sort()
  return [tup[1] for tup in to_sort]


def TryConvert(fn, val):
  """Try to convert a value ignoring errors.

784 785 786 787 788 789 790 791 792 793
  This function tries to apply function I{fn} to I{val}. If no
  C{ValueError} or C{TypeError} exceptions are raised, it will return
  the result, else it will return the original value. Any other
  exceptions are propagated to the caller.

  @type fn: callable
  @param fn: function to apply to the value
  @param val: the value to be converted
  @return: The converted value if the conversion was successful,
      otherwise the original value.
Iustin Pop's avatar
Iustin Pop committed
794 795 796 797

  """
  try:
    nv = fn(val)
Michael Hanselmann's avatar
Michael Hanselmann committed
798
  except (ValueError, TypeError):
Iustin Pop's avatar
Iustin Pop committed
799 800 801 802 803
    nv = val
  return nv


def IsValidIP(ip):
804
  """Verifies the syntax of an IPv4 address.
Iustin Pop's avatar
Iustin Pop committed
805

806 807 808 809 810 811
  This function checks if the IPv4 address passes is valid or not based
  on syntax (not IP range, class calculations, etc.).

  @type ip: str
  @param ip: the address to be checked
  @rtype: a regular expression match object
Michael Hanselmann's avatar
Michael Hanselmann committed
812
  @return: a regular expression match object, or None if the
813
      address is not valid
Iustin Pop's avatar
Iustin Pop committed
814 815 816

  """
  unit = "(0|[1-9]\d{0,2})"
817
  #TODO: convert and return only boolean
Iustin Pop's avatar
Iustin Pop committed
818 819 820 821 822 823 824 825 826 827 828 829 830
  return re.match("^%s\.%s\.%s\.%s$" % (unit, unit, unit, unit), ip)


def IsValidShellParam(word):
  """Verifies is the given word is safe from the shell's p.o.v.

  This means that we can pass this to a command via the shell and be
  sure that it doesn't alter the command line and is passed as such to
  the actual command.

  Note that we are overly restrictive here, in order to be on the safe
  side.

831 832 833 834 835
  @type word: str
  @param word: the word to check
  @rtype: boolean
  @return: True if the word is 'safe'

Iustin Pop's avatar
Iustin Pop committed
836 837 838 839 840 841 842 843 844
  """
  return bool(re.match("^[-a-zA-Z0-9._+/:%@]+$", word))


def BuildShellCmd(template, *args):
  """Build a safe shell command line from the given arguments.

  This function will check all arguments in the args list so that they
  are valid shell parameters (i.e. they don't contain shell
Michael Hanselmann's avatar
Michael Hanselmann committed
845
  metacharacters). If everything is ok, it will return the result of
Iustin Pop's avatar
Iustin Pop committed
846 847
  template % args.

848 849 850 851 852 853
  @type template: str
  @param template: the string holding the template for the
      string formatting
  @rtype: str
  @return: the expanded command line

Iustin Pop's avatar
Iustin Pop committed
854 855 856
  """
  for word in args:
    if not IsValidShellParam(word):
857 858
      raise errors.ProgrammerError("Shell argument '%s' contains"
                                   " invalid characters" % word)
Iustin Pop's avatar
Iustin Pop committed
859 860 861
  return template % args


862
def FormatUnit(value, units):
Iustin Pop's avatar
Iustin Pop committed
863 864
  """Formats an incoming number of MiB with the appropriate unit.

865 866
  @type value: int
  @param value: integer representing the value in MiB (1048576)
867 868 869 870 871 872
  @type units: char
  @param units: the type of formatting we should do:
      - 'h' for automatic scaling
      - 'm' for MiBs
      - 'g' for GiBs
      - 't' for TiBs
873 874
  @rtype: str
  @return: the formatted value (with suffix)
Iustin Pop's avatar
Iustin Pop committed
875 876

  """
877 878
  if units not in ('m', 'g', 't', 'h'):
    raise errors.ProgrammerError("Invalid unit specified '%s'" % str(units))
Iustin Pop's avatar
Iustin Pop committed
879

880 881 882 883 884 885 886 887 888 889 890
  suffix = ''

  if units == 'm' or (units == 'h' and value < 1024):
    if units == 'h':
      suffix = 'M'
    return "%d%s" % (round(value, 0), suffix)

  elif units == 'g' or (units == 'h' and value < (1024 * 1024)):
    if units == 'h':
      suffix = 'G'
    return "%0.1f%s" % (round(float(value) / 1024, 1), suffix)
Iustin Pop's avatar
Iustin Pop committed
891 892

  else:
893 894 895
    if units == 'h':
      suffix = 'T'
    return "%0.1f%s" % (round(float(value) / 1024 / 1024, 1), suffix)
Iustin Pop's avatar
Iustin Pop committed
896 897 898 899 900


def ParseUnit(input_string):
  """Tries to extract number and scale from the given string.

901 902 903
  Input must be in the format C{NUMBER+ [DOT NUMBER+] SPACE*
  [UNIT]}. If no unit is specified, it defaults to MiB. Return value
  is always an int in MiB.
Iustin Pop's avatar
Iustin Pop committed
904 905

  """
906
  m = re.match('^([.\d]+)\s*([a-zA-Z]+)?$', str(input_string))
Iustin Pop's avatar
Iustin Pop committed
907
  if not m:
908
    raise errors.UnitParseError("Invalid format")
Iustin Pop's avatar
Iustin Pop committed
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928

  value = float(m.groups()[0])

  unit = m.groups()[1]
  if unit:
    lcunit = unit.lower()
  else:
    lcunit = 'm'

  if lcunit in ('m', 'mb', 'mib'):
    # Value already in MiB
    pass

  elif lcunit in ('g', 'gb', 'gib'):
    value *= 1024

  elif lcunit in ('t', 'tb', 'tib'):
    value *= 1024 * 1024

  else:
929
    raise errors.UnitParseError("Unknown unit: %s" % unit)
Iustin Pop's avatar
Iustin Pop committed
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945

  # Make sure we round up
  if int(value) < value:
    value += 1

  # Round up to the next multiple of 4
  value = int(value)
  if value % 4:
    value += 4 - value % 4

  return value


def AddAuthorizedKey(file_name, key):
  """Adds an SSH public key to an authorized_keys file.

946 947 948 949 950
  @type file_name: str
  @param file_name: path to authorized_keys file
  @type key: str
  @param key: string containing key

Iustin Pop's avatar
Iustin Pop committed
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
  """
  key_fields = key.split()

  f = open(file_name, 'a+')
  try:
    nl = True
    for line in f:
      # Ignore whitespace changes
      if line.split() == key_fields:
        break
      nl = line.endswith('\n')
    else:
      if not nl:
        f.write("\n")
      f.write(key.rstrip('\r\n'))
      f.write("\n")
      f.flush()
  finally:
    f.close()


def RemoveAuthorizedKey(file_name, key):
  """Removes an SSH public key from an authorized_keys file.

975 976 977 978 979
  @type file_name: str
  @param file_name: path to authorized_keys file
  @type key: str
  @param key: string containing key

Iustin Pop's avatar
Iustin Pop committed
980 981 982 983 984
  """
  key_fields = key.split()

  fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name))
  try:
985
    out = os.fdopen(fd, 'w')
Iustin Pop's avatar
Iustin Pop committed
986
    try:
987 988 989 990 991 992
      f = open(file_name, 'r')
      try:
        for line in f:
          # Ignore whitespace changes while comparing lines
          if line.split() != key_fields:
            out.write(line)
993 994 995 996 997 998 999 1000 1001 1002 1003 1004

        out.flush()
        os.rename(tmpname, file_name)
      finally:
        f.close()
    finally:
      out.close()
  except:
    RemoveFile(tmpname)
    raise


1005 1006
def SetEtcHostsEntry(file_name, ip, hostname, aliases):
  """Sets the name of an IP address and hostname in /etc/hosts.
1007

1008 1009 1010 1011 1012 1013 1014 1015 1016
  @type file_name: str
  @param file_name: path to the file to modify (usually C{/etc/hosts})
  @type ip: str
  @param ip: the IP address
  @type hostname: str
  @param hostname: the hostname to be added
  @type aliases: list
  @param aliases: the list of aliases to add for the hostname

1017
  """
1018
  # FIXME: use WriteFile + fn rather than duplicating its efforts
1019 1020 1021
  # Ensure aliases are unique
  aliases = UniqueSequence([hostname] + aliases)[1:]

1022
  fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name))
1023
  try:
1024 1025 1026 1027 1028 1029
    out = os.fdopen(fd, 'w')
    try:
      f = open(file_name, 'r')
      try:
        for line in f:
          fields = line.split()
1030
          if fields and not fields[0].startswith('#') and ip == fields[0]:
1031 1032 1033
            continue
          out.write(line)

1034
        out.write("%s\t%s" % (ip, hostname))
1035 1036 1037 1038 1039
        if aliases:
          out.write(" %s" % ' '.join(aliases))
        out.write('\n')

        out.flush()
1040
        os.fsync(out)
1041
        os.chmod(tmpname, 0644)
1042 1043 1044 1045 1046 1047 1048 1049
        os.rename(tmpname, file_name)
      finally:
        f.close()
    finally:
      out.close()
  except:
    RemoveFile(tmpname)
    raise
1050 1051


1052 1053 1054
def AddHostToEtcHosts(hostname):
  """Wrapper around SetEtcHostsEntry.

1055 1056 1057 1058
  @type hostname: str
  @param hostname: a hostname that will be resolved and added to
      L{constants.ETC_HOSTS}

1059 1060 1061 1062 1063
  """
  hi = HostInfo(name=hostname)
  SetEtcHostsEntry(constants.ETC_HOSTS, hi.ip, hi.name, [hi.ShortName()])


1064
def RemoveEtcHostsEntry(file_name, hostname):
1065
  """Removes a hostname from /etc/hosts.
1066

1067
  IP addresses without names are removed from the file.
1068 1069 1070 1071 1072 1073

  @type file_name: str
  @param file_name: path to the file to modify (usually C{/etc/hosts})
  @type hostname: str
  @param hostname: the hostname to be removed

1074
  """
1075
  # FIXME: use WriteFile + fn rather than duplicating its efforts
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
  fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name))
  try:
    out = os.fdopen(fd, 'w')
    try:
      f = open(file_name, 'r')
      try:
        for line in f:
          fields = line.split()
          if len(fields) > 1 and not fields[0].startswith('#'):
            names = fields[1:]
            if hostname in names:
              while hostname in names:
                names.remove(hostname)
              if names:
1090
                out.write("%s %s\n" % (fields[0], ' '.join(names)))
1091 1092 1093
              continue

          out.write(line)
1094 1095

        out.flush()
1096
        os.fsync(out)
1097
        os.chmod(tmpname, 0644)
1098 1099 1100
        os.rename(tmpname, file_name)
      finally:
        f.close()
Iustin Pop's avatar
Iustin Pop committed
1101
    finally:
1102 1103 1104 1105
      out.close()
  except:
    RemoveFile(tmpname)
    raise
Iustin Pop's avatar
Iustin Pop committed
1106 1107


1108 1109 1110
def RemoveHostFromEtcHosts(hostname):
  """Wrapper around RemoveEtcHostsEntry.

1111 1112 1113 1114 1115
  @type hostname: str
  @param hostname: hostname that will be resolved and its
      full and shot name will be removed from
      L{constants.ETC_HOSTS}

1116 1117 1118 1119 1120 1121
  """
  hi = HostInfo(name=hostname)
  RemoveEtcHostsEntry(constants.ETC_HOSTS, hi.name)
  RemoveEtcHostsEntry(constants.ETC_HOSTS, hi.ShortName())


1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
def TimestampForFilename():
  """Returns the current time formatted for filenames.

  The format doesn't contain colons as some shells and applications them as
  separators.

  """
  return time.strftime("%Y-%m-%d_%H_%M_%S")


Iustin Pop's avatar
Iustin Pop committed
1132 1133 1134
def CreateBackup(file_name):
  """Creates a backup of a file.

1135 1136 1137 1138 1139
  @type file_name: str
  @param file_name: file to be backed up
  @rtype: str
  @return: the path to the newly created backup
  @raise errors.ProgrammerError: for invalid file names
Iustin Pop's avatar
Iustin Pop committed
1140 1141 1142

  """
  if not os.path.isfile(file_name):
1143 1144
    raise errors.ProgrammerError("Can't make a backup of a non-file '%s'" %
                                file_name)
Iustin Pop's avatar
Iustin Pop committed
1145

1146 1147
  prefix = ("%s.backup-%s." %
            (os.path.basename(file_name), TimestampForFilename()))
Iustin Pop's avatar
Iustin Pop committed
1148
  dir_name = os.path.dirname(file_name)
1149 1150 1151

  fsrc = open(file_name, 'rb')
  try:
Iustin Pop's avatar
Iustin Pop committed
1152
    (fd, backup_name) = tempfile.mkstemp(prefix=prefix, dir=dir_name)
1153 1154
    fdst = os.fdopen(fd, 'wb')
    try:
1155
      logging.debug("Backing up %s at %s", file_name, backup_name)
1156 1157 1158 1159 1160 1161
      shutil.copyfileobj(fsrc, fdst)
    finally:
      fdst.close()
  finally:
    fsrc.close()

Iustin Pop's avatar
Iustin Pop committed
1162 1163 1164 1165 1166
  return backup_name


def ShellQuote(value):
  """Quotes shell argument according to POSIX.
1167

1168 1169 1170 1171 1172
  @type value: str
  @param value: the argument to be quoted
  @rtype: str
  @return: the quoted value

Iustin Pop's avatar
Iustin Pop committed
1173 1174 1175 1176 1177 1178 1179 1180
  """
  if _re_shell_unquoted.match(value):
    return value
  else:
    return "'%s'" % value.replace("'", "'\\''")


def ShellQuoteArgs(args):