source: fedkit/fed-tun.pl @ f3691ff

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

events to both federants - start repeaters on both sides of the gateway

  • Property mode set to 100755
File size: 12.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
32# Ports that are forwarded between testbeds
33my $TMCD_PORT = 7777;
34my $SMBFS_PORT = 139;
35my $PUBSUB_PORT = 16505;
36
37
38my $remote_pubsub_port = $PUBSUB_PORT - 1;  # There will be a local
39                                            # pubsubd running, so we
40                                            # dodge the port on the
41                                            # remote tunnel node.
42sub setup_bridging;
43sub setup_tunnel_cfg;
44sub parse_config;
45
46# Option use is as follows:
47#    -f         filename containing config file
48#    -d         turn on debugging output
49#    -r         remotely invoked
50#               (if remotely invoked the last two args are the tun interface
51#               number and the remote address of the tunnel)
52
53my $usage = "Usage: fed-tun.pl [-r] [-d] [-f config-filename] [count addr]\n";
54
55my %opts;       # Note that this is used for both getops and the options file
56my @expected_opts = qw(active tunnelcfg bossname fsname type
57                       peer pubkeys privkeys);
58my $filename;
59my $remote;
60my $debug = 1;
61my $count;
62my $addr;
63my $active;
64my $type;
65my $tunnelcfg;
66my $ssh_port_fwds = "";
67my $remote_script_dir;          # location of the other sides fed-tun.pl
68my $event_repeater;             # The pathname of the event repeater
69my $remote_config_file;         # Config file for the other side
70
71if ($#ARGV != 0 && !getopts('df:r', \%opts)) {
72    die "$usage";
73}
74
75if (defined($opts{'d'})) {
76    $debug = 1;
77}
78
79if (defined($opts{'f'})) {
80    $filename = $opts{'f'};
81}
82
83if (defined($opts{'r'})) {
84    $remote = 1;
85    die "$usage" if ($#ARGV != 1);
86   
87    $count = pop @ARGV;
88    $addr = pop @ARGV;
89}
90
91die "$usage" if (!defined($remote) && !defined($filename));
92
93if (defined($filename)) {
94    &parse_config("$filename", \%opts) || 
95        die "Cannot read config file $filename: $!\n";
96
97    foreach my $opt (@expected_opts) {
98        warn "Missing $opt option\n" if (!defined($opts{$opt}));
99    }
100
101    $active = 1 if ($opts{'active'} =~ /true/i);
102    $tunnelcfg = 1 if ($opts{'tunnelcfg'} =~ /true/i);
103    $type = $opts{'type'};
104    $type =~ tr/A-Z/a-z/;
105    $remote_script_dir = $opts{'remotescriptdir'} || ".";
106    $event_repeater = $opts{'eventrepeater'};
107    $remote_config_file = $opts{'remoteconfigfile'};
108    $remote_config_file = "-f $remote_config_file" if $remote_config_file;
109
110    if (defined($opts{'fsname'})) {
111        $ssh_port_fwds = "-R :$SMBFS_PORT:$opts{'fsname'}:$SMBFS_PORT ";
112    }
113
114    if (defined($opts{'bossname'})) {
115        $ssh_port_fwds .= "-R :$TMCD_PORT:$opts{'bossname'}:$TMCD_PORT ";
116    }
117
118    if (defined($opts{'eventservername'})) {
119        $ssh_port_fwds .= "-R :$remote_pubsub_port:$opts{'eventservername'}:" . 
120            "$PUBSUB_PORT ";
121    }
122    if (defined($opts{'remoteeventservername'})) {
123        $ssh_port_fwds .= "-L :$remote_pubsub_port:" . 
124            "$opts{'remoteeventservername'}:$PUBSUB_PORT ";
125    }
126
127    $ssh_port_fwds = "" if ($opts{'type'} eq 'experiment');
128
129    print "ssh_port_fwds = $ssh_port_fwds\n" if ($debug);
130}
131
132# Need these to make the Ethernet tap and bridge to work...
133
134system("kldload /boot/kernel/if_bridge.ko");
135system("kldload /boot/kernel/if_tap.ko");
136
137if ($tunnelcfg && !$remote) {
138    # Most Emulab-like testbeds use globally-routable addresses on the
139    # control net;  at DETER, we isolate the control net from the Internet.
140    # On DETER-like testbeds, we need to create special tunneling nodes
141    # with external access.  Set up the external addresses as necessary.
142    &setup_tunnel_cfg(%opts);
143}
144
145if (!$remote) {
146    system("umask 077 && cp $opts{'privkeys'} /root/.ssh/id_rsa");
147    system("umask 077 && cp $opts{'pubkeys'} /root/.ssh/id_rsa.pub");
148    system("umask 077 && cat $opts{'pubkeys'} >> /root/.ssh/authorized_keys");
149}
150
151if ($active) {
152    # If we're the initiator, open up a separate tunnel to the remote
153    # host for each of the different experiment net interfaces on this
154    # machine.  Execute this startup script on the far end, but with
155    # the -r option to indicate that it's getting invoked remotely and
156    # we should just handle the remote-end tasks.
157
158    # Set up synchronization, so that the various user machines won't try to
159    # contact boss before the tunnels are set up.  (Thanks jjh!)
160
161    do {
162        system("$NC -z $opts{'peer'} $SSH_PORT");
163    } until (!$?);
164
165    # XXX:  Do we need to clear out previously created bridge interfaces?
166
167    my $count = 0;
168    my @SSHCMD;
169
170    # If we are just setting up a control net connection, just fire up
171    # ssh with the null command, and hang loose.
172
173    if ($type eq "control") {
174        system("$SSH $ssh_port_fwds -Nno \"StrictHostKeyChecking no\" $opts{'peer'} &"); #or die "Failed to run ssh";
175
176        exit;
177    }
178
179    open(IFFILE, "/var/emulab/boot/ifmap") || die "couldn't open ifmap\n";
180    while (<IFFILE>) {
181        my @a = split(' ');
182        my $iface = $a[0];
183        my $addr = $a[1];
184        my $bridge = "bridge" . $count;
185        my $tun = "tap" . $count;
186
187        print "Found $iface, $addr, to bridge on $bridge\n" if ($debug);
188
189        # Note that we're going to fire off an ssh which will never return;
190        # we need the connection to stay up to keep the tunnel up.
191        # In order to check for problems, we open it this way and read
192        # the expected single line of output when the tunnel is connected.
193
194        print "$SSH -w $count:$count $ssh_port_fwds -o \"StrictHostKeyChecking no\" $opts{'peer'}  \"$remote_script_dir/fed-tun.pl $remote_config_file -r $addr $count\"\n" if $debug;
195        open($SSHCMD[$count], "$SSH -w $count:$count $ssh_port_fwds -o \"StrictHostKeyChecking no\" $opts{'peer'}  \"$remote_script_dir/fed-tun.pl $remote_config_file -r $addr $count\" |") or die "Failed to run ssh";
196
197        my $check = <$SSHCMD[$count]>;  # Make sure something ran...
198        print "Got line [$check] from remote side\n" if ($debug);
199
200        &setup_bridging($tun, $bridge, $iface, $addr);
201        $count++;
202        $ssh_port_fwds = "";  # only do this on the first connection
203    }
204    close(IFFILE);
205
206    # Start a local event repeater (unless we're missing parameters
207    die "Missing event repeater params (No config file ?)\n"
208        unless $event_repeater && $opts{'remoteexperiment'} && 
209        $opts{'localexperiment'};
210
211    print "Starting event repeater\n" if $debug;
212   
213    print("$event_repeater -M -P $remote_pubsub_port -S localhost " . 
214        "-E $opts{'remoteexperiment'} -e $opts{'localexperiment'}\n") 
215        if $debug;
216    # Connect to the forwarded pubsub port on this host to listen to the
217    # other experiment's events, and to the local experiment to forward
218    # events.
219    system("$event_repeater -M -P $remote_pubsub_port -S localhost " . 
220        "-E $opts{'remoteexperiment'} -e $opts{'localexperiment'}");
221    warn "Event repeater returned $?\n" if $?;
222} elsif ($remote) {
223    # We're on the remote system;  figure out which interface to
224    # tweak, based on the IP address passed in.
225
226    my $iter = 0;
227    my $iface;
228
229    open(RTFILE, "$ROUTE_GET $addr |") || die "couldn't do $ROUTE_GET\n";
230    while (<RTFILE>) {
231        if (/interface: (\w+)/) {
232            $iface = $1;
233        }
234    }
235    close(RTFILE);
236
237    die "Couldn't find interface to use." if (!defined($iface));
238    my $bridge = "bridge" . $count;
239    my $tun = "tap" . $count;
240
241    &setup_bridging($tun, $bridge, $iface, $addr);
242    print "Remote connection all set up!\n";  # Trigger other end with output
243
244    # If this is the first remote invocation on a control gateway, start the
245    # event repeater.
246
247    my $file = new IO::File(">/tmp/remote");
248    print($file "hello!!!\n") if $file;
249    if ( $count == 0 && $type ne "experiment" ) {
250        my $remote_pubsub_port = $PUBSUB_PORT - 1;  # There will be a local
251                                                    # pubsubd running, so we
252                                                    # dodge the port on the
253                                                    # remote tunnel node.
254        print($file "In here!\n");
255        # Make sure we have the relevant parameters
256        die "Missing event repeater params (No config file ?)\n"
257            unless $event_repeater && $opts{'remoteexperiment'} && 
258            $opts{'localexperiment'};
259
260        print "Starting event repeater\n" if $debug;
261       
262        print($file "$event_repeater -P $remote_pubsub_port -S localhost " . 
263            "-E $opts{'remoteexperiment'} -e $opts{'localexperiment'}\n") 
264            if $file;
265        # Connect to the forwarded pubsub port on this host to listen to the
266        # other experiment's events, and to the local experiment to forward
267        # events.
268        system("$event_repeater -P $remote_pubsub_port -S localhost " . 
269            "-E $opts{'remoteexperiment'} -e $opts{'localexperiment'}");
270        warn "Event repeater returned $?\n" if $?;
271    }
272    $file->close() if $file;
273} else {
274    print "inactive end of a connection, finishing" if ($debug);
275}
276
277print "all done!\n" if ($debug);
278exit;
279
280
281# Set up the bridging for the new stuff...
282
283sub setup_bridging($; $; $; $) {
284    my ($tun, $bridge, $iface, $addr) = @_;
285
286    print "Waiting to see if new iface $tun is up\n" if ($debug);
287
288    do {
289        sleep 1;
290        system("$IFCONFIG $tun");
291    } until (!$?);
292
293    print "setting up $bridge with $iface and nuking $addr\n" if ($debug);
294
295    system("ifconfig $bridge create");
296    system("ifconfig $iface delete $addr");
297    system("ifconfig $bridge addm $iface up");
298    system("ifconfig $bridge addm $tun");
299}
300
301# Set up tunnel info for DETER-like testbeds.
302
303sub setup_tunnel_cfg {
304    my (%opts) = @_;
305    my $tunnel_iface = "em0";   # XXX
306    my $tunnel_ip;
307    my $tunnel_mask;
308    my $tunnel_mac;
309    my $tunnel_router;
310
311    print "Opening $TMCC tunnelip\n" if ($debug);
312
313    open(TMCD, "$TMCC tunnelip |") || die "tmcc failed\n";
314    print "Opened $TMCC tunnelip\n" if ($debug);
315    while (<TMCD>) {
316        print "got one line from tmcc\n" if ($debug);
317        print if ($debug);
318        if (/^TUNNELIP=([0-9.]*) TUNNELMASK=([0-9.]*) TUNNELMAC=(\w*) TUNNELROUTER=([0-9.]*)$/) {
319            $tunnel_ip = $1;
320            $tunnel_mask = $2;
321            $tunnel_mac = $3;
322            $tunnel_router = $4;
323        }
324    }
325    close(TMCD);
326
327    die "Unable to determine tunnel node configuration information"
328        if (!defined($tunnel_router));
329
330    print "tunnel options:  ip=$tunnel_ip mask=$tunnel_mask mac=$tunnel_mac router=$tunnel_router\n" if ($debug);
331
332    # Sadly, we ignore the tunnel mac for now -- we should eventually
333    # use it to determine which interface to use, just like the
334    # Emulab startup scripts.
335
336    system("ifconfig $tunnel_iface $tunnel_ip" .
337           ($tunnel_mask ? " netmask $tunnel_mask" : ""));
338    warn "configuration of tunnel interface failed" if ($?);
339
340    # Sometimes the insertion of DNS names lags a bit.  Retry this
341    # configuration a few times to let DNS catch up.  Might want to really
342    # check the DNS name before we try this...
343    my $config_succeeded = 0;
344    my $tries = 0;
345    my $max_retries = 6;
346
347    do {
348        system("route add $opts{'peer'} $tunnel_router");
349        if ( $? ) {
350            warn "configuration routes via tunnel interface failed";
351            $tries++;
352            sleep(10);
353        }
354        else { $config_succeeded = 1; }
355    } until ( $config_succeeded || $tries > $max_retries );
356
357    print "setup_tunnel_cfg done\n" if ($debug);
358}
359
360# Trick config-file parsing code from Ted Faber:
361
362# Parse the config file.  The format is a colon-separated parameter name
363# followed by the value of that parameter to the end of the line.  This parses
364# that format and puts the parameters into the referenced hash.  Parameter
365# names are mapped to lower case, parameter values are unchanged.  Returns 0 on
366# failure (e.g. file open) and 1 on success.
367sub parse_config {
368    my($file, $href) = @_;
369    my($fh) = new IO::File($file);
370       
371    unless ($fh) {
372        warn "Can't open $file: $!\n";
373        return 0;
374    }
375
376    while (<$fh>) {
377        next if /^\s*#/ || /^\s*$/;     # Skip comments & blanks
378        chomp;
379        /^([^:]+):\s*(.*)/ && do {
380            my($key) = $1; 
381
382            $key =~ tr/A-Z/a-z/;
383            $href->{$key} = $2;
384            next;
385        };
386        warn "Unparasble line in $file: $_\n";
387    }
388    $fh->close();   # It will close when it goes out of scope, but...
389    return 1;
390}
Note: See TracBrowser for help on using the repository browser.