~ubuntu-branches/ubuntu/vivid/namebench/vivid

« back to all changes in this revision

Viewing changes to libnamebench/config.py

  • Committer: Bazaar Package Importer
  • Author(s): Miguel Landaeta
  • Date: 2010-01-27 19:49:17 UTC
  • Revision ID: james.westby@ubuntu.com-20100127194917-1ssrtuje4zabmonl
Tags: upstream-1.1+dfsg
ImportĀ upstreamĀ versionĀ 1.1+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
# Copyright 2009 Google Inc. All Rights Reserved.
 
3
#
 
4
# Licensed under the Apache License, Version 2.0 (the "License");
 
5
# you may not use this file except in compliance with the License.
 
6
# You may obtain a copy of the License at
 
7
#
 
8
#      http://www.apache.org/licenses/LICENSE-2.0
 
9
#
 
10
# Unless required by applicable law or agreed to in writing, software
 
11
# distributed under the License is distributed on an "AS IS" BASIS,
 
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
13
# See the License for the specific language governing permissions and
 
14
# limitations under the License.
 
15
 
 
16
"""Define and process configuration from command-line or config file."""
 
17
 
 
18
__author__ = 'tstromberg@google.com (Thomas Stromberg)'
 
19
 
 
20
import ConfigParser
 
21
import optparse
 
22
import StringIO
 
23
import tempfile
 
24
 
 
25
# from third_party
 
26
import httplib2
 
27
 
 
28
import history_parser
 
29
import util
 
30
import version
 
31
 
 
32
SANITY_REFERENCE_URL = 'http://namebench.googlecode.com/svn/trunk/data/hostname_reference.cfg'
 
33
 
 
34
 
 
35
def GetConfiguration(filename='namebench.cfg'):
 
36
  (options, args) = DefineAndParseOptions(filename=filename)
 
37
  (configured_options, global_ns, regional_ns) = ProcessConfigurationFile(options)
 
38
  supplied_ns = util.ExtractIPTuplesFromString(' '.join(args))
 
39
  return (configured_options, supplied_ns, global_ns, regional_ns)
 
40
 
 
41
def DefineAndParseOptions(filename='namebench.cfg'):
 
42
  """Get our option configuration setup.
 
43
 
 
44
  Returns: tuple of (OptionParser object, args)
 
45
  """
 
46
  h = history_parser.HistoryParser()
 
47
  import_types = sorted(h.GetTypes().keys())
 
48
  parser = optparse.OptionParser()
 
49
  parser.add_option('-r', '--runs', dest='run_count', default=1, type='int',
 
50
                    help='Number of test runs to perform on each nameserver.')
 
51
  parser.add_option('-z', '--config', dest='config', default=filename,
 
52
                    help='Config file to use.')
 
53
  parser.add_option('-o', '--output', dest='output_file', default=None,
 
54
                    help='Filename to write HTML output to')
 
55
  parser.add_option('-c', '--csv_output', dest='csv_file', default=None,
 
56
                    help='Filename to write CSV output to')
 
57
  parser.add_option('-j', '--threads', dest='thread_count', type='int',
 
58
                    help='# of threads to use')
 
59
  parser.add_option('-y', '--timeout', dest='timeout', type='float',
 
60
                    help='# of seconds general requests timeout in.')
 
61
  parser.add_option('-Y', '--health_timeout', dest='health_timeout',
 
62
                    type='float', help='health check timeout (in seconds)')
 
63
  parser.add_option('-d', '--datafile', dest='data_file',
 
64
                    default='data/alexa-top-10000-global.txt',
 
65
                    help='File containing a list of domain names to query.')
 
66
  parser.add_option('-i', '--import', dest='import_source',
 
67
                    help=('Import history from an external application (%s)' %
 
68
                          ', '.join(import_types)))
 
69
  parser.add_option('-I', '--invalidate_cache', dest='invalidate_cache',
 
70
                    action='store_true',
 
71
                    help='Force health cache to be invalidated')
 
72
  parser.add_option('-t', '--tests', dest='test_count', type='int',
 
73
                    help='Number of queries per run.')
 
74
  parser.add_option('-m', '--select_mode', dest='select_mode',
 
75
                    default='weighted',
 
76
                    help='Selection algorithm to use (weighted, random, chunk)')
 
77
  parser.add_option('-s', '--num_servers', dest='num_servers',
 
78
                    type='int', help='Number of nameservers to include in test')
 
79
  parser.add_option('-S', '--no_regional', dest='no_regional',
 
80
                    action='store_true', help='Disable regional_ns servers')
 
81
  parser.add_option('-w', '--open_webbrowser', dest='open_webbrowser',
 
82
                    action='store_true', help='Opens the final report in your browser')
 
83
  parser.add_option('-x', '--no_gui', dest='no_gui',
 
84
                    action='store_true', help='Disable GUI')
 
85
  parser.add_option('-C', '--enable-censorship-checks', dest='enable_censorship_checks',
 
86
                    action='store_true', help='Enable censorship checks')
 
87
  parser.add_option('-6', '--ipv6_only', dest='ipv6_only',
 
88
                    action='store_true', help='Only include IPv6 name servers')
 
89
  # Silly Mac OS X adding -psn_0_xxxx
 
90
  parser.add_option('-p', '--psn')
 
91
  parser.add_option('-O', '--only', dest='only',
 
92
                    action='store_true',
 
93
                    help='Only test nameservers passed as arguments')
 
94
  return parser.parse_args()
 
95
 
 
96
def GetLatestSanityChecks():
 
97
  """Get the latest copy of the sanity checks config."""
 
98
  h = httplib2.Http(tempfile.gettempdir(), timeout=10)
 
99
  try:
 
100
    resp, content = h.request(SANITY_REFERENCE_URL, 'GET')
 
101
  except exc:
 
102
    print exc
 
103
  config = ConfigParser.ConfigParser()
 
104
 
 
105
  if '[sanity]' in content:
 
106
    fp = StringIO.StringIO(content)
 
107
    try:
 
108
      config.readfp(fp)
 
109
    except:
 
110
      pass
 
111
 
 
112
  if not config.has_section('sanity') or not config.has_section('censorship'):
 
113
    ref_file = util.FindDataFile('data/hostname_reference.cfg')
 
114
    print '- Using built-in sanity reference: %s' % ref_file
 
115
    config.read(ref_file)
 
116
 
 
117
  return (config.items('sanity'), config.items('sanity-secondary'), config.items('censorship'))
 
118
 
 
119
 
 
120
def ProcessConfigurationFile(options):
 
121
  """Process configuration file, merge configuration with OptionParser.
 
122
 
 
123
  Args:
 
124
    options: optparse.OptionParser() object
 
125
 
 
126
  Returns:
 
127
    options: optparse.OptionParser() object
 
128
    global_ns: A list of global nameserver tuples.
 
129
    regional_ns: A list of regional nameservers tuples.
 
130
  """
 
131
  config = ConfigParser.ConfigParser()
 
132
  config.read(util.FindDataFile(options.config))
 
133
  general = dict(config.items('general'))
 
134
 
 
135
  if options.only:
 
136
    global_ns = []
 
137
    regional_ns = []
 
138
  else:
 
139
    global_ns = config.items('global')
 
140
    regional_ns = config.items('regional') + config.items('private')
 
141
 
 
142
  if options.no_regional:
 
143
    regional_ns = []
 
144
 
 
145
  for option in general:
 
146
    if not getattr(options, option):
 
147
      if 'timeout' in option:
 
148
        value = float(general[option])
 
149
      elif 'count' in option or 'num' in option:
 
150
        value = int(general[option])
 
151
      else:
 
152
        value = general[option]
 
153
      setattr(options, option, value)
 
154
 
 
155
  options.version = version.VERSION
 
156
  return (options, global_ns, regional_ns)