source: fedkit/fed-tun.pl @ 4abace9

axis_examplecompt_changesinfo-opsversion-1.30version-2.00version-3.01version-3.02
Last change on this file since 4abace9 was 4abace9, checked in by Ted Faber <faber@…>, 16 years ago

Changes to imporve reliability of routes coming up. Restructuring of
federate leaves the stsyem in a state where we can safely restart the router
(specifically, talking to the local boss again) and we restart it in the
final topology. This introduces a lag in routing actually being established.
It may be useful to add a lag to the startcmd to take this into account.

  • Property mode set to 100755
File size: 9.1 KB
Line 
1#!/usr/bin/perl -w
2
3# Kevin Lahey, lahey@isi.edu
4# July 11, 2007
5
6# Set up ssh tunnel infrastructure for federation:
7#
8# * Parse the configuration file provided.
9#
10# * Figure out whether we're the initiator or the reciever;  if we're
11#   the receiver, we just need to set up ssh keys and exit.
12#
13# * Pick out the experimental interface, remove the IP address
14#
15# * Create a layer 2 ssh tunnel, set up bridging, and hang loose.
16#
17
18use strict;
19use Getopt::Std;
20use POSIX qw(strftime);
21use Sys::Hostname;
22use IO::File;
23
24my $IFCONFIG = "/sbin/ifconfig";
25my $TMCC = "/usr/local/etc/emulab/tmcc";
26my $SSH = "/usr/local/bin/ssh";
27my $NC = "/usr/bin/nc";
28my $SSH_PORT = 22;
29my $ROUTE_GET = "/sbin/route get";  # XXX:  works on FreeBSD, but should
30                                    #       should be 'ip route get' for Linux
31
32sub setup_bridging;
33sub setup_tunnel_cfg;
34sub parse_config;
35
36# Option use is as follows:
37#    -f         filename containing config file
38#    -d         turn on debugging output
39#    -r         remotely invoked
40#               (if remotely invoked the last two args are the tun interface
41#               number and the remote address of the tunnel)
42
43my $usage = "Usage: fed-tun.pl [-r] [-d] [-f config-filename] [count addr]\n";
44
45my %opts;       # Note that this is used for both getops and the options file
46my @expected_opts = qw(active tunnelcfg bossname fsname type
47                       peer pubkeys privkeys);
48my $filename;
49my $remote;
50my $debug = 1;
51my $count;
52my $addr;
53my $active;
54my $type;
55my $tunnelcfg;
56my $ssh_port_fwds = "";
57my $remote_script_dir;          # location of the other sides fed-tun.pl
58
59if ($#ARGV != 0 && !getopts('df:r', \%opts)) {
60    die "$usage";
61}
62
63if (defined($opts{'d'})) {
64    $debug = 1;
65}
66
67if (defined($opts{'f'})) {
68    $filename = $opts{'f'};
69}
70
71if (defined($opts{'r'})) {
72    $remote = 1;
73    die "$usage" if ($#ARGV != 1);
74   
75    $count = pop @ARGV;
76    $addr = pop @ARGV;
77}
78
79die "$usage" if (!defined($remote) && !defined($filename));
80
81if (defined($filename)) {
82    &parse_config("$filename", \%opts) || 
83        die "Cannot read config file $filename: $!\n";
84
85    foreach my $opt (@expected_opts) {
86        warn "Missing $opt option\n" if (!defined($opts{$opt}));
87    }
88
89    $active = 1 if ($opts{'active'} =~ /true/i);
90    $tunnelcfg = 1 if ($opts{'tunnelcfg'} =~ /true/i);
91    $type = $opts{'type'};
92    $type =~ tr/A-Z/a-z/;
93    $remote_script_dir = $opts{'remotescriptdir'} || ".";
94
95    if (defined($opts{'fsname'})) {
96        $ssh_port_fwds = "-R :139:$opts{'fsname'}:139 ";
97    }
98
99    if (defined($opts{'bossname'})) {
100        $ssh_port_fwds .= "-R :7777:$opts{'bossname'}:7777 ";
101    }
102
103    $ssh_port_fwds = "" if ($opts{'type'} eq 'experiment');
104
105    print "ssh_port_fwds = $ssh_port_fwds\n" if ($debug);
106}
107
108# Need these to make the Ethernet tap and bridge to work...
109
110system("kldload /boot/kernel/if_bridge.ko");
111system("kldload /boot/kernel/if_tap.ko");
112
113if ($tunnelcfg && !$remote) {
114    # Most Emulab-like testbeds use globally-routable addresses on the
115    # control net;  at DETER, we isolate the control net from the Internet.
116    # On DETER-like testbeds, we need to create special tunneling nodes
117    # with external access.  Set up the external addresses as necessary.
118    &setup_tunnel_cfg(%opts);
119}
120
121if (!$remote) {
122    system("umask 077 && cp $opts{'privkeys'} /root/.ssh/id_rsa");
123    system("umask 077 && cp $opts{'pubkeys'} /root/.ssh/id_rsa.pub");
124    system("umask 077 && cat $opts{'pubkeys'} >> /root/.ssh/authorized_keys");
125}
126
127if ($active) {
128    # If we're the initiator, open up a separate tunnel to the remote
129    # host for each of the different experiment net interfaces on this
130    # machine.  Execute this startup script on the far end, but with
131    # the -r option to indicate that it's getting invoked remotely and
132    # we should just handle the remote-end tasks.
133
134    # Set up synchronization, so that the various user machines won't try to
135    # contact boss before the tunnels are set up.  (Thanks jjh!)
136
137    do {
138        system("$NC -z $opts{'peer'} $SSH_PORT");
139    } until (!$?);
140
141    # XXX:  Do we need to clear out previously created bridge interfaces?
142
143    my $count = 0;
144    my @SSHCMD;
145
146    # If we are just setting up a control net connection, just fire up
147    # ssh with the null command, and hang loose.
148
149    if ($type eq "control") {
150        system("$SSH $ssh_port_fwds -Nno \"StrictHostKeyChecking no\" $opts{'peer'} &"); #or die "Failed to run ssh";
151
152        exit;
153    }
154
155    open(IFFILE, "/var/emulab/boot/ifmap") || die "couldn't open ifmap\n";
156    while (<IFFILE>) {
157        my @a = split(' ');
158        my $iface = $a[0];
159        my $addr = $a[1];
160        my $bridge = "bridge" . $count;
161        my $tun = "tap" . $count;
162
163        print "Found $iface, $addr, to bridge on $bridge\n" if ($debug);
164
165        # Note that we're going to fire off an ssh which will never return;
166        # we need the connection to stay up to keep the tunnel up.
167        # In order to check for problems, we open it this way and read
168        # the expected single line of output when the tunnel is connected.
169
170        open($SSHCMD[$count], "$SSH -w $count:$count $ssh_port_fwds -o \"StrictHostKeyChecking no\" $opts{'peer'}  \"$remote_script_dir/fed-tun.pl -r $addr $count\" |") or die "Failed to run ssh";
171
172        my $check = <$SSHCMD[$count]>;  # Make sure something ran...
173        print "Got line [$check] from remote side\n" if ($debug);
174
175        &setup_bridging($tun, $bridge, $iface, $addr);
176        $count++;
177        $ssh_port_fwds = "";  # only do this on the first connection
178    }
179    close(IFFILE);
180} elsif ($remote) {
181    # We're on the remote system;  figure out which interface to
182    # tweak, based on the IP address passed in.
183
184    my $iter = 0;
185    my $iface;
186
187    open(RTFILE, "$ROUTE_GET $addr |") || die "couldn't do $ROUTE_GET\n";
188    while (<RTFILE>) {
189        if (/interface: (\w+)/) {
190            $iface = $1;
191        }
192    }
193    close(RTFILE);
194
195    die "Couldn't find interface to use." if (!defined($iface));
196    my $bridge = "bridge" . $count;
197    my $tun = "tap" . $count;
198
199    &setup_bridging($tun, $bridge, $iface, $addr);
200    print "Remote connection all set up!\n";  # Trigger other end with output
201} else {
202    print "inactive end of a connection, finishing" if ($debug);
203}
204
205print "all done!\n" if ($debug);
206exit;
207
208
209# Set up the bridging for the new stuff...
210
211sub setup_bridging($; $; $; $) {
212    my ($tun, $bridge, $iface, $addr) = @_;
213
214    print "Waiting to see if new iface $tun is up\n" if ($debug);
215
216    do {
217        sleep 1;
218        system("$IFCONFIG $tun");
219    } until (!$?);
220
221    print "setting up $bridge with $iface and nuking $addr\n" if ($debug);
222
223    system("ifconfig $bridge create");
224    system("ifconfig $iface delete $addr");
225    system("ifconfig $bridge addm $iface up");
226    system("ifconfig $bridge addm $tun");
227}
228
229# Set up tunnel info for DETER-like testbeds.
230
231sub setup_tunnel_cfg {
232    my (%opts) = @_;
233    my $tunnel_iface = "em0";   # XXX
234    my $tunnel_ip;
235    my $tunnel_mask;
236    my $tunnel_mac;
237    my $tunnel_router;
238
239    print "Opening $TMCC tunnelip\n" if ($debug);
240
241    open(TMCD, "$TMCC tunnelip |") || die "tmcc failed\n";
242    print "Opened $TMCC tunnelip\n" if ($debug);
243    while (<TMCD>) {
244        print "got one line from tmcc\n" if ($debug);
245        print if ($debug);
246        if (/^TUNNELIP=([0-9.]*) TUNNELMASK=([0-9.]*) TUNNELMAC=(\w*) TUNNELROUTER=([0-9.]*)$/) {
247            $tunnel_ip = $1;
248            $tunnel_mask = $2;
249            $tunnel_mac = $3;
250            $tunnel_router = $4;
251        }
252    }
253    close(TMCD);
254
255    die "Unable to determine tunnel node configuration information"
256        if (!defined($tunnel_router));
257
258    print "tunnel options:  ip=$tunnel_ip mask=$tunnel_mask mac=$tunnel_mac router=$tunnel_router\n" if ($debug);
259
260    # Sadly, we ignore the tunnel mac for now -- we should eventually
261    # use it to determine which interface to use, just like the
262    # Emulab startup scripts.
263
264    system("ifconfig $tunnel_iface $tunnel_ip" .
265           ($tunnel_mask ? " netmask $tunnel_mask" : ""));
266    warn "configuration of tunnel interface failed" if ($?);
267
268    # Sometimes the insertion of DNS names lags a bit.  Retry this
269    # configuration a few times to let DNS catch up.  Might want to really
270    # check the DNS name before we try this...
271    my $config_succeeded = 0;
272    my $tries = 0;
273    my $max_retries = 6;
274
275    do {
276        system("route add $opts{'peer'} $tunnel_router");
277        if ( $? ) {
278            warn "configuration routes via tunnel interface failed";
279            $tries++;
280            sleep(10);
281        }
282        else { $config_succeeded = 1; }
283    } until ( $config_succeeded || $tries > $max_retries );
284
285    print "setup_tunnel_cfg done\n" if ($debug);
286}
287
288# Trick config-file parsing code from Ted Faber:
289
290# Parse the config file.  The format is a colon-separated parameter name
291# followed by the value of that parameter to the end of the line.  This parses
292# that format and puts the parameters into the referenced hash.  Parameter
293# names are mapped to lower case, parameter values are unchanged.  Returns 0 on
294# failure (e.g. file open) and 1 on success.
295sub parse_config {
296    my($file, $href) = @_;
297    my($fh) = new IO::File($file);
298       
299    unless ($fh) {
300        warn "Can't open $file: $!\n";
301        return 0;
302    }
303
304    while (<$fh>) {
305        next if /^\s*#/ || /^\s*$/;     # Skip comments & blanks
306        chomp;
307        /^([^:]+):\s*(.*)/ && do {
308            my($key) = $1; 
309
310            $key =~ tr/A-Z/a-z/;
311            $href->{$key} = $2;
312            next;
313        };
314        warn "Unparasble line in $file: $_\n";
315    }
316    $fh->close();   # It will close when it goes out of scope, but...
317    return 1;
318}
Note: See TracBrowser for help on using the repository browser.