source: fedkit/fed-tun.pl @ 33e3537

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

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

  • Property mode set to 100755
File size: 12.1 KB
RevLine 
[c9f5490]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#
[a098fab]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
[c9f5490]14#
[a098fab]15# * Create a layer 2 ssh tunnel, set up bridging, and hang loose.
[fd7a59b]16#
[c9f5490]17
18use strict;
19use Getopt::Std;
20use POSIX qw(strftime);
21use Sys::Hostname;
[a098fab]22use IO::File;
[c9f5490]23
[d501c38]24my $IFCONFIG = "/sbin/ifconfig";
[c9f5490]25my $TMCC = "/usr/local/etc/emulab/tmcc";
26my $SSH = "/usr/local/bin/ssh";
[a098fab]27my $NC = "/usr/bin/nc";
28my $SSH_PORT = 22;
[fd7a59b]29my $ROUTE_GET = "/sbin/route get";  # XXX:  works on FreeBSD, but should
30                                    #       should be 'ip route get' for Linux
[c9f5490]31
[f64fa81]32# Ports that are forwarded between testbeds
33my $TMCD_PORT = 7777;
34my $SMBFS_PORT = 139;
35my $PUBSUB_PORT = 16505;
36
[33e3537]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.
[a098fab]42sub setup_bridging;
43sub setup_tunnel_cfg;
44sub parse_config;
[c9f5490]45
[a098fab]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)
[c9f5490]52
[a098fab]53my $usage = "Usage: fed-tun.pl [-r] [-d] [-f config-filename] [count addr]\n";
[c9f5490]54
[fd7a59b]55my %opts;       # Note that this is used for both getops and the options file
[cd3eceb]56my @expected_opts = qw(active tunnelcfg bossname fsname type
57                       peer pubkeys privkeys);
[a098fab]58my $filename;
59my $remote;
60my $debug = 1;
[c9f5490]61my $count;
62my $addr;
[cd3eceb]63my $active;
64my $type;
65my $tunnelcfg;
66my $ssh_port_fwds = "";
[c8c45ee]67my $remote_script_dir;          # location of the other sides fed-tun.pl
[8034579]68my $event_repeater;             # The pathname of the event repeater
69my $remote_config_file;         # Config file for the other side
[c9f5490]70
[a098fab]71if ($#ARGV != 0 && !getopts('df:r', \%opts)) {
[c9f5490]72    die "$usage";
73}
74
[a098fab]75if (defined($opts{'d'})) {
76    $debug = 1;
77}
[c9f5490]78
[a098fab]79if (defined($opts{'f'})) {
80    $filename = $opts{'f'};
[c9f5490]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
[a098fab]91die "$usage" if (!defined($remote) && !defined($filename));
[c9f5490]92
[a098fab]93if (defined($filename)) {
94    &parse_config("$filename", \%opts) || 
95        die "Cannot read config file $filename: $!\n";
[c9f5490]96
[cd3eceb]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/;
[c8c45ee]105    $remote_script_dir = $opts{'remotescriptdir'} || ".";
[8034579]106    $event_repeater = $opts{'eventrepeater'};
107    $remote_config_file = $opts{'remoteconfigfile'};
108    $remote_config_file = "-f $remote_config_file" if $remote_config_file;
[c9f5490]109
[cd3eceb]110    if (defined($opts{'fsname'})) {
[f64fa81]111        $ssh_port_fwds = "-R :$SMBFS_PORT:$opts{'fsname'}:$SMBFS_PORT ";
[cd3eceb]112    }
[c9f5490]113
[cd3eceb]114    if (defined($opts{'bossname'})) {
[f64fa81]115        $ssh_port_fwds .= "-R :$TMCD_PORT:$opts{'bossname'}:$TMCD_PORT ";
[33e3537]116    }
117
118    if (defined($opts{'eventservername'})) {
[f64fa81]119        $ssh_port_fwds .= "-R :$remote_pubsub_port:$opts{'eventservername'}:" . 
120            "$PUBSUB_PORT ";
[cd3eceb]121    }
[33e3537]122    if (defined($opts{'remoteeventservername'})) {
123        $ssh_port_fwds .= "-L :$remote_pubsub_port:" . 
124            "$opts{'remoteeventservername'}:$PUBSUB_PORT ";
125    }
[c9f5490]126
[cd3eceb]127    $ssh_port_fwds = "" if ($opts{'type'} eq 'experiment');
[c9f5490]128
[cd3eceb]129    print "ssh_port_fwds = $ssh_port_fwds\n" if ($debug);
130}
[c9f5490]131
[a098fab]132# Need these to make the Ethernet tap and bridge to work...
[c9f5490]133
[a098fab]134system("kldload /boot/kernel/if_bridge.ko");
135system("kldload /boot/kernel/if_tap.ko");
[c9f5490]136
[cd3eceb]137if ($tunnelcfg && !$remote) {
[a098fab]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);
[c9f5490]143}
144
145if (!$remote) {
[a098fab]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}
[c9f5490]150
[cd3eceb]151if ($active) {
[a098fab]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.
[c9f5490]157
[a098fab]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!)
[c9f5490]160
[a098fab]161    do {
162        system("$NC -z $opts{'peer'} $SSH_PORT");
163    } until (!$?);
[c9f5490]164
165    # XXX:  Do we need to clear out previously created bridge interfaces?
166
167    my $count = 0;
[a098fab]168    my @SSHCMD;
[c9f5490]169
[d501c38]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
[c9f5490]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
[a098fab]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.
[c9f5490]193
[8034579]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";
[c9f5490]196
[a098fab]197        my $check = <$SSHCMD[$count]>;  # Make sure something ran...
[d501c38]198        print "Got line [$check] from remote side\n" if ($debug);
[c9f5490]199
[a098fab]200        &setup_bridging($tun, $bridge, $iface, $addr);
[c9f5490]201        $count++;
[a098fab]202        $ssh_port_fwds = "";  # only do this on the first connection
[c9f5490]203    }
204    close(IFFILE);
[33e3537]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 $?;
[a098fab]222} elsif ($remote) {
[fd7a59b]223    # We're on the remote system;  figure out which interface to
224    # tweak, based on the IP address passed in.
[c9f5490]225
226    my $iter = 0;
[fd7a59b]227    my $iface;
[c9f5490]228
[fd7a59b]229    open(RTFILE, "$ROUTE_GET $addr |") || die "couldn't do $ROUTE_GET\n";
230    while (<RTFILE>) {
231        if (/interface: (\w+)/) {
232            $iface = $1;
233        }
[c9f5490]234    }
[fd7a59b]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;
[a098fab]240
[fd7a59b]241    &setup_bridging($tun, $bridge, $iface, $addr);
[a098fab]242    print "Remote connection all set up!\n";  # Trigger other end with output
[8034579]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;
[a098fab]273} else {
274    print "inactive end of a connection, finishing" if ($debug);
[c9f5490]275}
276
277print "all done!\n" if ($debug);
278exit;
279
280
281# Set up the bridging for the new stuff...
282
[a098fab]283sub setup_bridging($; $; $; $) {
[c9f5490]284    my ($tun, $bridge, $iface, $addr) = @_;
285
[d501c38]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
[c9f5490]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}
[a098fab]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 ($?);
[4abace9]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 );
[a098fab]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.