assign_wrapper.in 69.6 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1
2
#!/usr/bin/perl -w

Leigh B. Stoller's avatar
Leigh B. Stoller committed
3
4
#
# EMULAB-COPYRIGHT
Leigh B. Stoller's avatar
Leigh B. Stoller committed
5
# Copyright (c) 2000-2003 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
6
7
8
9
# All rights reserved.
#


Leigh B. Stoller's avatar
Leigh B. Stoller committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# This function as the main assign loop.  It converts the virtual
# topology into a top input including LAN and delay translation.  It
# then snapshots the current testbed physical state and runs assign,
# looping a couple times if assign fails.  When assign successfully
# completes it will interpret the results.  Attempt to match any
# existing portmap entries and then update the delays and vlans table.

# Syntax: assign_wrapper <pid> <eid>

# Caveats:
#  The support for direct and interswitch links has not been testbed much.

# Settings
# delaythresh is the maximum delay in ms above which a delay node is needed.
24
#  (Note that the DB represents delays as floating point numbers)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
25
# maxrun is maximum number of times we run assign.
26
27
# delaywithswitch if 1 will use the switch to delay when possible.  Currently
#  this only works for 10mbit links.
28
$delaythresh = 2;
29
$maxrun = 20;
30
$delaywithswitch=0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
31

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#
# Some handy constants. Speed in Mbits/sec and Kbits/sec units.
# The conversion routine is to make explicit that we operate with two
# different sets of units. One is the topology, which is in Kbps now.
# The second is the physical description, which has been changed to
# Kbps in the DB (and in ptopgen).
#
# Its probably a good idea to leave portbw (current_speed) in Mbs, since
# those numbers are used at the switch and the interfaces, which really
# only think in Mbps.
#
my $S10Mbs  = 10;
my $S100Mbs = 100;
my $S10Kbs  = 10000;
my $S100Kbs = 100000;
sub BWConvert($) {
    #
    # Use this if physical units are in Mbs (used to be).
    #
    #my $bw = $_[0] / 1000;
    
    my $bw = $_[0];
    return $bw;
}

57
$DELAYCAPACITY = @DELAYCAPACITY@;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
58
$TBROOT = "@prefix@";
59
$ENV{'PATH'} = "/usr/bin:$TBROOT/libexec:$TBROOT/sbin:$TBROOT/bin";
60

61
62
use lib '@prefix@/lib';
use libdb;
63
use libtestbed;
64
require exitonwarn;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
65

66
67
68
69
70
#
# Turn off line buffering on output
#
$| = 1;

71
72
73
74
75
76
77
use Getopt::Std;

getopts('v',\%opt);

sub usage {
	print "Usage: $0 [-v] pid eid\n";
	print "		-v enables verbose output\n";
78
	exit(-1);
79
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
80

81
my $verbose = 0;
82
83
84
85
86
if ($opt{v}) {
	$verbose = 1;
}

if (@ARGV != 2) {
87
	usage();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
88
}
89

Leigh B. Stoller's avatar
Leigh B. Stoller committed
90
91
92
93
94
95
96
97
98
99
($pid,$eid) = @ARGV;

$ptopfile = "$pid-$eid-$$.ptop";

sub printdb {
    if ($verbose) {
	print $_[0];
    }
};

100
101
TBDebugTimeStamp("assign_wrapper started");

Leigh B. Stoller's avatar
Leigh B. Stoller committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
######################################################################
# Step 1 - Setup virtual topology
#
# Here we need to read the virtual topology in from the virt_nodes
# and virt_lans table.  We then need to add delay and lan nodes as
# necessary.
#
# Conversion details:
#   Let L be a LAN with N members.
#   If N == 2 
#      Let N1 be node 1
#      Let N2 be node 2
#      If L is delayed
#         Generate delay node D
#         Link N1 to D
#         Link N2 to D
#      Else
#         Link N1 to N2
#   Else
#      Generate lan node A
#      If L is delayed
#        Foreach node N in L
#           Generate delay node DN
#           Link A to DN
#           Link N to DN
#      Else
#        Foreach node N in L
#           Link N to A
#
# Datastructures:
#  nodes is indexed by virtual node and contains the node type.
133
134
#  isremotenode is indexed by virtual node and says whether the node is
#    is remote. We let wanassign deal with those nodes.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
135
136
137
138
139
#  nodelans is indexed by virtual node and contains a list of
#    <port>:<lan> that it is connected to.
#  ips is indexed by nodeport and contains the IP addresses.
#  lans is indexed by virtual lan and is a list of nodeport members.
#  lannodes is indexed by physical name is the set of lan nodes.
140
#  portbw is indexed by virtual nodeport and contains the bandwidth
141
142
143
144
#    of that port. Note that port bandwidth in the interfaces table is
#    left in Mbps units for now. Thats inconsistent, I know. For LANs with
#    other bandwidths the port speed will be 100 and a delay node will
#    be inserted.
145
146
#  fixed_nodes is indexed by virtual node name and points to physical node
#   name.
Christopher Alfeld's avatar
Christopher Alfeld committed
147
#  vtypes is indexed by vtype name and is a list of {weight types}.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
148
149
150
151
152
153
154
155
156
#
# Delay node names:
#  delay nodes are named tbdelayXX N > 2
#   and tbsdelayXX for N == 2.
# 
# Lan node nameS:
#  lan nodes are named lan/<virtual lan>
######################################################################

157
158
159
printdb "Generating TOP file.\n";
TBDebugTimeStamp("top started");

Leigh B. Stoller's avatar
Leigh B. Stoller committed
160
161
162
163
164
165
166
167
168
169
# Shark Hack
# For each LAN we replace all the sharks in the LAN with a single
# shark shelf node.  After this goes through assign we pull them
# all back out.
#
# sharkshelves is indexed by virtual shelf name and is a list of
# the virtual nodes in it.
# sharkshelfid is used to generate ids for shark shelves.
$sharkshelfid = 0;

170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# delayinfo stores the virt_lans info, and is indexed by virtual
# lan:node:port and is a list of delay, bandwidth, lossrate, rdelay,
# rbandwidth, rlossrate.  Where r* indicates switch->node and the
# others indicate node->switch.
my %delayinfo = ();

# queueinfo overlaps with delayinfo. It came later, and I added before
# I understood this stuff. It should be merged into delayinfo above.
# It holds the q_ stuff from virt_lans. 
my %queueinfo = ();

# delaylinks stores the actual link delay info, converted from the
# virt delay params above. It is indexed by link name and contains
# [delay,bw,loss] for each direction. 
my %delaylinks = ();

# delaynodes stores the names of delaynodes that we create on the
# fly using delayid. This is useful for doing isdelay? tests.
my %delaynodes = ();
my $delayid    = 0;

# nodedelays and linkdelays are the final (!) representation. Indexed by
# integer id, they store the physical node info and the delay info. 
my %nodedelays = ();
my %linkdelays = ();

# Set this when forcing linkdelays instead of delay nodes. Set in the NS
# file with a tb-compat directive. The force directive says to set up a
# link delay, even when no delay would otherwise be inserted. 
my $uselinkdelays   = 0;
my $forcelinkdelays = 0;

my $query_result =
    DBQueryFatal("SELECT uselinkdelays,forcelinkdelays from experiments ".
		 "where pid='$pid' and eid='$eid'");
($uselinkdelays,$forcelinkdelays) = $query_result->fetchrow_array();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
206

207
208
209
# Figure out what kind of links we have. Indexed by bandwidth and is
# just a set.
my %okbandwidths = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
210

211
212
$query_result =
    DBQueryFatal("SELECT type,max_speed from interface_types");
213

214
while (($type,$bandwidth) = $query_result->fetchrow_array()) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
215
216
    $okbandwidths{$bandwidth} = 1;
}
217
218
219
220
221
222
223
224
225

# Load delay osids and default osids for types
my %delayosids   = ();
my %defaultosids = ();

$query_result =
    DBQueryFatal("SELECT type,delay_osid,osid from node_types");

while (($type,$delayosid,$defosid) = $query_result->fetchrow_array()) {
226
227
    $delayosids{$type} = $delayosid;
#  $delayosids{$type} = "testbed-FBSD47-UPDATE";
228
229
    $defaultosids{$type} = $defosid;
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
230

Shashi Guruprasad's avatar
Shashi Guruprasad committed
231
232
233
234
235
236
# XXX NSE hack: List of simulated nodes. All these are gonna go
# into one pc850. Needs to change in distributed nse
my @simnodelist;
my %simnode_iplist = ();
my %iptonodemap = ();

Leigh B. Stoller's avatar
Leigh B. Stoller committed
237
238
239
# XXX Remote/Virt node hacks. Turns out to be similar to NSE.
my %isremotenode = ();
my %isvirtnode   = ();
240
241
my $remotecount  = 0;
my $virtcount    = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
242

Leigh B. Stoller's avatar
Leigh B. Stoller committed
243
printdb "Loading virt_nodes.\n";
244
$result =
Leigh B. Stoller's avatar
Leigh B. Stoller committed
245
246
    DBQueryFatal("select distinct vname,ips,vn.type,fixed, ".
		 " nt.isremotenode,nt.isvirtnode ".
247
248
249
250
251
		 " from virt_nodes as vn ".
		 "left join node_types as nt on ".
		 " nt.type=vn.type or nt.class=vn.type ".
		 "where pid='$pid' and eid='$eid'");

Leigh B. Stoller's avatar
Leigh B. Stoller committed
252
253
254
255
256
while (($vname,$ips,$type,$fixed,$isremote,$isvirt) = $result->fetchrow_array){
    if (defined($fixed) && $fixed eq "") {
	undef($fixed);
    }
    
257
    # REMOTENODE HACK
258
    #
259
    # if its a vtype, no entry in node_types. vtypes break remote nodes.
260
261
262
    # Need to look inside the vtype and make sure no mixing of vnodes and
    # physnodes. Later ...
    #
263
    if (! defined($isremote)) {$isremote = 0;}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
264
265
266
267
    if (! defined($isvirt)) {$isvirt = 0;}
    
    printdb "  $vname $type $ips";
    printdb " " . (defined($fixed) ? $fixed : "") . " $isremote\n";
268
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
269
270
271
272
273
274
275
276
277
278
    # We need to check the names to make sure they won't clash with
    # our internal delay node names.
    if (($vname =~ /^tbdelay\d+/) ||
	($vname =~ /^tbsdelay\d+/)) {
	print STDERR "Warning: $vname is a reserved name.  Working around.\n";
	($num) = ($vname =~ /(\d+)/);
	$delayid = $num + 1;
    }
    $nodes{$vname} = $type;
    $nodelans{$vname} = [];
279

Shashi Guruprasad's avatar
Shashi Guruprasad committed
280
281
282
283
    if( $type eq "sim" ) {
      push( @simnodelist, $vname );
      $simnode_iplist{$vname} = [];
    }    
284
    # REMOTENODE HACK
285
    # 
286
    $isremotenode{$vname} = $isremote;
287
288
    $remotecount++
	if ($isremote);
289
290
291
    foreach $ipinfo (split(" ",$ips)) {
	($port,$ip) = split(":",$ipinfo);
	$ips{"$vname:$port"} = $ip;
Shashi Guruprasad's avatar
Shashi Guruprasad committed
292
293
294
295
	if( $type eq "sim" ) {
	  push(@{$simnode_iplist{$vname}}, $ip);
	}
	$iptonodemap{$ip} = $vname;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
296
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
297
    $isvirtnode{$vname} = $isvirt;
298
299
    $virtcount++
	if ($isvirt);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
300
    if (defined($fixed)) {
301
302
	$fixed_nodes{$vname} = $fixed;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
303
}
304
$result->finish;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
305
306

printdb "Loading virt_lans.\n";
307
308
$result =
    DBQueryFatal("select vname,member,delay,bandwidth,lossrate," .
309
		 "rdelay,rbandwidth,rlossrate,widearea " .
310
311
312
		 "from virt_lans where pid='$pid' and eid='$eid'");

#
313
# REMOTENODE HACK: Remote nodes are special.
314
#
315
# A list of all lans that have remote nodes as members,
316
my %rnodelans = ();
317
318
319
# A list of all the tunnels we need to build. Each list member is a list
# of the nodes in the tunnel.
my %tunnels   = ();
320
321
322
323

#
# Now do the real pass.
# 
Christopher Alfeld's avatar
Christopher Alfeld committed
324
while (($vname,$member,$delay,$bandwidth,$lossrate,
325
	$rdelay,$rbandwidth,$rlossrate,$widearea) = $result->fetchrow_array) {
326
327
328
    ($node,$port) = split(":",$member);

    #
329
    # REMOTENODE HACK: 
330
    #
331
    # If its a duplex link involving a remotenode, skip it. 
332
    # We do not want to have assign deal with these. The nodes are
333
334
    # allocated as unconnected by another program, and we deal with
    # it later by creating tunnels.
335
    # 
336
    if ($widearea) {
337
338
339
340
	if (! defined($tunnels{$vname})) {
	    $tunnels{$vname} = [];
	}
	push(@{$tunnels{$vname}},$member);
341
	$rnodelans{$vname} = 1;
342
343
	printdb "    Added $member to tunnels of $vname\n";
	next;
344
345
    }
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
346
347
348
349
    if (! defined($lans{$vname})) {
	$lans{$vname} = [];
    }
    push(@{$lans{$vname}},$member);
Christopher Alfeld's avatar
Christopher Alfeld committed
350
351
    $delayinfo{"$vname:$member"} = [$delay,$bandwidth,$lossrate,
				    $rdelay,$rbandwidth,$rlossrate];
352
353
354
355
356
357
358
359
360

    #
    # Grab the Q stuff from virt_lans. I'm keeping this separate for
    # now until I understand whats going on. There are no "r" params
    # either. I have no idea how do to this stuff for lans, and for
    # duplex links the "r" params are not necessary. Each virt_lans
    # entry gives the params towards the switch, which equal the
    # reverse params for the other member. 
    #
361
    $query_result =
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
	DBQueryFatal("select q_limit,q_maxthresh,q_minthresh,q_weight, ".
		     "       q_linterm,q_qinbytes,q_bytes,q_meanpsize, ".
		     "       q_wait,q_setbit,q_droptail,q_red,q_gentle ".
		     "from virt_lans ".
		     "where pid='$pid' and eid='$eid' and ".
		     "      vname='$vname' and member='$member'");
    
    my ($q_limit,$q_maxthresh,$q_minthresh,$q_weight,$q_linterm,
	$q_qinbytes,$q_bytes,$q_meanpsize,$q_wait,$q_setbit,
	$q_droptail,$q_red,$q_gentle) = $query_result->fetchrow_array;
    
    $queueinfo{"$vname:$member"} =
	[$q_limit,$q_maxthresh,$q_minthresh,$q_weight,$q_linterm,
	 $q_qinbytes,$q_bytes,$q_meanpsize,$q_wait,$q_setbit,
	 $q_droptail,$q_red,$q_gentle];

    if ($q_red) {
	$mustdelay{$vname} = 1;
    }
    
382
383
384
385
386
387
388
389
390
391
392
393
    #
    # XXX - Whenever a delay node is inserted, port speeds are set to
    #       100Mbs, even if they requested exactly 10Mbs. This is a
    #       simplification. At some point we might want to force all the
    #       ports along the way to 10Mbs, and have the delay node worry
    #       about delay only, and not bandwidth. That will be harder to
    #       to do in this mess. See companion XXX below where the delays
    #       table is initialized. Initially, we set the speed to 10Mbs,
    #       if a delay node is insterted below, it resets this to 100Mbs.
    # 
    if ($bandwidth == $S10Kbs && $delaywithswitch) {
	$portbw{$member} = $S10Mbs;
394
    } else {
395
	$portbw{$member} = $S100Mbs;
396
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
397
    push(@{$nodelans{$node}},"$port:$vname");
398
    printdb "  portbw of $member = $portbw{$member}\n";
Christopher Alfeld's avatar
Christopher Alfeld committed
399
    printdb "  $vname $member - $delay $bandwidth $lossrate $rdelay $rbandwidth $rlossrate\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
400
401
    printdb "    Added $port:$vname to nodelans of $node\n";
}
402
$result->finish;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
403

404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#
# Check event list. Anytime we find an event to control a link, we need
# to drop a delay node in. start/stop especially, since thats the easiest
# way to do that, even if the link has no other traffic shaping in it. 
# 
printdb "Checking events for LINK commands.\n";
$result =
    DBQueryFatal("select distinct vname from eventlist as ex ".
		 "left join event_eventtypes as et on ex.eventtype=et.idx ".
		 "left join event_objecttypes as ot on ex.objecttype=ot.idx ".
		 "where ot.type='LINK' and ex.pid='$pid' and ex.eid='$eid'");
while (($vname) = $result->fetchrow_array) {
    $mustdelay{$vname} = 1;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
419
420
421
422
423
424
425
# Shark hack
foreach $lan (keys(%lans)) {
    $realmembers = [];
    $sharks = [];
    $hassharks = 0;
    foreach $member (@{$lans{$lan}}) {
	($node) = (split(":",$member))[0];
426
	if (($nodes{$node} eq "shark") || ($nodes{$node} eq "dnard")) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
427
428
429
430
431
432
433
434
435
436
437
438
	    push(@$sharks,$member);
	    $hassharks = 1;
	} else {
	    push(@$realmembers,$member);
	}
    }
    if ($hassharks) {
	$shelfid = "sharkshelf$sharkshelfid";
	printdb "  Creating shark shelf: $shelfid (" . 
	    join(" ",@$sharks) . ")\n";
	$sharkshelfid++;
	$sharkshelves{$shelfid} = $sharks;
439
	$delayinfo{"$lan:$shelfid:uplink"} = [0,$S100Kbs,0.0,
440
					      0,$S100Kbs,0.0];
Leigh B. Stoller's avatar
Leigh B. Stoller committed
441
442
443
444
445
446
447
	push(@$realmembers,"$shelfid:uplink");
	$nodes{$shelfid} = "shark-shelf";
    }
    $lans{$lan} = $realmembers;
}
# End shark hack

Christopher Alfeld's avatar
Christopher Alfeld committed
448
449
450
451
452
453
454
455
456
# Load virt types
printdb "Loading virt_vtypes.\n";
$result = DBQueryFatal("SELECT name,weight,members from virt_vtypes" .
		       " where pid=\"$pid\" and eid=\"$eid\"");
while (($name,$weight,$types) = $result->fetchrow_array) {
    printdb "  $name $weight $types\n";
    $vtypes{$name} = "$weight $types";
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
457
# Open the TOP file
458
$topfile = "$eid.top";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
459
open(TOPFILE,"> $topfile") || do {
460
461
    die("*** $0:\n".
	"    Could not open $topfile.\n");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
462
463
};

Christopher Alfeld's avatar
Christopher Alfeld committed
464
465
466
467
# Print out vtypes
foreach $vtype (keys(%vtypes)) {
    print TOPFILE "make-vclass $vtype $vtypes{$vtype}\n";
}
468
469
470

$nodes=0;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
471
472
foreach $node (keys(%nodes)) {
    # Shark hack
473
    if (($nodes{$node} ne "shark") &&
474
	($nodes{$node} ne "dnard") && !$isremotenode{$node}) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
475
	print TOPFILE "node $node $nodes{$node}\n";
476
477
478
	if ($nodes{$node} ne "shark-shelf") {
	    $nodes++;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
479
480
481
482
    }
    # End Shark hack
}

Shashi Guruprasad's avatar
Shashi Guruprasad committed
483
484
485
486
#
# lans that have simulated nodes
my %simnodelans = ();

Leigh B. Stoller's avatar
Leigh B. Stoller committed
487
488
foreach $lan (keys(%lans)) {
    @members = @{$lans{$lan}};
489
    printdb "$lan - " . join(" ",@members) . "\n";
490
491
492
    # Shark hack for rvr
    $sharks = 0;
    $nonsharks = 0;
Shashi Guruprasad's avatar
Shashi Guruprasad committed
493
494
    $simnodes = 0;
    $realnodes = 0;
495
    $emulated = 0;
496
    $trivial_ok = 0;
497
498
499
500
    foreach $member (@members) {
	($node) = (split(":",$member))[0];
	if ($nodes{$node} eq "shark-shelf") {
	    $sharks++;
501
	} elsif ($nodes{$node} eq "sim") {
Shashi Guruprasad's avatar
Shashi Guruprasad committed
502
503
	    $simnodes++;
	    $simnodelans{$lan} = 1;
504
505
506
507
	} else {
	    if ($isvirtnode{$node}) {
		$emulated++;
	    }
508
	    $nonsharks++;
Shashi Guruprasad's avatar
Shashi Guruprasad committed
509
	    $realnodes++;
510
511
	}
    }
512
513
514
    if ($simnodes > 0 && $realnodes == 0 && $sharks == 0) {
	$trivial_ok = 1;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
515
516
517
518
    if ($#members == 1) {
	($nodeport0,$nodeport1) = @members;
	$node0 = (split(":",$nodeport0))[0];
	$node1 = (split(":",$nodeport1))[0];
Christopher Alfeld's avatar
Christopher Alfeld committed
519
520
521
522
523
524
525
526
527
528
529
530
531
	($delay0,$bw0,$loss0,
	 $rdelay0,$rbw0,$rloss0) = @{$delayinfo{"$lan:$nodeport0"}};
	($delay1,$bw1,$loss1,
	 $rdelay1,$rbw1,$rloss1) = @{$delayinfo{"$lan:$nodeport1"}};
	# Here the r's aregoing to be 1->0 and the others 0->1
	$delay = $delay0+$rdelay1;
	$loss = 1-(1-$loss0)*(1-$rloss1);
	$bw = &min($bw0,$rbw1);
	$rdelay = $rdelay0+$delay1;
	$rloss = 1-(1-$rloss0)*(1-$loss1);
	$rbw = &min($rbw0,$bw1);
	$bandwidth = &getbandwidth(&min($bw0,$rbw1));
	$rbandwidth = &getbandwidth(&min($rbw0,$bw1));
Shashi Guruprasad's avatar
Shashi Guruprasad committed
532
	if (((($delay >= $delaythresh) ||
533
534
535
536
537
	     (($bw != $S100Kbs) && ($bw != $S10Kbs)) ||
	     (($delaywithswitch == 0) && 
	      (($bw != $S100Kbs) && (($sharks == 0) || ($nonsharks > 1)))) || 
	     ($loss != 0)) ||
	    (defined($mustdelay{$lan})) ||
538
	    ($forcelinkdelays != 0) ||
Christopher Alfeld's avatar
Christopher Alfeld committed
539
540
541
542
	    (($rdelay >= $delaythresh) ||
	     (($rbw != $S100Kbs) && ($rbw != $S10Kbs)) ||
	     (($delaywithswitch == 0) && 
	      (($rbw != $S100Kbs) && (($sharks == 0) || ($nonsharks > 1)))) || 
Shashi Guruprasad's avatar
Shashi Guruprasad committed
543
	     ($rloss != 0))) &&
544
545
546
547
	    # XXX simulated nodes hack. We don't want to put delay nodes
	    # between simulated nodes. If there is a link between a
	    # simulated and a real node, we might need to put in delay
	    # nodes
Shashi Guruprasad's avatar
Shashi Guruprasad committed
548
549
	    ($realnodes != 0)
	   ) {
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
	    if ($emulated || $uselinkdelays || $forcelinkdelays) {
		#
		# Emulated links are special. We want to do traffic shaping
		# but not using a delay node.
		#
		my $plink = "linksimple/$lan/$nodeport0,$nodeport1";
		
		$delaylinks{$plink} = [$nodeport0,$delay,$bw,$loss,
				       $nodeport1,$rdelay,$rbw,$rloss];
	    
		print(TOPFILE "link $plink $node0 $node1 ".
		      max($bw,$rbw) . " 0 0" .
		      ($emulated ? " emulated\n" : "\n"));

		printdb "Delay link $plink = " . 
		    join(" ",@{$delaylinks{$plink}}) . "\n";
	    }
	    else {
		my $delayname = "tbsdelay" . $delayid++;
		my $plink     = "linksdelaysrc/$lan/$nodeport0,$nodeport1";
		
		$delaylinks{$plink} = [$nodeport0,$delay,$bw,$loss,
				       $nodeport1,$rdelay,$rbw,$rloss];

		print TOPFILE "node $delayname delay\n";
		print TOPFILE "link linksdelaysrc/$lan/$nodeport0,$nodeport1 ".
		    "$node0 $delayname $bandwidth 0 0\n";
		print TOPFILE "link linksdelaydst/$lan/$nodeport1,$nodeport0 ".
		    "$node1 $delayname $bandwidth 0 0\n";

		$delaynodes{$delayname} = $delayname;
		
		printdb "Delay node $plink ($delayname) = " . 
		    join(" ",@{$delaylinks{$plink}}) . "\n";
	    }
585
586
587
588
589
590
591
592
	    #
	    # Ports are set to 100Mbs when a link gets a delay node.
	    # This can override initialization above cause we could not
	    # tell earlier if the link was going to get a real delay node
	    # or just a delaywithswitch.
	    #
	    $portbw{$nodeport0} = $S100Mbs;	    
	    $portbw{$nodeport1} = $S100Mbs;	    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
593
	} else {
594
595
596
597
598
	    print TOPFILE "link linksimple/$lan/$nodeport0,$nodeport1 ".
		"$node0 $node1 $bandwidth 0 0";
	    if ($emulated) {
		print TOPFILE " emulated";
	    }
599
600
601
	    if ($trivial_ok) {
		print TOPFILE " trivial_ok";
	    }
602
	    print TOPFILE "\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
603
	}
604
    } elsif ($#members != 0) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
605
606
607
	print TOPFILE "node lan/$lan lan\n";
	$lannodes{"lan/$lan"} = 1;
	foreach $member (@members) {
Christopher Alfeld's avatar
Christopher Alfeld committed
608
609
	    ($delay,$bw,$loss,
	     $rdelay,$rbw,$rloss) = @{$delayinfo{"$lan:$member"}};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
610
	    $bandwidth = &getbandwidth($bw);
Christopher Alfeld's avatar
Christopher Alfeld committed
611
	    $rbandwidth = &getbandwidth($rbw);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
612
	    ($node) = (split(":",$member))[0];
613
614
# XXX The expression below should be modified for better bandwidth support.
# Probably needs to happen post assign somehow.
Shashi Guruprasad's avatar
Shashi Guruprasad committed
615
	    if (((($delay >= $delaythresh) ||
616
617
618
619
620
621
		 (($bw != $S100Kbs) && ($bw != $S10Kbs))  ||
		 (($delaywithswitch == 0) && 
		  (($bw != $S100Kbs) && (($sharks == 0) ||
					 ($nonsharks > 1)))) ||
		 ($loss != 0)) || 
		(defined($mustdelay{$lan})) ||
622
		($forcelinkdelays != 0) ||
Christopher Alfeld's avatar
Christopher Alfeld committed
623
624
625
626
627
		(($rdelay >= $delaythresh) ||
		 (($rbw != $S100Kbs) && ($rbw != $S10Kbs))  ||
		 (($delaywithswitch == 0) && 
		  (($rbw != $S100Kbs) && (($sharks == 0) ||
					 ($nonsharks > 1)))) ||
Shashi Guruprasad's avatar
Shashi Guruprasad committed
628
		 ($rloss != 0))) &&
629
630
		# if we have 1 real node in the LAN, we may need to create
		# a lan
Shashi Guruprasad's avatar
Shashi Guruprasad committed
631
632
		($realnodes != 0)
	       ) {
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
		if ($emulated || $uselinkdelays || $forcelinkdelays) {
		    #
		    # Emulated links are special. We want to do traffic shaping
		    # but not using a delay node.
		    #
		    my $plink = "linklan/$lan/$member";
		    
		    $delaylinks{$plink} =
			[$member,$delay,$bw,$loss,
			 $member,$rdelay,$rbw,$rloss];

		    print(TOPFILE "link $plink $node lan/$lan " .
			  "$bandwidth 0 0 " .
			  ($emulated ? " emulated\n" : "\n"));

		    printdb "Delay link $plink = " .
			    join(" ", @{$delaylinks{$plink}}) . "\n";
		}
		else {
		    my $delayname = "tbdelay" . $delayid++;
		    my $plink     = "linkdelaysrc/$lan/$member";

		    $delaylinks{$plink} =
			[$member,$delay,$bw,$loss,
			 $member,$rdelay,$rbw,$rloss];
		    
		    print TOPFILE "node $delayname delay\n";
		    print TOPFILE "link linkdelaysrc/$lan/$member" .
			" $node $delayname $bandwidth 0 0\n";
		    print TOPFILE "link linkdelaydst/$lan/$member" .
			" lan/$lan $delayname $bandwidth 0 0\n";
		    
		    $delaynodes{$delayname} = $delayname;

		    printdb "Delay node $plink ($delayname) = " .
			    join(" ", @{$delaylinks{$plink}}) . "\n";
		}
670
671
672
673
674
675
676
		#
		# Port is set to 100Mbs when the link gets a delay node.
		# This can override initialization above cause we could not
		# tell earlier if the link was going to get a real delay node
		# or just a delaywithswitch.
		#
		$portbw{$member} = $S100Mbs;	    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
677
678
	    } else {
		print TOPFILE "link linklan/$lan/$member $node lan/$lan" .
679
680
681
682
		    " $bandwidth 0 0";
		if ($emulated) {
		    print TOPFILE " emulated";
		}
683
684
685
		if ($trivial_ok) {
		    print TOPFILE " trivial_ok";
		}
686
		print TOPFILE "\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
687
688
689
	    }
	}
    }
690
    # If a LAN has only one member we don't do anything.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
691
692
}

Shashi Guruprasad's avatar
Shashi Guruprasad committed
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
# XXX NSE hack
# Will find a free randomly chosen pc850 and fix sim nodes to it
# Assign's scoring needs to be fixed so that the solution has
# as many sim nodes on a phy node as possible while maxing out
# its interfaces. Currently having sim:N where N is a large
# number in the ptop file does not guarantee that all these
# get mapped to a single phy node even when that mapping has no
# violations and a low score. distributed nse will fix this
#$result =
#  DBQueryFatal("select a.node_id,a.type from nodes as a ".
#	   "left join reserved as b on a.node_id=b.node_id ".
#	   "left join reserved as m on a.phys_nodeid=m.node_id ".
#	   "where b.node_id is null and (a.role='testnode' and ".
#	   "      a.type='pc850' and ".
#	   "       (m.node_id is null or ".
#	   "        m.pid!='$DEADPID' or m.eid!='$DEADEID'))");
if( scalar(@simnodelist) > 0 ) {
  open(AVAIL,"$TBROOT/sbin/avail type=pc rand |")
    or die "*** $0:\n".
           "    avail failed\n";

  my $num = 0;
  while (<AVAIL>) {
    if (! /^\|/) {next};
    if (/node_id/) {next;}
    ($fixednode,$type) = /^\|([-a-zA-Z0-9]+)\s*\|(\w+)\s*\|(\w+)\s*\|$/;    
    $num++;
    last;
  }
  close(AVAIL);
  
  if( $num == 0 ) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
725
    print STDERR "$0: *** Insufficient PCs available.\n";
Shashi Guruprasad's avatar
Shashi Guruprasad committed
726
727
728
729
730
731
732
733
    exit(2);
  }

  foreach $simnode (@simnodelist) {
    print TOPFILE "fix-node $simnode $fixednode\n";
  }
}

734
735
# Print out fixed nodes
foreach $fixed (keys(%fixed_nodes)) {
736
    if (!$isremotenode{$fixed}) {
737
738
	print TOPFILE "fix-node $fixed $fixed_nodes{$fixed}\n";
    }
739
740
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
741
742
close TOPFILE;

743
# Set estimations
744
745
$minimum_nodes = $nodes + keys(%delaynodes)/$DELAYCAPACITY;
$maximum_nodes = $nodes + keys(%delaynodes);
746
DBQueryFatal("UPDATE experiments set maximum_nodes=$maximum_nodes, " .
747
	 "minimum_nodes=$minimum_nodes where pid=\"$pid\" and eid=\"$eid\"");
748
print "Minimum nodes = $minimum_nodes\n";
749
750
print "Maximum nodes = $maximum_nodes\n";

751
752
TBDebugTimeStamp("top finished");

Leigh B. Stoller's avatar
Leigh B. Stoller committed
753
754
755
756
757
758
759
760
761
######################################################################
# Step 2 - Assign Loop
# 
# Here we loop up to maxrun times.  In each loop we snapshot the
# current testbed state into a ptop file.  We then run assign.  If
# assign succeeds we attempt to reserve the resources.  If that works
# we're done with step 2 otherwise we loop again.
#
# v2pmap is indexed by virtual and contains the physical node.
Shashi Guruprasad's avatar
Shashi Guruprasad committed
762
# p2vmap is indexed by physical and contains one or more virtual nodes
Leigh B. Stoller's avatar
Leigh B. Stoller committed
763
764
765
766
767
# plinks is indexed by virtual name and contains 
#  (pnodeportA,pnodeportB) .  If one is a delay node it is always
#  the second.
#######################################################################

768
TBDebugTimeStamp("assign_loop started");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
769
770
771
772
773
$currentrun = 1;
while (1) {
    print "Assign Run $currentrun\n";

    # Violation counts
774
    $unassigned = -1;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
775
776
777
778
779
780
781
782
    $linkusers = -1;
    $bandwidth = -1;
    $desires = -1;

    # Clear v2pmap, p2vmap, and plinks
    undef %v2pmap;
    undef %p2vmap;
    undef %plinks;
783
784
    undef %toreserve;
    undef %virtnodes;
Shashi Guruprasad's avatar
Shashi Guruprasad committed
785
    
786
    TBDebugTimeStamp("ptopgen started");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
787
    # Snapshot
788
    system("ptopgen > $ptopfile");
789
    TBDebugTimeStamp("ptopgen finished");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
790
791

    # Get number of nodes
792
793
    my $numnodes_result = 
	DBQueryFatal("select a.node_id,a.type from" .
Leigh B. Stoller's avatar
Leigh B. Stoller committed
794
795
796
		     " nodes as a left join reserved as b" .
		     " on a.node_id=b.node_id" .
		     " where b.node_id is null" .
797
		     " and a.role='testnode' and a.type!='dnard'");
798
    $numnodes = $numnodes_result->numrows;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
799
800
    
    if ($numnodes < $minimum_nodes) {
801
	print STDERR "$0: *** Insufficient nodes available.\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
802
803
804
	exit(2);
    }

805
    TBDebugTimeStamp("assign started");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
806
807
    # Run assign
    $fail = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
808
    my $cmdargs = "$ptopfile $topfile";
809
    $cmdargs = "-p $cmdargs"
810
	if ($virtcount);
811
812
    print "assign $cmdargs\n";
    open(ASSIGNFP,"assign $cmdargs | tee assign.log |");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
813
814
815
816
817
818
819
820
    $violations = 0;
    $score = -1;

    # read output
    # Header
    printdb "Reading assign results.\n";
    while (<ASSIGNFP>) {
	chop;
821
822
823
824
	/No physical nodes of type (.+)$/ && do {
	    $score=-2;
	    print $_ . "\n";
	};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
825
826
827
828
	/^With ([0-9]+) violations$/ && do {
	    $violations = $1;
	    last;
	};
829
 	/^[ \t]+BEST SCORE: [ \t]+([0-9]+(\.[0-9]+)?)/ && ($score=$1);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
830
    }
831
832
833
834
835
    if ($score == -2) {
	# Type error
	print "Giving up.\n";
	exit(2);
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
836
837
838
839
840
841
842
843
844
845
846
    printdb "Found score $score, violations $violations.\n";

    # We don't bother reading anything else if violations occured.
    if (($violations == 0) && ($score != -1)) {
	# read nodes section
	while (<ASSIGNFP> !~ /^Nodes:/) {}
	printdb "Nodes:\n";
	while (<ASSIGNFP>) {
	    chop;
	    /^End Nodes$/ && last;
	    @info = split;
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
	    ($virtual,$physical) = @info[0,1];

	    # We don't care about LAN nodes anymore.
	    if (defined($lannodes{$virtual})) {
		next;
	    }
	    $toreserve{$physical} = 1;	    
	    
	    if ($isvirtnode{$virtual}) {
		#
		# If mapping a virtual node, then record that, since we need
		# to allocate the virtnodes on that physnode, later.
		#
		if (!defined($virtnodes{$physical})) {
		    $virtnodes{$physical} = [];
		}
		push(@{$virtnodes{$physical}}, $virtual);
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
865
	    $v2pmap{$virtual} = $physical;
Shashi Guruprasad's avatar
Shashi Guruprasad committed
866
	    if( ! defined($p2vmap{$physical}) ) {
867
		$p2vmap{$physical} = [];
Shashi Guruprasad's avatar
Shashi Guruprasad committed
868
869
	    }
	    push(@{$p2vmap{$physical}}, $virtual);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
870
871
872
873
874
875
876
877
	    printdb "  $virtual $physical\n";
	}

	# read Edges
	# By convention, in plinks, the delay node is always the second
	# entry.
	while (<ASSIGNFP> !~ /^Edges:/) {}
	printdb "Edges:\n";
Shashi Guruprasad's avatar
Shashi Guruprasad committed
878
879
	EDGEWHILE: while (<ASSIGNFP>) {
	    /^End Edges$/ && last EDGEWHILE;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
880
881
882
883
884
885
886
887
888
	    @info = split;
	    $line = $_;
	    $_ = $info[1]; # type
	  SWITCH1: {
	      /^intraswitch$/ && do {
		  ($vlink,$rawA,$rawB) = @info[0,3,5];
		  last SWITCH1;
	      };
	      /^interswitch$/ && do {
889
890
		  ($vlink,$rawA,$rawB) = @info[0,3,$#info];
		  last SWITCH1;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
891
892
	      };
	      /^direct$/ && do {
893
894
		  die("*** $0:\n".
		      "    Unsupported link type: direct.\n");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
895
	      };
Shashi Guruprasad's avatar
Shashi Guruprasad committed
896
897
898
899
900
901
	      /^trivial$/ && do {
		  # we don't have plinks for trivial links
		  $vlink = $info[0];
		  $plinks{$vlink} = [];
		  next EDGEWHILE;
	      };
Leigh B. Stoller's avatar
Leigh B. Stoller committed
902
903
	      print "Found garbage: $line\n";
	  }
904
905
906
907
	    $nodeportA = &getnodeport($rawA);
	    $nodeportB = &getnodeport($rawB);
	    $nodeportA =~ s/\//:/;
	    $nodeportB =~ s/\//:/;
908
	    $plinks{$vlink} = [$nodeportA,$nodeportB];
Leigh B. Stoller's avatar
Leigh B. Stoller committed
909
910
911
912
913
914
	    printdb "  $vlink " . join(" ",@{$plinks{$vlink}}) . "\n";
	}
    } else {
	# spit out up to nodes
	print "ASSIGN FAILED:\n";       
	while (<ASSIGNFP>) {
915
	    if (/link_users:\s*(\d+)$/) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
916
		$linkusers = $1;
917
	    } elsif (/bandwidth:\s*(\d+)$/) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
918
		$bandwidth = $1;
919
	    } elsif (/unassigned:\s*(\d+)$/) {
920
		$unassigned = $1;
921
	    } elsif (/desires:\s*(\d+)$/) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
922
923
924
925
926
927
928
929
930
		$desires = $1;
	    }
	    if (/^Nodes:/) {last;}
	    print "$_";
	}
	$fail = 1;
    }
    while (<ASSIGNFP>) { } # Read anything left in the pipe before closing
    close(ASSIGNFP);
931
    TBDebugTimeStamp("assign finished");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
932

933
    TBDebugTimeStamp("reserving started");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
934
    # Reserve resources
935
    if (!$fail) {
936
	if (system("nalloc $pid $eid " . join(" ", keys(%toreserve)))) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
937
	    print "Failed to reserve nodes. Trying again.\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
938
	} else {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
939
	    print "Successfully reserved physical nodes\n";
940
	    TBDebugTimeStamp("reserving finished");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
	    last;
	}
    }

    # Check for exit
    if ($currentrun >= $maxrun) {
	$exitcode = 1;
	if ($bandwidth > 0) {
	    $exitcode += 4;
	} 
	if ($linkusers > 0) {
	    $exitcode += 8;
	}
	if ($desires > 0) {
	    $exitcode += 16;
	}
957
958
959
	if ($unassigned > 0) {
	    $exitcode += 32;
	}
960
961
	print "*** $0:\n".
	      "    Reached run limit. Giving up. Exitcode: $exitcode.\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
962
963
964
965
966
	exit($exitcode);
    }
    $currentrun++;
}

967
968
TBDebugTimeStamp("assign_loop finished");

969
970
971
972
973
974
975
976
977
978
###########################################################################
# Step 2A
#
# We run the wanassigner to allocate remote nodes. We do this after cause
# it takes so long. We run it just once.
#
# wanassign does its own nalloc.
#
###########################################################################

979
980
981
982
983
984
985
986
#
# VIRTNODES HACK: physical nodes (from the nodes table) might really
# be a virtual node :-) Must record the underlying phys_nodeid and an
# indicator for jail.
#
my %jailed = ();

# Now allocate the remote nodes. 
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
if (scalar(keys(%isremotenode))) {
    my $success  = 0;
    my $doremote = 0;
    
    foreach my $value (values(%isremotenode)) {
	if ($value) {
	    $doremote = 1;
	}
    }
    
    if ($doremote) {
	print "Running 'wanassign -d $pid $eid'\n";
	open(WANFP,"wanassign -d $pid $eid 2>&1 | tee wanassign.log |") or
	    die("*** $0:\n".
		"    Failed to start wanassign: $!\n");

	printdb "Reading wanassign results.\n";
	while (<WANFP>) {
	    chop;
	    if ($_ =~ /(\S+) mapsto (\S+)/) {
1007
		$v2vmap{$1} = $2;
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
		printdb "  $1 $2\n";
	    }
	    if ($_ =~ /^Success/) {
		$success = 1;
	    }
	    # Skip other output. Usually its debugging output.
	}
	close(WANFP) or
	    die("*** $0:\n".
		"    wanassign: " . $? ? "exited with status: $?.\n" :
		                         "error closing pipe: $!\n");

	if (!$success) {
	    die("*** $0:\n".
		"    wanassign could not find a solution!\n");
	}
1024
1025
1026
1027
1028
1029
1030
	foreach my $virtual (keys(%v2vmap)) {
	    my $physical = $v2vmap{$virtual};
	    my $jailflag;

	    TBIsNodeVirtual($physical, \$jailflag);
	    $jailed{$virtual}  = $jailflag;
	}
1031
1032
1033
1034
	TBDebugTimeStamp("wanassign finished");
    }
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1035
#
1036
1037
1038
1039
# VIRTNODES HACK: Local virtnodes have to be mapped now. This is a little
# hokey in that the virtnodes just need to be allocated from the pool that
# is on the real node. We know they are free, but we should go through
# nalloc anyway.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1040
#
1041
1042
1043
foreach my $pnode (keys(%virtnodes)) {
    my @vlist = @{$virtnodes{$pnode}};
    my @plist = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1044
1045

    #
1046
1047
1048
1049
1050
1051
    # Run avail to get the list of virtnodes on the phys node. We already
    # know there are enough, since assign knows that.
    #
    my $num  = @vlist;
    
    open(AVAIL,"$TBROOT/sbin/avail virtonly=$pnode rand limit=$num |")
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1052
1053
1054
1055
1056
1057
1058
1059
1060
	or die("*** $0:\n".
	       "    avail failed\n");

    while (<AVAIL>) {
	next
	    if (! /^\|/);
	next
	    if (/node_id/);
	
1061
1062
	my ($nodeid) = /^\|([-a-zA-Z0-9]+)\s*\|(\w+)\s*\|(\w+)\s*\|$/;
	push(@plist, $nodeid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1063
1064
1065
    }
    close(AVAIL);

1066
    if (scalar(@vlist) != scalar(@plist)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1067
	print STDERR "*** $0:\n".
1068
	    "Could not map some virtual nodes on $pnode\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1069
1070
1071
1072
1073
	exit(2);
    }

    #
    # Try to allocate. Note, if this fails we are done for. Okay for now
1074
    # since it is never the case that it should fail!
1075
    #
1076
1077
    print "Reserving @plist ...\n";
    if (system("nalloc $pid $eid @plist")) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1078
	die("*** $0:\n".
1079
	    "Failed to reserve @plist (on $pnode)\n");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1080
    }
1081
1082
1083
    while (@plist) {
	my $physical = pop(@plist);
	my $virtual  = pop(@vlist);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1084

1085
1086
	$v2vmap{$virtual}  = $physical;
	printdb "  Mapping $virtual to $physical on $pnode\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1087

1088
1089
	my $jailflag;
	my $phys_nodeid;
1090

1091
1092
1093
	TBIsNodeVirtual($physical, \$jailflag);
	
	$jailed{$virtual}  = $jailflag;
1094
1095
    }
}
1096

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1097
TBExptSetPortRange();
1098

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
######################################################################
# Step 3 - Convert to vlans, delays, and portmap
# 
# Here we convert the plinks into vlans, delays, and portmap.  We
# convert them first into internal datastructure.  After Step 4
# when we do some port swapping we'll upload the modified versions
# of these structures into the database.
#
# delays is indexed by an internal ID and contains:
#  [pnode, int0, int1, vname, delay, bandwidth, lossrate]
# portmap is indexed by <virtual node>:<virtual port> and contains
#  the physical port.
#
# vlan ids
#  vlan ids are increasing integers in the case of node<->delay connections.
#  In the case of actual LANs either of real node or of delay nodes
#  they are indexed by virtual lan name.
# delay ids
#  delay ids are increasing integers.  We could have used a list of
# delays just as well.  Having it as an array may prove useful for
# future changes however.
######################################################################

$delayid = 0;

printdb "Interpreting results.\n";
1125
TBDebugTimeStamp("interpreting started");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1126
foreach $plink (keys(%plinks)) {
Shashi Guruprasad's avatar
Shashi Guruprasad committed
1127

1128
    # trivial links do not have physical links
Shashi Guruprasad's avatar
Shashi Guruprasad committed
1129
1130
1131
1132
    if( scalar(@{$plinks{$plink}}) == 0 ) {
      next;
    }
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1133
1134
1135
1136
    ($nodeportA,$nodeportB) = @{$plinks{$plink}};
    ($nodeA,$portA) = split(":",$nodeportA);
    ($nodeB,$portB) = split(":",$nodeportB);
    printdb "plink $plink - $nodeportA $nodeportB\n";
1137
    if (($lan,$virtA,$virtC) = ($plink =~ m|^linksdelaysrc/(.+)/(.+),(.+)$|)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1138
1139
1140
1141
	# Node has a single entry in lan.
	# Node is nodeportA
	# Delay node is nodeportB
	# Other end of delay node will be given by plink
1142
1143
	#   linksdelaydst/lan/virtC,virtA where nodeportA will be the other 
	#   node in the virtual LAN and nodeportB will be the other end of the
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1144
	#   delay node.
1145
1146
	($nodeportC,$nodeportD) =
	    @{$plinks{"linksdelaydst/$lan/$virtC,$virtA"}};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1147
1148
1149
1150
1151
1152
1153
	($nodeC,$portC) = split(":",$nodeportC);
	($nodeD,$portD) = split(":",$nodeportD);
	printdb "LINK delay: other end = $nodeportC $nodeportD\n";

	# assert nodeB == nodeD

	printdb "  VLANS:\n";
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
	AddVlan("link", $lan, $nodeportA, $nodeportB);
	AddVlan("link", $lan, $nodeportC, $nodeportD);
	
	my ($member0,$delay,$bandwidth,$lossrate,
	    $member1,$rdelay,$rbandwidth,$rlossrate) = @{$delaylinks{$plink}};
	
	$nodedelays{$delayid++} = [$nodeB,$portB,$portD,$lan,
			       $member0,$delay,$bandwidth,$lossrate,
			       $member1,$rdelay,$rbandwidth,$rlossrate];
	printdb "  Delay: \[$nodeB,$portB,$portD,$lan," .
	    "$delay,$bandwidth,$lossrate,$rdelay,$rbandwidth," .
	    "$rlossrate,$nodeportA,$nodeportC\]\n";

	#
	# Setup portmap using virt members in plink name.
	#
	$portmap{$virtA} = $portA;
	$portmap{$virtC} = $portC;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1172
	printdb "  Portmap:\n";
1173
1174
1175
1176
	printdb "    $virtA = $portA\n";
	printdb "    $virtC = $portC\n";
    }
    elsif (($lan,$virtA) = ($plink =~ m|^linkdelaysrc/([^/]+)/(.+)$|)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1177
1178
1179
1180
1181
	# Node may have multiple entries in lan.
	# Delay node is nodeB and portB.
	# Other end of delay node will be given by plink
	#  linkdelaydst/lan/node where nodeportA will the LAN node and
	#  nodeportB will be the other end of the delay node.
1182
1183
	
	($nodeportC,$nodeportD) = @{$plinks{"linkdelaydst/$lan/$virtA"}};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1184
1185
1186
	($nodeC,$portC) = split(":",$nodeportC);
	($nodeD,$portD) = split(":",$nodeportD);
	printdb "LAN delay src: other end = $nodeportC $nodeportD\n";
1187

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1188
	printdb "  VLANS:\n";
1189
1190
	AddVlan("link", $lan, $nodeportA, $nodeportB);
	AddVlan("lan",  $lan, $nodeportD);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1191
	
1192
1193
1194
1195
1196
1197
1198
	my ($member0,$delay,$bandwidth,$loss,
	    $member1,$rdelay,$rbandwidth,$rloss) = @{$delaylinks{$plink}};
	
	$nodedelays{$delayid++} = [$nodeB,$portB,$portD,$lan,
				   $member0,$delay,$bandwidth,$loss,
				   $member1,$rdelay,$rbandwidth,$rloss];
	printdb "  Delays: \[$nodeB,$portB,$portD,$lan," .
Christopher Alfeld's avatar
Christopher Alfeld committed
1199
	    "$delay,$bandwidth,$loss,$rdelay,$rbandwidth,$rloss," .
1200
	    "$nodeportA,$nodeportC\]\n";
Shashi Guruprasad's avatar
Shashi Guruprasad committed
1201

1202
	$portmap{$virtA} = $portA;
Shashi Guruprasad's avatar
Shashi Guruprasad committed
1203
	printdb "  Portmap:\n";
1204
1205
1206
1207
1208
1209
1210
1211
1212
	printdb "    $virtA = $portA\n";
    }
    elsif (($lan,$virtA,$virtB) = ($plink =~ m|^linksimple/(.+)/(.+),(.+)$|)) {
	#
	# nodeportA and nodeportB are the only two nodes in the LAN.
	# If the link is delayed, its with endpoint delays, not a delay node.
	#
	printdb "  Link:";
	AddVlan("link", $lan, $nodeportA, $nodeportB);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1213
	
1214
1215
1216
1217
	if ($delaylinks{$plink}) {
	    my ($member0,$delay,$bandwidth,$loss,
		$member1,$rdelay,$rbandwidth,$rloss) =
		    @{$delaylinks{$plink}};
Shashi Guruprasad's avatar
Shashi Guruprasad committed
1218

1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
	    #
	    # Two entries, one for each side of the duplex link.
	    #
	    $linkdelays{$delayid++} = [$nodeA,$portA,$lan,$member0,
				       $delay,$bandwidth,$loss,
				       undef,undef,undef,0];
	    
	    $linkdelays{$delayid++} = [$nodeB,$portB,$lan,$member1,
				       $rdelay,$rbandwidth,$rloss,
				       undef,undef,undef,0];
	    
	    printdb "  LinkDelay: \[$nodeA,$portA,$nodeB,$portB," .
		"$lan,$delay,$bandwidth,$loss,$rdelay,$rbandwidth,$rloss\]\n";
Shashi Guruprasad's avatar
Shashi Guruprasad committed
1232
	}
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243

	#
	# Setup portmap using virt members in plink name.
	#
	$portmap{$virtA} = $portA;
	$portmap{$virtB} = $portB;
	printdb "  Portmap:\n";
	printdb "    $virtA = $portA\n";
	printdb "    $virtB = $portB\n";
    }
    elsif (($lan,$virtA) = ($plink =~ m|^linklan/([^/]+)/(.+)$|)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1244
1245
1246
1247
	# node may be the LAN multiple times.
	# nodeportA is the node.
	# nodeportB is the LAN
	# No delays
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
	printdb "  LAN:";
	AddVlan("lan", $lan, $nodeportA);
	
	if ($delaylinks{$plink}) {
	    my ($member0,$delay,$bandwidth,$loss,
		$member1,$rdelay,$rbandwidth,$rloss) =
		    @{$delaylinks{$plink}};

	    #
	    # One entry, comprising each side of the link to lan.
	    #
	    $linkdelays{$delayid++} = [$nodeA,$portA,$lan,$member0,
				       $delay,$bandwidth,$loss,
				       $rdelay,$rbandwidth,$rloss,1];
	    
	    printdb "  LinkDelay: \[$nodeA,$portA," .
		"$lan,$delay,$bandwidth,$loss,$rdelay,$rbandwidth,$rloss\]\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1265
1266
	}

1267
	$portmap{$virtA} = $portA;
Shashi Guruprasad's avatar
Shashi Guruprasad committed
1268
	printdb "  Portmap:\n";
1269
1270
1271
1272
1273
1274
1275
1276
	printdb "    $virtA = $portA\n";
    }
    elsif ($plink =~ m|^linkdelaydst/([^/]+)/(.+)$| ||
	   $plink =~ m|^linksdelaydst/(.+)/(.+),(.+)$|) {
	next;
    }
    else {
	warn("Bad plink: $plink\n");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1277
1278
    }
}
1279
TBDebugTimeStamp("interpreting finished");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1280
1281
1282
1283
1284
1285
1286

######################################################################
# Step 4 - Upload to DB
#
# Nothing fancy.
######################################################################
printdb "Uploading to DB\n";
1287
TBDebugTimeStamp("uploading started");
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304

# Write the vlans to the DB.
UploadVlans();

#
# Clean the virt_agents table.
# Yuck. There should be an agents table instead of munging virt_agents.
#
my $virt_agents =
    DBQueryFatal("select vname,vnode from virt_agents as v ".
		 "left join event_objecttypes as e on e.idx=v.objecttype ".
		 "where e.type='LINK' and pid='$pid' and eid='$eid'");

while (my ($vname,$vnode) = $virt_agents->fetchrow_array()) {
    DBQueryFatal("delete from virt_agents ".
		 "where pid='$pid' and eid='$eid' and ".
		 " vname='$vname' and vnode='$vnode'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1305
}
1306

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1307
1308
my $pipeid = 100;

1309
foreach $delayid (keys(%nodedelays)) {
Christopher Alfeld's avatar
Christopher Alfeld committed