utils.py 60 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
Michael Hanselmann's avatar
Michael Hanselmann committed
44
import signal
45
import string
46
47

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

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

Iustin Pop's avatar
Iustin Pop committed
55
from ganeti import errors
Iustin Pop's avatar
Iustin Pop committed
56
from ganeti import constants
Iustin Pop's avatar
Iustin Pop committed
57

58

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

62
debug_locks = False
63
64

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

67
68
_RANDOM_UUID_FILE = "/proc/sys/kernel/random/uuid"

69

Iustin Pop's avatar
Iustin Pop committed
70
class RunResult(object):
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
  """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
87
88
89
90
91
92

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


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

    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"

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

Iustin Pop's avatar
Iustin Pop committed
112
113
114
115
116
117
118
119
120
  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")


121
def RunCmd(cmd, env=None, output=None, cwd='/'):
Iustin Pop's avatar
Iustin Pop committed
122
123
124
125
126
  """Execute a (shell) command.

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

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

  """
143
144
145
  if no_fork:
    raise errors.ProgrammerError("utils.RunCmd() called with fork() disabled")

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

  cmd_env = os.environ.copy()
  cmd_env["LC_ALL"] = "C"
  if env is not None:
    cmd_env.update(env)

160
161
162
163
164
165
166
167
168
169
170
171
  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
172
173
174
175
176
177
178
179
180
181

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

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

182

183
def _RunCmdPipe(cmd, env, via_shell, cwd):
184
185
186
187
188
189
190
191
  """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
192
193
  @type cwd: string
  @param cwd: the working directory for the program
194
195
196
197
  @rtype: tuple
  @return: (out, err, status)

  """
198
  poller = select.poll()
199
  child = subprocess.Popen(cmd, shell=via_shell,
200
201
202
                           stderr=subprocess.PIPE,
                           stdout=subprocess.PIPE,
                           stdin=subprocess.PIPE,
203
204
                           close_fds=True, env=env,
                           cwd=cwd)
205
206

  child.stdin.close()
207
208
209
210
211
212
213
214
215
216
217
218
219
  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:
220
221
222
223
224
225
226
227
228
229
230
231
    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:
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
      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
247
248

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

251

252
def _RunCmdFile(cmd, env, via_shell, output, cwd):
253
254
255
256
257
258
259
260
261
262
  """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
263
264
  @type cwd: string
  @param cwd: the working directory for the program
265
266
267
268
269
270
271
272
273
274
  @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,
275
276
                             close_fds=True, env=env,
                             cwd=cwd)
277
278
279
280
281
282

    child.stdin.close()
    status = child.wait()
  finally:
    fh.close()
  return status
Iustin Pop's avatar
Iustin Pop committed
283
284
285
286
287
288
289
290


def RemoveFile(filename):
  """Remove a file ignoring some errors.

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

291
292
293
  @type filename: str
  @param filename: the file to be removed

Iustin Pop's avatar
Iustin Pop committed
294
295
296
297
  """
  try:
    os.unlink(filename)
  except OSError, err:
298
    if err.errno not in (errno.ENOENT, errno.EISDIR):
Iustin Pop's avatar
Iustin Pop committed
299
300
301
      raise


302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
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
      os.makedirs(os.path.dirname(new), mkdir_mode)
      return os.rename(old, new)
    raise


Iustin Pop's avatar
Iustin Pop committed
328
329
330
331
332
333
def _FingerprintFile(filename):
  """Compute the fingerprint of a file.

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

334
335
336
337
338
  @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
339
340
341
342
343
344
345

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

  f = open(filename)

346
  fp = sha1()
Iustin Pop's avatar
Iustin Pop committed
347
348
349
350
351
352
353
354
355
356
357
358
359
  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.

360
361
362
363
364
  @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
365
366
367
368
369
370
371
372
373
374
375
376

  """
  ret = {}

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

  return ret


377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
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 = []

392
393
394
395
  if not isinstance(target, dict):
    msg = "Expected dictionary, got '%s'" % target
    raise errors.TypeEnforcementError(msg)

396
397
398
399
400
401
402
403
  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
404
405
406
    ktype = key_types[key]
    if ktype not in constants.ENFORCEABLE_TYPES:
      msg = "'%s' has non-enforceable type %s" % (key, ktype)
407
408
      raise errors.ProgrammerError(msg)

Iustin Pop's avatar
Iustin Pop committed
409
    if ktype == constants.VTYPE_STRING:
410
411
412
413
414
415
      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
416
    elif ktype == constants.VTYPE_BOOL:
417
418
419
420
421
422
423
424
425
426
427
428
      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
429
    elif ktype == constants.VTYPE_SIZE:
430
431
432
433
434
435
      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
436
    elif ktype == constants.VTYPE_INT:
437
438
439
440
441
442
443
      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
444
445
446
def IsProcessAlive(pid):
  """Check if a given pid exists on the system.

447
448
  @note: zombie status is not handled, so zombie processes
      will be returned as alive
449
450
451
452
  @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
453
454

  """
455
456
457
  if pid <= 0:
    return False

Iustin Pop's avatar
Iustin Pop committed
458
  try:
459
460
461
    os.stat("/proc/%d/status" % pid)
    return True
  except EnvironmentError, err:
462
    if err.errno in (errno.ENOENT, errno.ENOTDIR):
Iustin Pop's avatar
Iustin Pop committed
463
      return False
464
    raise
Iustin Pop's avatar
Iustin Pop committed
465
466


467
def ReadPidFile(pidfile):
468
  """Read a pid from a file.
469

470
471
472
  @type  pidfile: string
  @param pidfile: path to the file containing the pid
  @rtype: int
473
  @return: The process id, if the file exists and contains a valid PID,
474
           otherwise 0
475
476
477

  """
  try:
478
    raw_data = ReadFile(pidfile)
479
480
  except EnvironmentError, err:
    if err.errno != errno.ENOENT:
481
      logging.exception("Can't read pid file")
482
    return 0
483
484

  try:
485
    pid = int(raw_data)
486
  except ValueError, err:
487
    logging.info("Can't parse pid file contents", exc_info=True)
488
    return 0
489

490
  return pid
491
492


493
def MatchNameComponent(key, name_list, case_sensitive=True):
Iustin Pop's avatar
Iustin Pop committed
494
495
496
  """Try to match a name against a list.

  This function will try to match a name like test1 against a list
497
498
499
500
  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',
501
502
  '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
503

504
505
506
507
  @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
508
509
  @type case_sensitive: boolean
  @param case_sensitive: whether to provide a case-sensitive match
Iustin Pop's avatar
Iustin Pop committed
510

511
512
513
  @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
514
515

  """
516
517
  if key in name_list:
    return key
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536

  re_flags = 0
  if not case_sensitive:
    re_flags |= re.IGNORECASE
    key = string.upper(key)
  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)
      if not case_sensitive and key == string.upper(name):
        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
537
538


539
class HostInfo:
540
  """Class implementing resolver and hostname functionality
541
542

  """
543
  def __init__(self, name=None):
544
545
    """Initialize the host name object.

546
547
    If the name argument is not passed, it will use this system's
    name.
548
549

    """
550
551
552
553
554
    if name is None:
      name = self.SysName()

    self.query = name
    self.name, self.aliases, self.ipaddrs = self.LookupHostname(name)
555
556
    self.ip = self.ipaddrs[0]

557
558
559
560
561
562
  def ShortName(self):
    """Returns the hostname without domain.

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

563
564
565
  @staticmethod
  def SysName():
    """Return the current system's name.
566

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

569
570
    """
    return socket.gethostname()
Iustin Pop's avatar
Iustin Pop committed
571

572
573
574
  @staticmethod
  def LookupHostname(hostname):
    """Look up hostname
Iustin Pop's avatar
Iustin Pop committed
575

576
577
    @type hostname: str
    @param hostname: hostname to look up
578

579
580
581
582
    @rtype: tuple
    @return: a tuple (name, aliases, ipaddrs) as returned by
        C{socket.gethostbyname_ex}
    @raise errors.ResolverError: in case of errors in resolving
583
584
585
586
587
588
589

    """
    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
590

591
    return result
Iustin Pop's avatar
Iustin Pop committed
592
593
594
595
596


def ListVolumeGroups():
  """List volume groups and their size

597
598
599
600
  @rtype: dict
  @return:
       Dictionary with keys volume name and values
       the size of the volume
Iustin Pop's avatar
Iustin Pop committed
601
602
603
604
605
606
607
608
609
610
611
612
613

  """
  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:
614
      logging.error("Invalid output from vgs (%s): %s", err, line)
Iustin Pop's avatar
Iustin Pop committed
615
616
617
618
619
620
621
622
623
624
      continue

    retval[name] = size

  return retval


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

625
626
627
628
  @type bridge: str
  @param bridge: the bridge name to check
  @rtype: boolean
  @return: True if it does
Iustin Pop's avatar
Iustin Pop committed
629
630
631
632
633
634
635
636

  """
  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.

637
638
639
  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
640
641
642
643
644

  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.

645
646
647
648
  @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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673

  """
  _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.

674
675
676
677
678
679
680
681
682
683
  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
684
685
686
687

  """
  try:
    nv = fn(val)
Michael Hanselmann's avatar
Michael Hanselmann committed
688
  except (ValueError, TypeError):
Iustin Pop's avatar
Iustin Pop committed
689
690
691
692
693
    nv = val
  return nv


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

696
697
698
699
700
701
  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
702
  @return: a regular expression match object, or None if the
703
      address is not valid
Iustin Pop's avatar
Iustin Pop committed
704
705
706

  """
  unit = "(0|[1-9]\d{0,2})"
707
  #TODO: convert and return only boolean
Iustin Pop's avatar
Iustin Pop committed
708
709
710
711
712
713
714
715
716
717
718
719
720
  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.

721
722
723
724
725
  @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
726
727
728
729
730
731
732
733
734
  """
  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
735
  metacharacters). If everything is ok, it will return the result of
Iustin Pop's avatar
Iustin Pop committed
736
737
  template % args.

738
739
740
741
742
743
  @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
744
745
746
  """
  for word in args:
    if not IsValidShellParam(word):
747
748
      raise errors.ProgrammerError("Shell argument '%s' contains"
                                   " invalid characters" % word)
Iustin Pop's avatar
Iustin Pop committed
749
750
751
  return template % args


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

755
756
  @type value: int
  @param value: integer representing the value in MiB (1048576)
757
758
759
760
761
762
  @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
763
764
  @rtype: str
  @return: the formatted value (with suffix)
Iustin Pop's avatar
Iustin Pop committed
765
766

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

770
771
772
773
774
775
776
777
778
779
780
  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
781
782

  else:
783
784
785
    if units == 'h':
      suffix = 'T'
    return "%0.1f%s" % (round(float(value) / 1024 / 1024, 1), suffix)
Iustin Pop's avatar
Iustin Pop committed
786
787
788
789
790


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

791
792
793
  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
794
795

  """
796
  m = re.match('^([.\d]+)\s*([a-zA-Z]+)?$', str(input_string))
Iustin Pop's avatar
Iustin Pop committed
797
  if not m:
798
    raise errors.UnitParseError("Invalid format")
Iustin Pop's avatar
Iustin Pop committed
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818

  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:
819
    raise errors.UnitParseError("Unknown unit: %s" % unit)
Iustin Pop's avatar
Iustin Pop committed
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835

  # 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.

836
837
838
839
840
  @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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
  """
  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.

865
866
867
868
869
  @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
870
871
872
873
874
  """
  key_fields = key.split()

  fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name))
  try:
875
    out = os.fdopen(fd, 'w')
Iustin Pop's avatar
Iustin Pop committed
876
    try:
877
878
879
880
881
882
      f = open(file_name, 'r')
      try:
        for line in f:
          # Ignore whitespace changes while comparing lines
          if line.split() != key_fields:
            out.write(line)
883
884
885
886
887
888
889
890
891
892
893
894

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


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

898
899
900
901
902
903
904
905
906
  @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

907
  """
908
  # FIXME: use WriteFile + fn rather than duplicating its efforts
909
910
911
  # Ensure aliases are unique
  aliases = UniqueSequence([hostname] + aliases)[1:]

912
  fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name))
913
  try:
914
915
916
917
918
919
    out = os.fdopen(fd, 'w')
    try:
      f = open(file_name, 'r')
      try:
        for line in f:
          fields = line.split()
920
          if fields and not fields[0].startswith('#') and ip == fields[0]:
921
922
923
            continue
          out.write(line)

924
        out.write("%s\t%s" % (ip, hostname))
925
926
927
928
929
        if aliases:
          out.write(" %s" % ' '.join(aliases))
        out.write('\n')

        out.flush()
930
        os.fsync(out)
931
        os.chmod(tmpname, 0644)
932
933
934
935
936
937
938
939
        os.rename(tmpname, file_name)
      finally:
        f.close()
    finally:
      out.close()
  except:
    RemoveFile(tmpname)
    raise
940
941


942
943
944
def AddHostToEtcHosts(hostname):
  """Wrapper around SetEtcHostsEntry.

945
946
947
948
  @type hostname: str
  @param hostname: a hostname that will be resolved and added to
      L{constants.ETC_HOSTS}

949
950
951
952
953
  """
  hi = HostInfo(name=hostname)
  SetEtcHostsEntry(constants.ETC_HOSTS, hi.ip, hi.name, [hi.ShortName()])


954
def RemoveEtcHostsEntry(file_name, hostname):
955
  """Removes a hostname from /etc/hosts.
956

957
  IP addresses without names are removed from the file.
958
959
960
961
962
963

  @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

964
  """
965
  # FIXME: use WriteFile + fn rather than duplicating its efforts
966
967
968
969
970
971
972
973
974
975
976
977
978
979
  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:
980
                out.write("%s %s\n" % (fields[0], ' '.join(names)))
981
982
983
              continue

          out.write(line)
984
985

        out.flush()
986
        os.fsync(out)
987
        os.chmod(tmpname, 0644)
988
989
990
        os.rename(tmpname, file_name)
      finally:
        f.close()
Iustin Pop's avatar
Iustin Pop committed
991
    finally:
992
993
994
995
      out.close()
  except:
    RemoveFile(tmpname)
    raise
Iustin Pop's avatar
Iustin Pop committed
996
997


998
999
1000
def RemoveHostFromEtcHosts(hostname):
  """Wrapper around RemoveEtcHostsEntry.

1001
1002
1003
1004
1005
  @type hostname: str
  @param hostname: hostname that will be resolved and its
      full and shot name will be removed from
      L{constants.ETC_HOSTS}

1006
1007
1008
1009
1010
1011
  """
  hi = HostInfo(name=hostname)
  RemoveEtcHostsEntry(constants.ETC_HOSTS, hi.name)
  RemoveEtcHostsEntry(constants.ETC_HOSTS, hi.ShortName())


Iustin Pop's avatar
Iustin Pop committed
1012
1013
1014
def CreateBackup(file_name):
  """Creates a backup of a file.

1015
1016
1017
1018
1019
  @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
1020
1021
1022

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

1026
  prefix = '%s.backup-%d.' % (os.path.basename(file_name), int(time.time()))
Iustin Pop's avatar
Iustin Pop committed
1027
  dir_name = os.path.dirname(file_name)
1028
1029
1030

  fsrc = open(file_name, 'rb')
  try:
Iustin Pop's avatar
Iustin Pop committed
1031
    (fd, backup_name) = tempfile.mkstemp(prefix=prefix, dir=dir_name)
1032
1033
1034
1035
1036
1037
1038
1039
    fdst = os.fdopen(fd, 'wb')
    try:
      shutil.copyfileobj(fsrc, fdst)
    finally:
      fdst.close()
  finally:
    fsrc.close()

Iustin Pop's avatar
Iustin Pop committed
1040
1041
1042
1043
1044
  return backup_name


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

1046
1047
1048
1049
1050
  @type value: str
  @param value: the argument to be quoted
  @rtype: str
  @return: the quoted value

Iustin Pop's avatar
Iustin Pop committed
1051
1052
1053
1054
1055
1056
1057
1058
  """
  if _re_shell_unquoted.match(value):
    return value
  else:
    return "'%s'" % value.replace("'", "'\\''")


def ShellQuoteArgs(args):
1059
1060
1061
1062
1063
  """Quotes a list of shell arguments.

  @type args: list
  @param args: list of arguments to be quoted
  @rtype: str
Michael Hanselmann's avatar
Michael Hanselmann committed
1064
  @return: the quoted arguments concatenated with spaces
Iustin Pop's avatar
Iustin Pop committed
1065
1066
1067

  """
  return ' '.join([ShellQuote(i) for i in args])
1068
1069


1070
def TcpPing(target, port, timeout=10, live_port_needed=False, source=None):
1071
1072
  """Simple ping implementation using TCP connect(2).

1073
1074
1075
1076
1077
1078
1079
1080
  Check if the given IP is reachable by doing attempting a TCP connect
  to it.

  @type target: str
  @param target: the IP or hostname to ping
  @type port: int
  @param port: the port to connect to
  @type timeout: int
Michael Hanselmann's avatar
Michael Hanselmann committed
1081
  @param timeout: the timeout on the connection attempt
1082
1083
1084
1085
1086
1087
1088
  @type live_port_needed: boolean
  @param live_port_needed: whether a closed port will cause the
      function to return failure, as if there was a timeout
  @type source: str or None
  @param source: if specified, will cause the connect to be made
      from this specific source address; failures to bind other
      than C{EADDRNOTAVAIL} will be ignored
1089
1090
1091
1092

  """
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

1093
  success = False
1094

1095
1096
1097
  if source is not None:
    try:
      sock.bind((source, 0))
Michael Hanselmann's avatar
Michael Hanselmann committed
1098
    except socket.error, (errcode, _):
1099
1100
      if errcode == errno.EADDRNOTAVAIL:
        success = False
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110

  sock.settimeout(timeout)

  try:
    sock.connect((target, port))
    sock.close()
    success = True
  except socket.timeout:
    success = False
  except socket.error, (errcode, errstring):
1111
    success = (not live_port_needed) and (errcode == errno.ECONNREFUSED)
1112
1113

  return success
1114
1115


1116
1117
1118
def OwnIpAddress(address):
  """Check if the current host has the the given IP address.

1119
  Currently this is done by TCP-pinging the address from the loopback
1120
1121
1122
  address.

  @type address: string
Michael Hanselmann's avatar
Michael Hanselmann committed
1123
  @param address: the address to check
1124
  @rtype: bool
1125
  @return: True if we own the address
1126
1127
1128
1129
1130
1131

  """
  return TcpPing(address, constants.DEFAULT_NODED_PORT,
                 source=constants.LOCALHOST_IP_ADDRESS)


1132
def ListVisibleFiles(path):
1133
1134
1135
1136
1137
1138
  """Returns a list of visible files in a directory.

  @type path: str
  @param path: the directory to enumerate
  @rtype: list
  @return: the list of all files not starting with a dot
1139
1140

  """
1141
1142
1143
  files = [i for i in os.listdir(path) if not i.startswith(".")]
  files.sort()
  return files
1144
1145


1146
1147
1148
1149
1150
1151
def GetHomeDir(user, default=None):
  """Try to get the homedir of the given user.

  The user can be passed either as a string (denoting the name) or as
  an integer (denoting the user id). If the user is not found, the
  'default' argument is returned, which defaults to None.
1152
1153
1154

  """
  try:
1155
1156
1157
1158
1159
1160
1161
    if isinstance(user, basestring):
      result = pwd.getpwnam(user)
    elif isinstance(user, (int, long)):
      result = pwd.getpwuid(user)
    else:
      raise errors.ProgrammerError("Invalid type passed to GetHomeDir (%s)" %
                                   type(user))
1162
1163
1164
  except KeyError:
    return default
  return result.pw_dir
1165
1166


1167
def NewUUID():
1168
1169
  """Returns a random UUID.

1170
1171
1172
1173
  @note: This is a Linux-specific method as it uses the /proc
      filesystem.
  @rtype: str

1174
  """
1175
  return ReadFile(_RANDOM_UUID_FILE, size=128).rstrip("\n")
Iustin Pop's avatar
Iustin Pop committed
1176
1177


1178
def GenerateSecret(numbytes=20):
1179
1180
  """Generates a random secret.

1181
  This will generate a pseudo-random secret returning an hex string
1182
1183
  (so that it can be used where an ASCII string is needed).

1184
1185
  @param numbytes: the number of bytes which will be represented by the returned
      string (defaulting to 20, the length of a SHA1 hash)
1186
  @rtype: str
1187
  @return: an hex representation of the pseudo-random sequence
1188

1189
  """
1190
  return os.urandom(numbytes).encode('hex')
1191
1192


1193
1194
1195
1196
1197
1198
1199
1200
1201
def EnsureDirs(dirs):
  """Make required directories, if they don't exist.

  @param dirs: list of tuples (dir_name, dir_mode)
  @type dirs: list of (string, integer)

  """
  for dir_name, dir_mode in dirs:
    try:
Iustin Pop's avatar
Iustin Pop committed
1202
      os.mkdir(dir_name, dir_mode)
1203
1204
1205
    except EnvironmentError, err:
      if err.errno != errno.EEXIST:
        raise errors.GenericError("Cannot create needed directory"
Iustin Pop's avatar
Iustin Pop committed
1206
                                  " '%s': %s" % (dir_name, err))
1207
1208
1209
1210
    if not os.path.isdir(dir_name):
      raise errors.GenericError("%s is not a directory" % dir_name)


1211
1212
1213
1214
1215
def ReadFile(file_name, size=None):
  """Reads a file.

  @type size: None or int
  @param size: Read at most size bytes
1216
  @rtype: str
Michael Hanselmann's avatar
Michael Hanselmann committed
1217
  @return: the (possibly partial) content of the file
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229

  """
  f = open(file_name, "r")
  try:
    if size is None:
      return f.read()
    else:
      return f.read(size)
  finally:
    f.close()


Iustin Pop's avatar
Iustin Pop committed
1230
1231
def WriteFile(file_name, fn=None, data=None,
              mode=None, uid=-1, gid=-1,
1232
              atime=None, mtime=None, close=True,
1233
              dry_run=False, backup=False,
1234
              prewrite=None, postwrite=None):
Iustin Pop's avatar
Iustin Pop committed
1235
1236
1237
1238
1239
1240
1241
1242
1243
  """(Over)write a file atomically.

  The file_name and either fn (a function taking one argument, the
  file descriptor, and which should write the data to it) or data (the
  contents of the file) must be passed. The other arguments are
  optional and allow setting the file mode, owner and group, and the
  mtime/atime of the file.

  If the function doesn't raise an exception, it has succeeded and the
1244
  target file has the new contents. If the function has raised an
Iustin Pop's avatar
Iustin Pop committed
1245
1246
1247
  exception, an existing target file should be unmodified and the
  temporary file should be removed.

1248
1249
1250
1251
1252
  @type file_name: str
  @param file_name: the target filename
  @type fn: callable
  @param fn: content writing function, called with
      file descriptor as parameter
1253
  @type data: str
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
  @param data: contents of the file
  @type mode: int
  @param mode: file mode
  @type uid: int
  @param uid: the owner of the file
  @type gid: int
  @param gid: the group of the file
  @type atime: int
  @param atime: a custom access time to be set on the file
  @type mtime: int
  @param mtime: a custom modification time to be set on the file
  @type close: boolean
  @param close: whether to close file after writing it
  @type prewrite: callable
  @param prewrite: function to be called before writing content
  @type postwrite: callable
  @param postwrite: function to be called after writing content

  @rtype: None or int
  @return: None if the 'close' parameter evaluates to True,
      otherwise the file descriptor

1276
  @raise errors.ProgrammerError: if any of the arguments are not valid
1277

Iustin Pop's avatar
Iustin Pop committed
1278
  """
1279
  if not os.path.isabs(file_name):
Iustin Pop's avatar
Iustin Pop committed
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
    raise errors.ProgrammerError("Path passed to WriteFile is not"
                                 " absolute: '%s'" % file_name)

  if [fn, data].count(None) != 1:
    raise errors.ProgrammerError("fn or data required")

  if [atime, mtime].count(None) == 1:
    raise errors.ProgrammerError("Both atime and mtime must be either"
                                 " set or None")

Michael Hanselmann's avatar
Michael Hanselmann committed
1290
1291
  if backup and not dry_run and os.path.isfile(file_name):
    CreateBackup(file_name)
Iustin Pop's avatar
Iustin Pop committed
1292
1293
1294

  dir_name, base_name = os.path.split(file_name)
  fd, new_name = tempfile.mkstemp('.new', base_name, dir_name)
1295
  do_remove = True
Iustin Pop's avatar
Iustin Pop committed
1296
1297
1298
1299
1300
1301
1302
  # here we need to make sure we remove the temp file, if any error
  # leaves it in place
  try:
    if uid != -1 or gid != -1:
      os.chown(new_name, uid, gid)
    if mode:
      os.chmod(new_name, mode)
1303
1304
    if callable(prewrite):
      prewrite(fd)
Iustin Pop's avatar
Iustin Pop committed
1305
1306
1307
1308
    if data is not None:
      os.write(fd, data)
    else:
      fn(fd)
1309
1310
    if callable(postwrite):
      postwrite(fd)
Iustin Pop's avatar
Iustin Pop committed
1311
1312
1313
    os.fsync(fd)
    if atime is not None and mtime is not None:
      os.utime(new_name, (atime, mtime))
Michael Hanselmann's avatar
Michael Hanselmann committed
1314
1315
    if not dry_run:
      os.rename(new_name, file_name)
1316
      do_remove = False
Iustin Pop's avatar
Iustin Pop committed
1317
  finally:
1318
1319
1320
1321
1322
    if close:
      os.close(fd)
      result = None
    else:
      result = fd
1323
1324
    if do_remove:
      RemoveFile(new_name)
Guido Trotter's avatar
Guido Trotter committed
1325

1326
1327
  return result

Guido Trotter's avatar
Guido Trotter committed
1328

1329
1330
1331
1332
1333
1334
1335
1336
def FirstFree(seq, base=0):
  """Returns the first non-existing integer from seq.

  The seq argument should be a sorted list of positive integers. The
  first time the index of an element is smaller than the element
  value, the index will be returned.

  The base argument is used to start at a different offset,
1337
1338
1339
  i.e. C{[3, 4, 6]} with I{offset=3} will return 5.

  Example: C{[0, 1, 3]} will return I{2}.
1340

1341
1342
1343
1344
1345
1346
  @type seq: sequence
  @param seq: the sequence to be analyzed.
  @type base: int
  @param base: use this value as the base index of the sequence
  @rtype: int
  @return: the first non-used index in the sequence
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356

  """
  for idx, elem in enumerate(seq):
    assert elem >= base, "Passed element is higher than base offset"
    if elem > idx + base:
      # idx is not used
      return idx + base
  return None


Guido Trotter's avatar
Guido Trotter committed
1357
1358
def all(seq, pred=bool):
  "Returns True if pred(x) is True for every element in the iterable"
Michael Hanselmann's avatar
Michael Hanselmann committed
1359
  for _ in itertools.ifilterfalse(pred, seq):
Guido Trotter's avatar
Guido Trotter committed
1360
1361
1362
1363
1364
1365
    return False
  return True


def any(seq, pred=bool):
  "Returns True if pred(x) is True for at least one element in the iterable"
Michael Hanselmann's avatar
Michael Hanselmann committed
1366
  for _ in itertools.ifilter(pred, seq):
Guido Trotter's avatar
Guido Trotter committed
1367
1368
    return True
  return False
1369
1370
1371
1372
1373
1374