missing import ctypes in test_util.py
[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
55 def find_bin(name, extra_path = None):
56     search = []
57     if "PATH" in os.environ:
58         search += os.environ["PATH"].split(":")
59     for pref in ("/", "/usr/", "/usr/local/"):
60         for d in ("bin", "sbin"):
61             search.append(pref + d)
62     if extra_path:
63         search += extra_path
64
65     for d in search:
66             try:
67                 os.stat(d + "/" + name)
68                 return d + "/" + name
69             except OSError, e:
70                 if e.errno != os.errno.ENOENT:
71                     raise
72     return None
73
74 def find_bin_or_die(name, extra_path = None):
75     r = find_bin(name)
76     if not r:
77         raise RuntimeError(("Cannot find `%s' command, impossible to " +
78                 "continue.") % name)
79     return r
80
81 # SSH stuff
82
83 import os, os.path, re, signal, shutil, socket, subprocess, tempfile
84 def gen_ssh_keypair(filename):
85     ssh_keygen = nepi.util.environ.find_bin_or_die("ssh-keygen")
86     args = [ssh_keygen, '-q', '-N', '', '-f', filename]
87     assert subprocess.Popen(args).wait() == 0
88     return filename, "%s.pub" % filename
89
90 def add_key_to_agent(filename):
91     ssh_add = nepi.util.environ.find_bin_or_die("ssh-add")
92     args = [ssh_add, filename]
93     null = file("/dev/null", "w")
94     assert subprocess.Popen(args, stderr = null).wait() == 0
95     null.close()
96
97 def get_free_port():
98     s = socket.socket()
99     s.bind(("127.0.0.1", 0))
100     port = s.getsockname()[1]
101     return port
102
103 _SSH_CONF = """ListenAddress 127.0.0.1:%d
104 Protocol 2
105 HostKey %s
106 UsePrivilegeSeparation no
107 PubkeyAuthentication yes
108 PasswordAuthentication no
109 AuthorizedKeysFile %s
110 UsePAM no
111 AllowAgentForwarding yes
112 PermitRootLogin yes
113 StrictModes no
114 PermitUserEnvironment yes
115 """
116
117 def gen_sshd_config(filename, port, server_key, auth_keys):
118     conf = open(filename, "w")
119     text = _SSH_CONF % (port, server_key, auth_keys)
120     conf.write(text)
121     conf.close()
122     return filename
123
124 def gen_auth_keys(pubkey, output, environ):
125     #opts = ['from="127.0.0.1/32"'] # fails in stupid yans setup
126     opts = []
127     for k, v in environ.items():
128         opts.append('environment="%s=%s"' % (k, v))
129
130     lines = file(pubkey).readlines()
131     pubkey = lines[0].split()[0:2]
132     out = file(output, "w")
133     out.write("%s %s %s\n" % (",".join(opts), pubkey[0], pubkey[1]))
134     out.close()
135     return output
136
137 def start_ssh_agent():
138     ssh_agent = nepi.util.environ.find_bin_or_die("ssh-agent")
139     proc = subprocess.Popen([ssh_agent], stdout = subprocess.PIPE)
140     (out, foo) = proc.communicate()
141     assert proc.returncode == 0
142     d = {}
143     for l in out.split("\n"):
144         match = re.search("^(\w+)=([^ ;]+);.*", l)
145         if not match:
146             continue
147         k, v = match.groups()
148         os.environ[k] = v
149         d[k] = v
150     return d
151
152 def stop_ssh_agent(data):
153     # No need to gather the pid, ssh-agent knows how to kill itself; after we
154     # had set up the environment
155     ssh_agent = nepi.util.environ.find_bin_or_die("ssh-agent")
156     null = file("/dev/null", "w")
157     proc = subprocess.Popen([ssh_agent, "-k"], stdout = null)
158     null.close()
159     assert proc.wait() == 0
160     for k in data:
161         del os.environ[k]
162
163 class test_environment(object):
164     def __init__(self):
165         sshd = find_bin_or_die("sshd")
166         environ = {}
167         if 'PYTHONPATH' in os.environ:
168             environ['PYTHONPATH'] = ":".join(map(os.path.realpath, 
169                 os.environ['PYTHONPATH'].split(":")))
170         if 'NEPI_NS3BINDINGS' in os.environ:
171             environ['NEPI_NS3BINDINGS'] = \
172                     os.path.realpath(os.environ['NEPI_NS3BINDINGS'])
173         if 'NEPI_NS3LIBRARY' in os.environ:
174             environ['NEPI_NS3LIBRARY'] = \
175                     os.path.realpath(os.environ['NEPI_NS3LIBRARY'])
176
177         self.dir = tempfile.mkdtemp()
178         self.server_keypair = gen_ssh_keypair(
179                 os.path.join(self.dir, "server_key"))
180         self.client_keypair = gen_ssh_keypair(
181                 os.path.join(self.dir, "client_key"))
182         self.authorized_keys = gen_auth_keys(self.client_keypair[1],
183                 os.path.join(self.dir, "authorized_keys"), environ)
184         self.port = get_free_port()
185         self.sshd_conf = gen_sshd_config(
186                 os.path.join(self.dir, "sshd_config"),
187                 self.port, self.server_keypair[0], self.authorized_keys)
188
189         self.sshd = subprocess.Popen([sshd, '-q', '-D', '-f', self.sshd_conf])
190         self.ssh_agent_vars = start_ssh_agent()
191         add_key_to_agent(self.client_keypair[0])
192
193     def __del__(self):
194         if self.sshd:
195             os.kill(self.sshd.pid, signal.SIGTERM)
196             self.sshd.wait()
197         if self.ssh_agent_vars:
198             stop_ssh_agent(self.ssh_agent_vars)
199         shutil.rmtree(self.dir)
200