rspec2genilib.in 23.2 KB
Newer Older
1 2 3
#!/usr/bin/perl -w

#
4
# Copyright (c) 2000-2018 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
#
use strict;
use English;
use Getopt::Std;
use File::Temp qw(tempfile :mktemp :POSIX );
use POSIX qw(:signal_h);
use POSIX ":sys_wait_h";
use File::stat;
use Data::Dumper;

#
# Convert rspec to geni lib.
#
sub usage()
{
Leigh Stoller's avatar
Leigh Stoller committed
39 40
    print STDERR "Usage: rspec2genilib ".
	"[-o filename] [[-r] -s rspecfile] rspec\n";
41
    print STDERR "Options:\n";
42 43 44
    print STDERR "  -d       - Turn on debugging\n";
    print STDERR "  -o file  - Specify output file for geni-lib\n";
    print STDERR "  -s file  - Specify output file for post geni-lib rspec\n";
45
    print STDERR "  -r       - Regression test; run geni-lib, compare rspecs\n";
Leigh Stoller's avatar
Leigh Stoller committed
46
    print STDERR "  -t       - Do not add stub docstring (for regression)\n";
47
    print STDERR "  -p       - Permissive mode, ignore unsupported stuff\n";
48
    print STDERR "  -v       - Verbose mode, print extra errors\n";
49 50
    exit(-1);
}
51
my $optlist    = "do:rs:tpv";
52
my $debug      = 0;
Leigh Stoller's avatar
Leigh Stoller committed
53
my $regress    = 0;
Leigh Stoller's avatar
Leigh Stoller committed
54
my $nodocstr   = 0;
55
my $permissive = 0;
56
my $verbose    = 0;
57
my $ofile;
Leigh Stoller's avatar
Leigh Stoller committed
58
my $rfile;
59 60 61 62

#
# Configure variables
#
Leigh Stoller's avatar
Leigh Stoller committed
63 64 65 66
my $TB         = "@prefix@";
my $TBOPS      = "@TBOPSEMAIL@";
my $XMLLINT    = "/usr/local/bin/xmllint";
my $RUNGENILIB = "$TB/bin/rungenilib";
67 68 69 70 71 72

# Locals
my $rspecfile;

# Protos
sub fatal($);
Leigh Stoller's avatar
Leigh Stoller committed
73
sub GetTextOrFail($$);
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

#
# Turn off line buffering on output
#
$| = 1;

#
# Untaint the path
# 
$ENV{'PATH'} = "$TB/bin:$TB/sbin:/bin:/usr/bin:/sbin:/usr/sbin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

if ($UID == 0) {
    die("Please do not run this as root!");
}

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
Leigh Stoller's avatar
Leigh Stoller committed
94
use emutil;
95
use GeniXML;
Leigh Stoller's avatar
Leigh Stoller committed
96 97
use GeniHRN;
use APT_Rspec;
98 99 100 101 102 103 104 105 106 107 108 109

#
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
110
if (defined($options{"t"})) {
Leigh Stoller's avatar
Leigh Stoller committed
111
    $nodocstr = 1;
112
}
113 114 115
if (defined($options{"o"})) {
    $ofile = $options{"o"};
}
116 117 118
if (defined($options{"p"})) {
    $permissive = 1;
}
119 120 121
if (defined($options{"v"})) {
    $verbose = 1;
}
Leigh Stoller's avatar
Leigh Stoller committed
122
if (defined($options{"r"})) {
Leigh Stoller's avatar
Leigh Stoller committed
123 124
    $regress  = 1;
    $nodocstr = 1;
Leigh Stoller's avatar
Leigh Stoller committed
125 126 127 128
    if (defined($options{"s"})) {
	$rfile = $options{"s"};
    }
}
129 130 131 132 133 134
if (@ARGV != 1) {
    usage();
}
$rspecfile = $ARGV[0];

#
Leigh Stoller's avatar
Leigh Stoller committed
135
# Must taint check.
136 137 138 139 140 141 142
#
if ($rspecfile =~ /^([-\w\/\.]+)$/) {
    $rspecfile = $1;
}
else {
    die("Bad data in argument: $rspecfile.");
}
Leigh Stoller's avatar
Leigh Stoller committed
143

144 145 146
my $xmlerrors = `$XMLLINT --noout $rspecfile 2>&1`;
if ($?) {
    print STDERR $xmlerrors;
147
    fatal("rspec is not well formed");    
148
}
149
my $rspec = APT_Rspec->new($rspecfile, $permissive, $verbose);
Leigh Stoller's avatar
Leigh Stoller committed
150 151
fatal("Could not create rspec object")
    if (!defined($rspec));
152 153

#
Leigh Stoller's avatar
Leigh Stoller committed
154
# Generate statements for each node.
155
#
Leigh Stoller's avatar
Leigh Stoller committed
156
sub GenerateNodeStatements($)
157
{
Leigh Stoller's avatar
Leigh Stoller committed
158
    my ($rspec) = @_;
159

160
    foreach my $node (@{$rspec->nodelist()}) {
Leigh Stoller's avatar
Leigh Stoller committed
161 162 163
	my $client_id = $node->client_id();
	my $ntag      = $node->tag();
	my $ntype     = $node->type();
164
	
Leigh Stoller's avatar
Leigh Stoller committed
165 166 167
	#
	# Create the nodes.
	#
168
	if ($ntype eq "emulab-xen" || $ntype eq "default-vm") {
Leigh Stoller's avatar
Leigh Stoller committed
169
	    $node->addStatement("$ntag = request.XenVM('$client_id')");
170 171 172 173 174 175 176 177

	    #
	    # This is the only time we need to spit this out, since
	    # the default is False.
	    #
	    if (defined($node->{'exclusive'}) && $node->{'exclusive'}) {
		$node->addTagStatement("exclusive = True");
	    }
178
	    
Leigh Stoller's avatar
Leigh Stoller committed
179 180
	    if (defined($node->{'xen_settings'})) {
		my $settings = $node->{'xen_settings'};
181 182

		foreach my $setting (sort(keys(%{$settings}))) {
Leigh Stoller's avatar
Leigh Stoller committed
183 184 185 186 187 188 189 190 191 192
		    my $value = $settings->{$setting};
		    if ($setting eq "ram") {
			$node->addTagStatement("ram = $value");
		    }
		    elsif ($setting eq "cores") {
			$node->addTagStatement("cores = $value");
		    }
		    elsif ($setting eq "disk") {
			$node->addTagStatement("disk = $value");
		    }
193 194
		}
	    }
Leigh Stoller's avatar
Leigh Stoller committed
195 196 197 198 199 200 201 202
	    if (defined($node->{'xen_ptype'})) {
		my $ptype = $node->{'xen_ptype'};
		$node->addTagStatement("xen_ptype = '$ptype'");
	    }
	    if (defined($node->{'instantiate_on'})) {
		my $vhost = $node->{'instantiate_on'};
		$node->addTagStatement("InstantiateOn('$vhost')");
	    }
203
	}
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
	elsif ($ntype eq "emulab-docker") {
	    $node->addStatement("$ntag = request.DockerContainer('$client_id')");

	    #
	    # This is the only time we need to spit this out, since
	    # the default is False.
	    #
	    if (defined($node->{'exclusive'}) && $node->{'exclusive'}) {
		$node->addTagStatement("exclusive = True");
	    }
	    
	    if (defined($node->{'docker_settings'})) {
		my $settings = $node->{'docker_settings'};

		foreach my $setting (sort(keys(%{$settings}))) {
		    my $value = $settings->{$setting};
		    if ($setting eq "ram") {
			$node->addTagStatement("ram = $value");
		    }
		    elsif ($setting eq "cores") {
			$node->addTagStatement("cores = $value");
		    }
		    elsif ($setting eq "extimage") {
			$node->addTagStatement("docker_extimage = $value");
		    }
		    elsif ($setting eq "dockerfile") {
			$node->addTagStatement("docker_dockerfile = $value");
		    }
		}
	    }
	    if (defined($node->{'docker_ptype'})) {
		my $ptype = $node->{'docker_ptype'};
		$node->addTagStatement("docker_ptype = '$ptype'");
	    }
	    if (defined($node->{'instantiate_on'})) {
		my $vhost = $node->{'instantiate_on'};
		$node->addTagStatement("InstantiateOn('$vhost')");
	    }
	}
Leigh Stoller's avatar
Leigh Stoller committed
243 244 245 246 247 248 249 250 251 252 253 254 255 256
	elsif ($ntype eq "delay") {
	    #
	    # Bridges are also special, see comment above for blockstore.
	    #
	    my ($iface0, $iface1) = values(%{$node->{'ifaces'}});
	    my (undef,$if0) = split(":", $iface0->{'client_id'});
	    my (undef,$if1) = split(":", $iface1->{'client_id'});

	    $node->addStatement(
		"$ntag = request.Bridge('$client_id', '$if0', '$if1')");

	    #
	    # And the pipes. Just two of them.
	    #
257 258 259
	    foreach my $k (sort(keys(%{$node->pipes()}))) {
		my $p = $node->pipes()->{$k};
		
260
		my $pname = ($p->{'iface_id'} eq $if0 ? "pipe0" : "pipe1");
Leigh Stoller's avatar
Leigh Stoller committed
261 262 263 264 265 266 267 268

		$node->addTagStatement("${pname}.bandwidth = ". $p->capacity())
		    if (defined($p->capacity()));
		$node->addTagStatement("${pname}.latency = " . $p->latency())
		    if (defined($p->latency()));
		$node->addTagStatement("${pname}.lossrate = " . $p->lossrate())
		    if (defined($p->lossrate()));
	    }
269
	}
270 271 272 273 274 275 276 277 278 279
	elsif ($ntype eq "firewall") {
	    my $fwstyle = $node->firewall_style();
	    
	    $node->addStatement(
		"$ntag = request.ExperimentFirewall('$client_id','$fwstyle')");

	    foreach my $fwrule (@{$node->firewall_rules()}) {
		$node->addTagStatement("addRule('$fwrule')");
	    }
	}
Leigh Stoller's avatar
Leigh Stoller committed
280 281 282 283 284 285 286
	elsif ($ntype eq "emulab-blockstore") {
	    # attributes.
	    my $bstore = $node->{'blockstores'}->{$client_id};
	    my $mount  = ($bstore->{'mount'} ?
			  "'" . $bstore->{'mount'} . "'" : "None");
	    # The node and the blockstore are the same.
	    $ntag = $node->{'tag'} = $bstore->{'tag'};
287
	    
288
	    #
Leigh Stoller's avatar
Leigh Stoller committed
289 290 291 292 293
	    # Blockstores are special. We want to use the same iface names
	    # from the rspec, not the internal names that geni-lib uses,
	    # This ensures that the rspec->geni-lib->rspec ... path uses
	    # consistent naming. And we know that the blockstore has only one
	    # interface, so that makes it easier.
294
	    #
Leigh Stoller's avatar
Leigh Stoller committed
295
	    my ($iface) = values(%{$node->{'ifaces'}});
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
	    my $iface_id = $iface->{'client_id'};

	    #
	    # geni-lib is going to name the interfaces as node_id:iface_id
	    # so we have to careful to strip existing node_id from the id
	    # in case the rspec came from a geni-lib script. But geni-lib
	    # will not prepend the node_id if it is already in : format,
	    # so if the user named it whacky:iface_id, we are going to
	    # use that.
	    #
	    if ($iface_id =~ /^([^:]*):(.*)$/) {
		if ($1 eq $client_id) {
		    $iface_id = $2;
		}
	    }
311

Leigh Stoller's avatar
Leigh Stoller committed
312
	    $node->addStatement(
313 314
		"$ntag = request.RemoteBlockstore('$client_id', ".
		"$mount, '$iface_id')");
315
	}
Leigh Stoller's avatar
Leigh Stoller committed
316 317
	else {
	    $node->addStatement("$ntag = request.RawPC('$client_id')");
318 319
	}

Leigh Stoller's avatar
Leigh Stoller committed
320 321 322 323 324 325
	#
	# Attributes and flags.
	#
	if (defined($node->{'component_id'})) {
	    my $component_id = $node->{'component_id'};
	    $node->addTagStatement("component_id = '$component_id'");
326
	}
Leigh Stoller's avatar
Leigh Stoller committed
327 328 329
	if (defined($node->{'component_manager_id'})) {
	    my $manager_id = $node->{'component_manager_id'};
	    $node->addTagStatement("component_manager_id = '$manager_id'");
330
	}
Leigh Stoller's avatar
Leigh Stoller committed
331 332
	if ($node->{'routable_control_ip'}) {
	    $node->addTagStatement("routable_control_ip = True");
333
	}
Leigh Stoller's avatar
Leigh Stoller committed
334 335 336
	if (defined($node->{'hardware_type'})) {
	    my $htype = $node->{'hardware_type'};
	    $node->addTagStatement("hardware_type = '$htype'");
337
	}
Leigh Stoller's avatar
Leigh Stoller committed
338 339 340
	if (defined($node->{'disk_image'})) {
	    my $name = $node->{'disk_image'};
	    $node->addTagStatement("disk_image = '$name'");
Leigh Stoller's avatar
Leigh Stoller committed
341
	}
342 343 344 345
	if (defined($node->{'adb_target'})) {
	    my $target_id = $node->{'adb_target'};
	    $node->addTagStatement("adb_target = '$target_id'");
	}
Leigh Stoller's avatar
Leigh Stoller committed
346 347 348 349
	if (defined($node->{'jacks_site'})) {
	    my $site = $node->{'jacks_site'};
	    $node->addTagStatement("Site('$site')");
	}
350 351 352 353
	if (defined($node->{'failure_action'})) {
	    my $action = $node->{'failure_action'};
	    $node->addTagStatement("setFailureAction('$action')");
	}
Leigh Stoller's avatar
Leigh Stoller committed
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

	#
	# Services.
	#
	foreach my $service (@{ $node->{'services'} }) {
	    my $type = $service->{'type'};

	    SWITCH: for (lc($type)) {
		/^install$/i && do {
		    my $url  =  $service->{'url'};
		    my $path =  $service->{'path'};
		    $node->addTagStatement(
			"addService(pg.Install('$url','$path'))");
		    last SWITCH;
		};
		/^execute$/i && do {
		    my $shell = $service->{'shell'};
		    my $cmd   = $service->{'cmd'};
372
		    $cmd =~ s/\'/\\'/g;
Leigh Stoller's avatar
Leigh Stoller committed
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
		    $node->addTagStatement(
			"addService(pg.Execute('$shell','$cmd'))");
		    last SWITCH;
		};
		/^program-agent$/i && do {
		    my $vname       = $service->{"name"};
		    my $command     = $service->{"command"};
		    my $directory   = $service->{"directory"};
		    my $onexpstart  = $service->{"onexpstart"} ? "True":"False";
		    if (defined($directory) && $directory ne "") {
			$directory = "'" . $directory . "'";
		    }
		    else {
			$directory = "None";
		    }
388 389
		    $command =~ s/\\/\\\\/g;
		    $command =~ s/\'/\\'/g;
Leigh Stoller's avatar
Leigh Stoller committed
390 391
		    $node->addTagStatement(
			"addService(emulab.ProgramAgent('$vname', ".
392
			"'$command', $directory, $onexpstart))");
Leigh Stoller's avatar
Leigh Stoller committed
393 394
		    last SWITCH;
		};
395 396
	    }
	}
397
	#
Leigh Stoller's avatar
Leigh Stoller committed
398
	# Desires.
399
	#
400
	foreach my $desire (sort(keys(%{ $node->{'desires'} }))) {
Leigh Stoller's avatar
Leigh Stoller committed
401 402
	    my $weight = $node->{'desires'}->{$desire};
	    $node->addTagStatement("Desire('$desire','$weight')");
403
	}
Leigh Stoller's avatar
Leigh Stoller committed
404
	
405 406 407 408 409 410 411 412
	#
	# Node Attributes.
	#
	foreach my $key (sort(keys(%{ $node->attributes() }))) {
	    my $value = $node->attributes()->{$key};
	    $node->addTagStatement("Attribute('$key','$value')");
	}
	
413
	#
Leigh Stoller's avatar
Leigh Stoller committed
414
	# Interfaces.
415
	#
416
	foreach my $iface (@{$node->ifacelist()}) {
417 418 419 420 421
	    my $iface_id     = $iface->{'client_id'};
	    my $itag         = $iface->{'tag'};
	    my $ip           = $iface->{'ip'};
	    my $mask         = $iface->{'mask'};
	    my $component_id = $iface->{'component_id'};
Leigh Stoller's avatar
Leigh Stoller committed
422 423 424 425 426

	    #
	    # geni-lib is going to name the interfaces as node_id:iface_id
	    # so we have to careful to strip existing node_id from the id
	    # in case the rspec came from a geni-lib script. But geni-lib
427 428 429
	    # will not prepend the node_id if it is already in : format,
	    # so if the user named it whacky:iface_id, we are going to
	    # use that.
Leigh Stoller's avatar
Leigh Stoller committed
430
	    #
431 432 433 434 435
	    if ($iface_id =~ /^([^:]*):(.*)$/) {
		if ($1 eq $client_id) {
		    $iface_id = $2;
		}
	    }
Leigh Stoller's avatar
Leigh Stoller committed
436 437 438 439 440 441 442
	    my $addr = ($ip && $mask ? "pg.IPv4Address('$ip','$mask')" : undef);

	    #
	    # Again, bridges and blockstores are special. We have to find
	    # the internally created interface, not add another one.
	    #
	    if ($ntype eq "delay") {
443 444 445 446 447 448
		my ($iface0, $iface1) = values(%{$node->{'ifaces'}});
		my (undef,$if0) = split(":", $iface0->{'client_id'});
		my (undef,$if1) = split(":", $iface1->{'client_id'});
		my $iname = ($iface_id eq $if0 ? "iface0" : "iface1");
		
		$node->addStatement("$itag = ${ntag}.${iname}");
Leigh Stoller's avatar
Leigh Stoller committed
449 450 451 452 453 454 455 456 457 458
		if ($addr) {
		    $node->addStatement("${itag}.addAddress($addr)");
		}
	    }
	    elsif ($ntype eq "emulab-blockstore") {
		$node->addStatement("$itag = ${ntag}.interface");
	    }
	    else {
		$node->addStatement("$itag = ${ntag}.addInterface('$iface_id'" .
				    (defined($addr) ? ", $addr" : "") . ")");
459 460 461 462
		if (defined($component_id)) {
		    $node->addStatement("${itag}.component_id = ".
					"'$component_id'");
		}
Leigh Stoller's avatar
Leigh Stoller committed
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
	    }
	}
	foreach my $id (sort(keys(%{$node->{'blockstores'}}))) {
	    my $blockstore = $node->{'blockstores'}->{$id};
	    my $bsname     = $blockstore->{'name'};
	    my $btag       = $blockstore->{'tag'};
	    my $mount      = ($blockstore->{'mount'} ?
			      "'" . $blockstore->{'mount'} . "'" : "None");

	    # Create local blockstore on node.
	    if ($ntype ne "emulab-blockstore") {
		$node->addStatement(
		    "$btag = ${ntag}.Blockstore('$bsname', $mount)");
	    }
	    # Now the attributes.
	    my $readonly  = $blockstore->{'readonly'};
	    my $size      = $blockstore->{'size'};
	    my $placement = $blockstore->{'placement'};
481
	    my $rwclone   = $blockstore->{'rwclone'};
Leigh Stoller's avatar
Leigh Stoller committed
482 483 484 485 486 487 488 489
	    my $dataset   = $blockstore->{'dataset'};

	    if (defined($readonly) && $readonly) {
		$node->addStatement("${btag}.readonly = True");
	    }
	    if (defined($size)) {
		$node->addStatement("${btag}.size = '$size'");
	    }
490 491
	    # Do not not spit out default.
	    if (defined($placement) && $placement ne "any") {
Leigh Stoller's avatar
Leigh Stoller committed
492 493 494 495
		$node->addStatement("${btag}.placement = '$placement'");
	    }
	    if (defined($dataset)) {
		$node->addStatement("${btag}.dataset = '$dataset'");
496
	    }
497 498 499 500
	    # Do not not spit out default (false).
	    if (defined($rwclone) && $rwclone) {
		$node->addStatement("${btag}.rwclone = True");
	    }
501 502 503
	}
    }
}
Leigh Stoller's avatar
Leigh Stoller committed
504 505 506
sub SpitNodeStatements($$)
{
    my ($rspec, $where) = @_;
507

508
    foreach my $node (@{$rspec->nodelist()}) {
Leigh Stoller's avatar
Leigh Stoller committed
509 510 511 512 513 514
	my $client_id = $node->client_id();
	print $where "# Node $client_id\n";
	foreach my $statement (@{$node->statements()}) {
	    print $where "$statement\n";
	}
	print $where "\n";
515 516 517 518
    }
}

#
Leigh Stoller's avatar
Leigh Stoller committed
519
# Generate statements for each node.
520
#
Leigh Stoller's avatar
Leigh Stoller committed
521 522 523 524
sub GenerateLinkStatements($)
{
    my ($rspec) = @_;
    
525
    foreach my $link (@{$rspec->linklist()}) {
Leigh Stoller's avatar
Leigh Stoller committed
526 527 528 529 530
	my $client_id = $link->client_id();
	my $ltag      = $link->tag();
	my $ltype     = $link->type();

	if (defined($ltype)) {
531
	    if ($ltype eq "lan") {
Leigh Stoller's avatar
Leigh Stoller committed
532 533 534 535 536 537 538
		$link->addStatement("$ltag = request.LAN('$client_id')");
	    }
	    elsif ($ltype eq "vlan" || $ltype eq "lan") {
		$link->addStatement(
		    "$ltag = request.Link('$client_id', 'vlan')");
	    }
	    elsif ($ltype eq "egre-tunnel") {
539
		$link->addStatement("$ltag = request.L2GRE('$client_id')");
Leigh Stoller's avatar
Leigh Stoller committed
540 541
	    }
	    elsif ($ltype eq "gre-tunnel") {
542
		$link->addStatement("$ltag = request.L3GRE('$client_id')");
Leigh Stoller's avatar
Leigh Stoller committed
543 544 545 546 547 548 549 550
	    }
	    else {
		fatal("Unknown link type $ltype for $client_id");
	    }
	}
	else {
	    $link->addStatement("$ltag = request.Link('$client_id')");
	}
551
	#
Leigh Stoller's avatar
Leigh Stoller committed
552
	# Link properties
553
	#
Leigh Stoller's avatar
Leigh Stoller committed
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
	if (defined($link->{'component_id'})) {
	    my $id = $link->{'component_id'};
	    $link->addTagStatement("component_id = '$id'");
	}
	if (defined($link->{'component_manager_id'})) {
	    my $id = $link->{'component_manager_id'};
	    $link->addTagStatement("component_manager_id = '$id'");
	}
	if (defined($link->{'openflow_controller'})) {
	    my $host = $link->{'openflow_controller'}->{'host'};
	    my $port = $link->{'openflow_controller'}->{'port'};
	    $link->addTagStatement(
			     "addChild(emulab.OFController('$host', $port))");
	}
	if (defined($link->{'best_effort'})) {
	    $link->addTagStatement("best_effort = True");
	}
	if (defined($link->{'shared_vlan'})) {
	    my $name = $link->{'shared_vlan'};
	    $link->addTagStatement("connectSharedVlan('$name')");
	}
	if (defined($link->{'force_shaping'})) {
	    $link->addTagStatement("setForceShaping()");
	}
578 579 580
	if (defined($link->{'force_nobwshaping'})) {
	    $link->addTagStatement("setNoBandwidthShaping()");
	}
Leigh Stoller's avatar
Leigh Stoller committed
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
	if (defined($link->{'trivial_ok'})) {
	    $link->addTagStatement("trivial_ok = True");
	}
	if (defined($link->{'vlan_tagging'})) {
	    my $istagged = ($link->{'vlan_tagging'} ? "True" : "False");
	    $link->addTagStatement("vlan_tagging = $istagged");
	}
	if (defined($link->{'link_multiplexing'})) {
	    my $emulated = ($link->{'link_multiplexing'} ? "True" : "False");
	    $link->addTagStatement("link_multiplexing = $emulated");
	}
	if (defined($link->{'interswitch'}) && !$link->{'interswitch'}) {
	    $link->addTagStatement("setNoInterSwitchLinks()");
	}
	if (defined($link->{'protocol'})) {
	    my $protocol = $link->{'protocol'};
	    $link->addTagStatement("protocol = '$protocol'");
	}
	if (defined($link->{'nomac_learning'})) {
	    $link->addTagStatement("disableMACLearning()");
	}
	if (defined($link->{'jacks_site'})) {
	    my $site = $link->{'jacks_site'};
	    $link->addTagStatement("Site('$site')");
	}
	# Managers
	foreach my $urn (@{$link->{'component_managers'}}) {
	    $link->addTagStatement("addComponentManager('$urn')");
	}
610 611
	
	#
Leigh Stoller's avatar
Leigh Stoller committed
612
	# Shaping.
613
	#
614
	foreach my $key (sort(keys(%{$link->properties()}))) {
Leigh Stoller's avatar
Leigh Stoller committed
615 616 617 618 619 620 621 622 623 624 625
	    my $property = $link->{'properties'}->{$key};
	    my $dest     = $property->{'dest'};
	    my $iface    = $rspec->getIface($property->source());

	    foreach my $p ("bandwidth", "latency", "plr") {
		if (defined($property->{$p})) {
		    my $pval = $property->{$p};
		    $iface->addTagStatement("$p = $pval");
		}
	    }
	}
626

627
	foreach my $iface (@{$link->ifacelist()}) {
Leigh Stoller's avatar
Leigh Stoller committed
628 629
	    my $client_id = $iface->{'client_id'};
	    my $itag      = $iface->{'tag'};
630

Leigh Stoller's avatar
Leigh Stoller committed
631 632 633 634
	    foreach my $statement (@{$iface->{'statements'}}) {
		$link->addStatement($statement);
	    }
	    $link->addTagStatement("addInterface($itag)");
635 636
	}
    }
Leigh Stoller's avatar
Leigh Stoller committed
637 638 639 640
}
sub SpitLinkStatements($$)
{
    my ($rspec, $where) = @_;
641

642
    foreach my $link (@{$rspec->linklist()}) {
Leigh Stoller's avatar
Leigh Stoller committed
643 644 645 646
	my $client_id = $link->client_id();
	print $where "# Link $client_id\n";
	foreach my $statement (@{$link->statements()}) {
	    print $where "$statement\n";
647
	}
Leigh Stoller's avatar
Leigh Stoller committed
648
	print $where "\n";
649
    }
Leigh Stoller's avatar
Leigh Stoller committed
650 651 652 653 654 655
}

sub SpitTopLevelStatements($$)
{
    my ($rspec, $where) = @_;

656 657 658
    foreach my $attribute (@{$rspec->toplevel_elements()}) {
	my $name = $attribute->name();
	my $val  = $attribute->value();
Leigh Stoller's avatar
Leigh Stoller committed
659 660 661
	
        SWITCH: for (lc($name)) {
	    /^password$/i && do {
662
		print $where "password = emulab.Password('$val')\n";
Leigh Stoller's avatar
Leigh Stoller committed
663 664 665 666
		print $where "request.addResource(password)\n";
		last SWITCH;
	    };
	    /^routable_pool$/i && do {
667 668 669 670 671
		my $pool = $val;
		my $id    = $pool->client_id();
		my $count = $pool->count();
		my $type  = $pool->type();
		print $where "request.AddressPool('$id', $count, '$type')\n";
Leigh Stoller's avatar
Leigh Stoller committed
672 673 674
		last SWITCH;
	    };
	    /^collocate_factor$/i && do {
675
		print $where "request.setCollocateFactor($val)\n";
Leigh Stoller's avatar
Leigh Stoller committed
676 677 678
		last SWITCH;
	    };
	    /^packing_strategy$/i && do {
679
		print $where "request.setPackingStrategy('$val')\n";
Leigh Stoller's avatar
Leigh Stoller committed
680 681 682
		last SWITCH;
	    };
	    /^routing_style$/i && do {
683
		print $where "request.setRoutingStyle('$val')\n";
Leigh Stoller's avatar
Leigh Stoller committed
684 685 686
		last SWITCH;
	    };
	    /^delay_image$/i && do {
687
		print $where "request.setDelayImage('$val')\n";
Leigh Stoller's avatar
Leigh Stoller committed
688 689 690
		last SWITCH;
	    };
	    fatal("toplevel element $name is not supported");
691 692 693
	}
    }
}
Leigh Stoller's avatar
Leigh Stoller committed
694 695 696 697 698 699 700

sub SpitTour($$)
{
    my ($rspec, $where) = @_;
    my $description  = $rspec->description();
    my $instructions = $rspec->instructions();

Leigh Stoller's avatar
Leigh Stoller committed
701 702 703 704 705
    return
	if ($nodocstr &&
	    ! ((defined($description) && $description->{"text"} ne "") ||
	       (defined($instructions) && $instructions->{"text"} ne "")));

Leigh Stoller's avatar
Leigh Stoller committed
706 707 708 709
    my $docstring = '"""';

    if (defined($description)) {
	$docstring .= $description->{'text'};
710 711
    }
    else {
Leigh Stoller's avatar
Leigh Stoller committed
712 713 714 715 716 717
	if ($nodocstr) {
	    $docstring .= "\n";
	}
	else {
	    $docstring .= "Please give this script a description.";
	}
718
    }
Leigh Stoller's avatar
Leigh Stoller committed
719
    if (defined($instructions)) {
Leigh Stoller's avatar
Leigh Stoller committed
720 721
	my $text = $instructions->{'text'};
	$docstring .= "\n\n" . "Instructions:" . "\n" . $text;
722
    }
Leigh Stoller's avatar
Leigh Stoller committed
723 724 725
    $docstring .= '"""';
    print $where $docstring . "\n\n";
}
726

Leigh Stoller's avatar
Leigh Stoller committed
727 728 729 730 731 732 733 734 735 736 737 738 739 740
sub SpitSteps($$)
{
    my ($rspec, $where) = @_;
    my $steps = $rspec->steps();
    return
	if (!defined($steps) || !scalar(@{$steps}));

    print $where "# Create a Tour object and the steps to it\n";
    print $where "tour = emulab.Tour()\n";
    print $where "tour.useDocstring()\n";
    foreach my $step (@{$steps}) {
	my $type = $step->{"type"};
	my $id   = $step->{"id"};
	my $desc = $step->{"description"};
741
	my $dtype = $step->{"description_type"};
Leigh Stoller's avatar
Leigh Stoller committed
742
	$desc =~ s/\"/\\"/g;
743 744 745 746 747 748
	print $where "tour.addStep(emulab.Tour.Step('$id', ".
	    "\"$desc\", '$type'";
	if (defined($dtype)) {
	    print $where ", '$dtype'";
	}
	print $where "))\n";
Leigh Stoller's avatar
Leigh Stoller committed
749 750 751 752 753
    }
    print $where "request.addTour(tour)\n\n\n";
    
}

Leigh Stoller's avatar
Leigh Stoller committed
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
sub SpitPreamble($)
{
    my ($where) = @_;

    print $where
	"#\n" .
	"# NOTE: This code was machine converted. An actual human would not\n".
	"#       write code like this!\n".
	"#\n\n" .
	"# Import the Portal object.\n" .
	"import geni.portal as portal\n" .
	"# Import the ProtoGENI library.\n" .
	"import geni.rspec.pg as pg\n" .
	"# Import the Emulab specific extensions.\n" .
	"import geni.rspec.emulab as emulab\n" .
	"\n" .
	"# Create a portal object,\n".
	"pc = portal.Context()\n\n".
	"# Create a Request object to start building the RSpec.\n".
	"request = pc.makeRequestRSpec()\n\n";
}

#
# Regression test the geni-lib code by running it and comparing it.
#
sub RunRegression($$$)
{
    my ($rspecfile, $genilibfile, $outrspecfile) = @_;

    my $output = emutil::ExecQuiet("$RUNGENILIB $genilibfile");
    if ($?) {
	print STDERR $output;
	print STDERR "*** $RUNGENILIB failed\n";
	return -1;
    }
    if ($debug) {
	print $output;
    }
    my $rspec1 = eval { APT_Rspec->new($rspecfile) };
    if ($@) {
	print STDERR $@;
	print STDERR "*** Could not parse source rspec into object\n";
	return -1;
    }
    my $rspec2 = eval { APT_Rspec->new($output) };
    if ($@) {
	print STDERR $@;
	print STDERR "*** Could not parse output rspec into object\n";
	return -1;
    }
    if ($rspec1->Compare($rspec2)) {
	print STDERR "*** rspec comparison failed\n";
	return -1;
    }
    if ($outrspecfile) {
	if (open(RS, ">$outrspecfile")) {
	    print RS $output;
	    close(RS);
	}
	else {
	    print STDERR "Could not open outputfile for rspec\n";
	    return -1;
816 817
	}
    }
Leigh Stoller's avatar
Leigh Stoller committed
818
    return 0;
819
}
Leigh Stoller's avatar
Leigh Stoller committed
820
    
821
#
Leigh Stoller's avatar
Leigh Stoller committed
822
# Well no errors, lets generate the geni code for the nodes and links.
823
#
Leigh Stoller's avatar
Leigh Stoller committed
824 825
GenerateNodeStatements($rspec);
GenerateLinkStatements($rspec);
826 827

#
Leigh Stoller's avatar
Leigh Stoller committed
828 829 830 831 832 833 834
# Spew rspec to file.
# 
my ($outfd, $filename) = tempfile("/tmp/rspec2genilibXXXXX", UNLINK => 1);
if (!defined($outfd)) {
    fatal("Could not open temporary file for result rspec");
    return -1;
}
Leigh Stoller's avatar
Leigh Stoller committed
835
SpitTour($rspec, $outfd);
Leigh Stoller's avatar
Leigh Stoller committed
836
SpitPreamble($outfd);
Leigh Stoller's avatar
Leigh Stoller committed
837
SpitSteps($rspec, $outfd);
Leigh Stoller's avatar
Leigh Stoller committed
838 839 840 841 842 843
SpitNodeStatements($rspec, $outfd);
SpitLinkStatements($rspec, $outfd);
SpitTopLevelStatements($rspec, $outfd);
print $outfd "\n";
print $outfd "# Print the generated rspec\n";
print $outfd "pc.printRequestRSpec(request)\n";
844

Leigh Stoller's avatar
Leigh Stoller committed
845 846 847
if ($regress) {
    if (RunRegression($rspecfile, $filename, $rfile)) {
	exit(-1);
848 849
    }
}
850

851
if (defined($ofile)) {
Leigh Stoller's avatar
Leigh Stoller committed
852
    system("/bin/cat $filename > $ofile");
853 854
}
else {
Leigh Stoller's avatar
Leigh Stoller committed
855
    system("/bin/cat $filename");
856
}
857 858 859 860 861 862
exit(0);

sub fatal($) {
    my ($mesg) = $_[0];

    print STDERR "*** $0:\n".
Leigh Stoller's avatar
Leigh Stoller committed
863
	         "*** $mesg\n";
864 865
    exit(-1);
}