box_get removed and replaced for get in testbed_impl
[nepi.git] / test / lib / test_util.py
1 #!/usr/bin/env python
2
3 import nepi.util.environ
4 import ctypes
5 import imp
6 import sys
7
8 # Unittest from Python 2.6 doesn't have these decorators
9 def _bannerwrap(f, text):
10     name = f.__name__
11     def banner(*args, **kwargs):
12         sys.stderr.write("*** WARNING: Skipping test %s: `%s'\n" %
13                 (name, text))
14         return None
15     return banner
16 def skip(text):
17     return lambda f: _bannerwrap(f, text)
18 def skipUnless(cond, text):
19     return (lambda f: _bannerwrap(f, text)) if not cond else lambda f: f
20 def skipIf(cond, text):
21     return (lambda f: _bannerwrap(f, text)) if cond else lambda f: f
22
23 def ns3_bindings_path():
24     if "NEPI_NS3BINDINGS" in os.environ:
25         return os.environ["NEPI_NS3BINDINGS"]
26     return None
27
28 def ns3_library_path():
29     if "NEPI_NS3LIBRARY" in os.environ:
30         return os.environ["NEPI_NS3LIBRARY"]
31     return None
32
33 def ns3_usable():
34     if ns3_library_path():
35         try:
36             ctypes.CDLL(ns3_library_path(), ctypes.RTLD_GLOBAL)
37         except:
38             return False
39
40     if ns3_bindings_path():
41         sys.path.insert(0, ns3_bindings_path())
42
43     try:
44         found = imp.find_module('ns3')
45         module = imp.load_module('ns3', *found)
46     except ImportError:
47         return False
48     finally:
49         if ns3_bindings_path():
50             del sys.path[0]
51
52     return True
53
54 def pl_auth():
55     user = os.environ.get('PL_USER')
56     pwd = os.environ.get('PL_PASS')
57      
58     if user and pwd:
59         return (user,pwd)
60     else:
61         return None
62
63 def find_bin(name, extra_path = None):
64     search = []
65     if "PATH" in os.environ:
66         search += os.environ["PATH"].split(":")
67     for pref in ("/", "/usr/", "/usr/local/"):
68         for d in ("bin", "sbin"):
69             search.append(pref + d)
70     if extra_path:
71         search += extra_path
72
73     for d in search:
74             try:
75                 os.stat(d + "/" + name)
76                 return d + "/" + name
77             except OSError, e:
78                 if e.errno != os.errno.ENOENT:
79                     raise
80     return None
81
82 def find_bin_or_die(name, extra_path = None):
83     r = find_bin(name)
84     if not r:
85         raise RuntimeError(("Cannot find `%s' command, impossible to " +
86                 "continue.") % name)
87     return r
88
89 # SSH stuff
90
91 import os, os.path, re, signal, shutil, socket, subprocess, tempfile
92 def gen_ssh_keypair(filename):
93     ssh_keygen = nepi.util.environ.find_bin_or_die("ssh-keygen")
94     args = [ssh_keygen, '-q', '-N', '', '-f', filename]
95     assert subprocess.Popen(args).wait() == 0
96     return filename, "%s.pub" % filename
97
98 def add_key_to_agent(filename):
99     ssh_add = nepi.util.environ.find_bin_or_die("ssh-add")
100     args = [ssh_add, filename]
101     null = file("/dev/null", "w")
102     assert subprocess.Popen(args, stderr = null).wait() == 0
103     null.close()
104
105 def get_free_port():
106     s = socket.socket()
107     s.bind(("127.0.0.1", 0))
108     port = s.getsockname()[1]
109     return port
110
111 _SSH_CONF = """ListenAddress 127.0.0.1:%d
112 Protocol 2
113 HostKey %s
114 UsePrivilegeSeparation no
115 PubkeyAuthentication yes
116 PasswordAuthentication no
117 AuthorizedKeysFile %s
118 UsePAM no
119 AllowAgentForwarding yes
120 PermitRootLogin yes
121 StrictModes no
122 PermitUserEnvironment yes
123 """
124
125 def gen_sshd_config(filename, port, server_key, auth_keys):
126     conf = open(filename, "w")
127     text = _SSH_CONF % (port, server_key, auth_keys)
128     conf.write(text)
129     conf.close()
130     return filename
131
132 def gen_auth_keys(pubkey, output, environ):
133     #opts = ['from="127.0.0.1/32"'] # fails in stupid yans setup
134     opts = []
135     for k, v in environ.items():
136         opts.append('environment="%s=%s"' % (k, v))
137
138     lines = file(pubkey).readlines()
139     pubkey = lines[0].split()[0:2]
140     out = file(output, "w")
141     out.write("%s %s %s\n" % (",".join(opts), pubkey[0], pubkey[1]))
142     out.close()
143     return output
144
145 def start_ssh_agent():
146     ssh_agent = nepi.util.environ.find_bin_or_die("ssh-agent")
147     proc = subprocess.Popen([ssh_agent], stdout = subprocess.PIPE)
148     (out, foo) = proc.communicate()
149     assert proc.returncode == 0
150     d = {}
151     for l in out.split("\n"):
152         match = re.search("^(\w+)=([^ ;]+);.*", l)
153         if not match:
154             continue
155         k, v = match.groups()
156         os.environ[k] = v
157         d[k] = v
158     return d
159
160 def stop_ssh_agent(data):
161     # No need to gather the pid, ssh-agent knows how to kill itself; after we
162     # had set up the environment
163     ssh_agent = nepi.util.environ.find_bin_or_die("ssh-agent")
164     null = file("/dev/null", "w")
165     proc = subprocess.Popen([ssh_agent, "-k"], stdout = null)
166     null.close()
167     assert proc.wait() == 0
168     for k in data:
169         del os.environ[k]
170
171 class test_environment(object):
172     def __init__(self):
173         sshd = find_bin_or_die("sshd")
174         environ = {}
175         if 'PYTHONPATH' in os.environ:
176             environ['PYTHONPATH'] = ":".join(map(os.path.realpath, 
177                 os.environ['PYTHONPATH'].split(":")))
178         if 'NEPI_NS3BINDINGS' in os.environ:
179             environ['NEPI_NS3BINDINGS'] = \
180                     os.path.realpath(os.environ['NEPI_NS3BINDINGS'])
181         if 'NEPI_NS3LIBRARY' in os.environ:
182             environ['NEPI_NS3LIBRARY'] = \
183                     os.path.realpath(os.environ['NEPI_NS3LIBRARY'])
184
185         self.dir = tempfile.mkdtemp()
186         self.server_keypair = gen_ssh_keypair(
187                 os.path.join(self.dir, "server_key"))
188         self.client_keypair = gen_ssh_keypair(
189                 os.path.join(self.dir, "client_key"))
190         self.authorized_keys = gen_auth_keys(self.client_keypair[1],
191                 os.path.join(self.dir, "authorized_keys"), environ)
192         self.port = get_free_port()
193         self.sshd_conf = gen_sshd_config(
194                 os.path.join(self.dir, "sshd_config"),
195                 self.port, self.server_keypair[0], self.authorized_keys)
196
197         self.sshd = subprocess.Popen([sshd, '-q', '-D', '-f', self.sshd_conf])
198         self.ssh_agent_vars = start_ssh_agent()
199         add_key_to_agent(self.client_keypair[0])
200
201     def __del__(self):
202         if self.sshd:
203             os.kill(self.sshd.pid, signal.SIGTERM)
204             self.sshd.wait()
205         if self.ssh_agent_vars:
206             stop_ssh_agent(self.ssh_agent_vars)
207         shutil.rmtree(self.dir)
208