~ubuntu-branches/ubuntu/saucy/namebench/saucy

« back to all changes in this revision

Viewing changes to libnamebench/util.py

  • Committer: Bazaar Package Importer
  • Author(s): Miguel Landaeta
  • Date: 2010-06-24 09:23:04 UTC
  • mfrom: (1.1.2 upstream)
  • Revision ID: james.westby@ubuntu.com-20100624092304-xrkglqsrod0cuhk9
Tags: 1.3.1+dfsg-1
* New upstream release.
* Updated watch file.
* Switched source package format to 3.0 (quilt).
* Dropped unneeded version for dependence on python (>= 2.5).
* Added necessary version for dependence on python-dnspython (>= 1.8.0).
* Updated manpage.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
__author__ = 'tstromberg@google.com (Thomas Stromberg)'
18
18
 
 
19
import datetime
19
20
import math
20
 
import re
21
 
import util
22
21
import os.path
23
22
import sys
24
 
import traceback
25
 
 
26
 
# third party lib
27
 
import dns.resolver
28
 
 
29
 
import nameserver
 
23
import tempfile
 
24
 
30
25
 
31
26
def CalculateListAverage(values):
32
27
  """Computes the arithmetic mean of a list of numbers."""
34
29
    return 0
35
30
  return sum(values) / float(len(values))
36
31
 
 
32
 
37
33
def DrawTextBar(value, max_value, max_width=53):
38
34
  """Return a simple ASCII bar graph, making sure it fits within max_width.
39
35
 
53
49
def SecondsToMilliseconds(seconds):
54
50
  return seconds * 1000
55
51
 
 
52
 
56
53
def SplitSequence(seq, size):
57
 
  """Recipe From http://code.activestate.com/recipes/425397/
58
 
 
59
 
  Modified to not return blank values."""
 
54
  """Split a list.
 
55
 
 
56
  Args:
 
57
    seq: sequence
 
58
    size: int
 
59
 
 
60
  Returns:
 
61
    New list.
 
62
 
 
63
  Recipe From http://code.activestate.com/recipes/425397/ (Modified to not return blank values)
 
64
  """
60
65
  newseq = []
61
66
  splitsize = 1.0/size*len(seq)
62
67
  for i in range(size):
63
68
    newseq.append(seq[int(round(i*splitsize)):int(round((i+1)*splitsize))])
64
69
 
65
 
  return  [ x for x in newseq if x ]
66
 
 
67
 
 
68
 
def InternalNameServers():
69
 
  """Return list of DNS server IP's used by the host."""
70
 
  try:
71
 
    return dns.resolver.Resolver().nameservers
72
 
  except:
73
 
    print "Unable to get list of internal DNS servers."
74
 
    return []
75
 
 
76
 
def ExtractIPsFromString(ip_string):
77
 
  """Return a tuple of ip addressed held in a string."""
78
 
 
79
 
  ips = []
80
 
  # IPV6 If this regexp is too loose, see Regexp-IPv6 in CPAN for inspiration.
81
 
  ips.extend(re.findall('[\dabcdef:]+:[\dabcdef:]+', ip_string, re.IGNORECASE))
82
 
  ips.extend(re.findall('\d+\.\d+\.\d+\.+\d+', ip_string))
83
 
  return ips
84
 
 
85
 
def ExtractIPTuplesFromString(ip_string):
86
 
  ip_tuples = []
87
 
  for ip in ExtractIPsFromString(ip_string):
88
 
      ip_tuples.append((ip,ip))
89
 
  return ip_tuples
 
70
  return  [x for x in newseq if x]
 
71
 
90
72
 
91
73
def FindDataFile(filename):
 
74
  """Find a datafile, searching various relative and OS paths."""
 
75
  filename = os.path.expanduser(filename)
92
76
  if os.path.exists(filename):
93
77
    return filename
94
78
 
107
91
                  '/etc/namebench',
108
92
                  '/usr/share/namebench',
109
93
                  '/usr/namebench']
110
 
  for dir in reversed(sys.path):
111
 
    other_places.append(dir)
112
 
    other_places.append(os.path.join(dir, 'namebench'))
 
94
  for directory in reversed(sys.path):
 
95
    other_places.append(directory)
 
96
    other_places.append(os.path.join(directory, 'namebench'))
113
97
 
114
98
  for place in other_places:
115
99
    path = os.path.join(place, filename)
116
100
    if os.path.exists(path):
117
101
      return path
118
102
 
119
 
  print "I could not find your beloved '%s'. Tried:" % filename
 
103
  print 'I could not find "%s". Tried:' % filename
120
104
  for path in other_places:
121
 
    print "  %s" % path
 
105
    print '  %s' % path
122
106
  return filename
123
107
 
 
108
def GenerateOutputFilename(extension):
 
109
  """Generate a decent default output filename for a given extensio."""
 
110
 
 
111
  # used for resolv.conf
 
112
  if '.' in extension:
 
113
    filename = extension
 
114
  else:
 
115
    output_base = 'namebench_%s' % datetime.datetime.strftime(datetime.datetime.now(),
 
116
                                                              '%Y-%m-%d %H%M')
 
117
    output_base = output_base.replace(':', '').replace(' ', '_')
 
118
    filename = '.'.join((output_base, extension))
 
119
 
 
120
  output_dir = tempfile.gettempdir()
 
121
  return os.path.join(output_dir, filename)
 
122
    
 
123
 
 
124
 
124
125
def GetLastExceptionString():
125
126
  """Get the last exception and return a good looking string for it."""
126
127
  (exc, error) = sys.exc_info()[0:2]
129
130
    exc_msg = exc_msg.split("'")[1]
130
131
 
131
132
  exc_msg = exc_msg.replace('dns.exception.', '')
132
 
  return '%s %s' % (exc_msg, error)
 
133
  error = '%s %s' % (exc_msg, error)
 
134
  # We need to remove the trailing space at some point.
 
135
  return error.rstrip()