prerender.in 15.8 KB
Newer Older
1
#!/usr/bin/perl -wT
2 3 4

#
# EMULAB-COPYRIGHT
5
# Copyright (c) 2000-2003, 2007 University of Utah and the Flux Group.
6 7 8 9 10
# All rights reserved.
#

use English;
use Getopt::Std;
11
use Digest::MD5  qw(md5 md5_hex md5_base64);
12
use Errno qw(ESRCH);
13
use BSD::Resource;
14 15 16 17 18 19

# Need this module to use mktemp (commented out below)
# use File::MkTemp;

# Configure variables
my $TB       = "@prefix@";
20
my $TBOPS    = "@TBOPSEMAIL@";
21 22 23

use lib '@prefix@/lib';
use libdb;
24
use libtestbed;
25 26 27 28 29

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

# Untaint the path
30
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:@prefix@/libexec/vis';
31 32 33 34 35 36 37
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#my $NEATO_CMD = "neato -Gstart=5 -Gepsilon=0.0001 -Goverlap=scale -Gsep=1";
#my $NEATO_CMD = "neato -Gstart=rand -Gepsilon=0.001 -Goverlap=scale -Gpack=true -Gsep=1 -Gmclimit=30";
#my $NEATO_CMD = "neato -Gstart=rand -Gepsilon=0.001 -Goverlap=scale -Gpack=true -Gsep=4 -Gmclimit=30";
#my $NEATO_CMD = "neato -Gstart=rand -Gepsilon=0.005 -Goverlap=scale -Gmaxiter=20000 -Gpack=true";
my $NEATO_CMD = "neato -Gstart=rand -Gepsilon=0.005 -Gmaxiter=20000 -Gpack=true";
38
my $THUMB_CMD = "render -t 160";
39

40
sub mungeName($);
41
sub dprint($);
42 43 44
sub cleanup();
sub fatal($);
sub KillOldRender();
45 46

sub usage {
47 48
    die "Usage:\nprerender [-v] [-r] [-t] [-f] <pid> <eid>\n" .
        "    -f  To stay in foreground (no fork).\n".
49 50
        "    -r  Just remove vis info from DB\n".
        "    -t  Generate (or remove) thumbnail\n";
51 52
}

53
my $optlist = "rvtf";
54 55 56 57 58 59 60

%options = ();

if (!getopts($optlist, \%options)) { usage; }
if (@ARGV != 2) { usage; }

my $debug = 0;
61
my $thumb = 0;
62
my $foreground = 0;
63

64 65
if ( defined($options{"v"}) ) {
    $debug++;
66
    # pass verbosity along to thumbnail render.
67
    $THUMB_CMD .= " -v";
68
}
69

70 71
if ( defined($options{"t"}) ) {
    $thumb++;
72
}
73 74
if ( defined($options{"f"}) ) {
    $foreground++;
75
}
76

77 78
#my ($pid) = $ARGV[0];
#my ($eid) = $ARGV[1];
79 80
my ($pid) = $ARGV[0] =~ /([0-9a-zA-Z_\-]+)/;
my ($eid) = $ARGV[1] =~ /([0-9a-zA-Z_\-]+)/;
81

82 83 84
# for the mungeName function, below.
$mungeUID = 0;

85 86 87 88 89 90 91 92 93 94 95
# For process handling, below.
my $renderpid;

sub handler ($) {
    my ($signame) = @_;

    fatal("Caught a SIG${signame}!");
}

#
# See if another prerender is still running. If so, kill it and update the
96
# pid in the DB. We always kill a running prerender.
97 98 99
#
KillOldRender();

100
### If they specified -r, meaning they just wanted to remove vis info
101 102
### from the DB, we do it and quit.
if (defined($options{"r"})) {
103 104
    DBQueryFatal("DELETE FROM vis_nodes WHERE pid='$pid' AND eid='$eid'");
    exit 0;
105
}
106

107 108 109 110 111
my $exptidx;
if (!TBExptIDX($pid, $eid, \$exptidx)) {
    fatal("No such experiment $pid/$eid!");
}

112
#
113 114
# Okay, go into the background.
#
115 116 117 118 119
if (! $foreground) {
    if (TBBackGround("prerender.output")) {
	#
	# Parent exits normally
	#
120
	print STDOUT "Image rendering proceeding in background mode ...\n";
121 122 123 124 125 126 127 128 129 130 131 132 133
	exit(0);
    }

    #
    # Setup a handler so we can be killed later.
    #
    $SIG{TERM} = \&handler;
    $SIG{INT}  = \&handler;

    #
    # Enter our pid into the DB.
    #
    $renderpid = $PID;
134

135 136 137 138 139 140 141 142
    DBQueryFatal("update experiments set ".
		 "prerender_pid=$renderpid ".
		 "where pid='$pid' and eid='$eid'");
}

# Lower priority since this whole thing consumes CPU like nuts
setpriority(PRIO_PROCESS, 0, 15);

143 144 145 146
### Now, read experiment virtual info from the DB.

# read nodes

147
my $result = DBQueryWarn("SELECT vname,fixed FROM virt_nodes " .
148 149 150 151
			 "WHERE pid='$pid' AND eid='$eid'");

fatal("Failed to get virt_nodes info from DB")
    if (!$result);
152 153 154 155

my $nodes = ();
my $lans  = ();
my $links = ();
156
my $fixednodes = ();
157 158

# all virt_nodes are visualizer nodes of type "node"
159 160
while (my ($vname,$fixed) = $result->fetchrow) {
    dprint "node $vname $fixed\t";
161 162
    $nodes{$vname}{"type"} = "node";
    dprint "added nodes($vname)\t";
163 164 165 166
    if (defined($fixed) && $fixed ne "") {
	# $vname is a subnode of $fixed, so we don't want
	# to viz any vnames named $fixed
	dprint "adding fixed($fixed)\t";
167
	$fixednodes{$vname} = $fixed;
168 169
    }
    dprint "\n";
170 171
}

172 173 174 175 176 177 178 179 180 181 182 183 184 185
# make another pass, removing parent nodes of subnodes
foreach my $fixednode (keys %fixednodes) {
    my $fixedto = $fixednodes{$fixednode};
    if ($fixedto eq $fixednode) {
	# ignore nodes that are fixed in place to themselves
	next;
    }
     # if $fixednode is $fixedto some other node in the topology, don't
     # vis the partent
     if (exists $nodes{$fixedto}) {
	 delete $nodes{$fixedto};
     }
}

186 187
# read lans

188
$result = DBQueryWarn("SELECT vname, member FROM virt_lans " .
189 190
		       "WHERE pid='$pid' AND eid='$eid'");

191 192 193
fatal("Failed to get virt_lans info from DB")
    if (!$result);

194 195
while (my ($vname, $member) = $result->fetchrow) {
    $member =~ s/\:.*//;
196 197 198 199 200 201 202
    dprint "link $vname $member\t";
    if (defined($nodes{$member})) {
	# the node exists, so add the link
	$lans{$vname}{$member} = 1;
	dprint "added lans($vname)($member)\t";
    }
    dprint "\n";
203 204 205 206 207 208 209 210 211 212 213 214
}

# construct links from lans

foreach my $lan (keys %lans) {
    if ((keys %{$lans{$lan}}) == 2) {
	# make a link
	my $a = (keys %{$lans{$lan}})[0];
	my $b = (keys %{$lans{$lan}})[1];
	$links{"$a $b"} = "pair";
    } else {
	# it's a lan; we need a visualizer node for it (of type "lan").
215
	if (exists $nodes{$lan}) { fatal("LAN $lan name collided."); }
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
	$nodes{$lan}{"type"} = "lan";

	# make the appropriate links (from each member to the LAN)
	foreach my $node (keys %{$lans{$lan}}) {
	    $links{"$node $lan"} = "lan";
	}
    }
}

### Write topology to temporary file

# Ideally, we could use mktemp, but module isn't installed.
# my $tempfile = mktemp("prerenderXXXXXX.topfile");

# Could use ($ENV{'TMP'} || "/tmp")  but not sure if that is safe.
my $tempfile =  "/tmp/prerender.$$-" . sprintf("%i",rand(65536));

233 234
open (TOPO, ">$tempfile" ) or
    fatal("Couldn't open temporary file '$tempfile'\n");
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274

# write topology to neato

print TOPO "graph G {\n";

foreach my $node (keys %nodes) {
    print TOPO "{node [shape = box] " . mungeName($node) . "}\n";
}

foreach my $link (keys %links) {
    my ($a, $b) = $link =~ /(\S+)\s(\S+)/;
    if ($links{$link} eq "pair") {
	print TOPO mungeName($a) . " -- " . mungeName($b) . " ;\n";
    } else {
	print TOPO mungeName($a) . " -- " . mungeName($b) . " ;\n";
    }
}

print TOPO "}\n";

close(TOPO);

my $bestOverlap;

# loop
for ($attempt = 0; $attempt < 16; $attempt++) {

### Send topology to neato.

    open (NEATO, "$NEATO_CMD $tempfile |" );

### Parse results from neato.

    %props = ();
    %nodeProps = ();

# General neato output parser.
# stashes away all properties returned for each graph node.
# (All we care about for now is "pos")
# Links are ignored.
275

276 277 278 279 280
    while (<NEATO>) {
	if (/^\s*(\w+)\s\[([^\]]*)\]/) {
	    # this line is a property set
	    ($cmd, $props) = ($1, $2);
	    $props =~ s/[\=\,]/ /g;
281

282 283 284 285 286 287
	    while (($props =~ s/^\s*(\w+)\s+((\"[^\"]*\")|(\w+))\s*//)) {
		# add each property to %props
		($k, $v) = ($1, $2);
		$v =~ s/\"//g;
		$props{$k} = $v;
#	        print "property $k gets value $v\n";
288 289
	    }

290 291 292 293 294 295 296
	    if ($cmd =~ /^node$/) {
#	print "node property $props\n";
	    } elsif ($cmd =~ /^graph$/) {
#	print "graph thingee (ignored)\n";
	    } else {
		# there is a name here, not "node" or "graph"
		# so it terminates the node.. store props away.
297
		$nodeProps{$cmd} = {%props};
298 299
		%props = ();
	    }
300
	}
301 302 303
    }

# done with neato process.
304

305
    close(NEATO);
306

307
# obtain X,Y for each node from stashed Properties.
308

309 310 311 312
    foreach $node (keys %nodes) {
	my $mungedName = mungeName( $node );
	if (exists $nodeProps{$mungedName}{"pos"}) {
	    $s = $nodeProps{$mungedName}{"pos"};
313
	    $s =~ /^\s*(\d+)\s+(\d+)/;
314
	    $nodes{ $node }{"x"} = $1;
315
	    $nodes{ $node }{"y"} = $2;
316 317 318 319
	} else {
	    warn "No position information returned for $node (mungedName=$mungedName)";
	}
    }
320

321
### Fixup positions (eat free columns and rows)
322

323 324 325 326 327 328 329 330 331 332 333
    my $subX = 0;
    my $lastX = 0;
    foreach $i (sort {$nodes{$a}{"x"} <=> $nodes{$b}{"x"}} keys %nodes) {
	my $xDiff = $nodes{$i}{"x"} - $lastX;
	if ($xDiff > 60) {
	    $subX += $xDiff - 60;
	}
	# last should be the position _before_ transform
	$lastX = $nodes{$i}{"x"};
	$nodes{$i}{"x"} -= $subX;
    }
334

335 336 337 338 339 340 341 342 343 344 345 346
    my $subY = 0;
    my $lastY = 0;
    foreach $i (sort {$nodes{$a}{"y"} <=> $nodes{$b}{"y"}} keys %nodes) {
	my $yDiff = $nodes{$i}{"y"} - $lastY;
	if ($yDiff > 60) {
	    $subY += $yDiff - 60;
	}
	# last should be the position _before_ transform
	$lastY = $nodes{$i}{"y"};
	$nodes{$i}{"y"} -= $subY;
    }

347
    # check for overlaps
348 349 350 351 352 353 354 355 356
    # false positive: each pair is checked twice. should fix this
    # false positive: two edges which end at the same node "collide".
    #                 but, this shouldn't give any attempt an unfair advantage.

    my $overlaps = 0;

    foreach my $linka (keys %links) {
	my ($a1, $a2) = ($linka =~ /(\S+)\s(\S+)/);

357 358 359 360
	defined $a1 or fatal("a1");
	defined $a2 or fatal("a2");
	exists $nodes{ $a1 } or fatal($a1);
	exists $nodes{ $a2 } or fatal($a2);
361 362 363 364

	my ($a1x,$a1y) = ($nodes{ $a1 }{"x"}, $nodes{ $a1 }{"y"});
	my ($a2x,$a2y) = ($nodes{ $a2 }{"x"}, $nodes{ $a2 }{"y"});

365 366 367 368
	defined $a1x or fatal("$linka $a1");
	defined $a1y or fatal($a1);
	defined $a2x or fatal($a2);
	defined $a2y or fatal($a2);
369 370 371 372

	foreach my $linkb (keys %links) {
	    # never check a link against itself
	    if ($linka eq $linkb) { next; }
373

374 375
	    my ($b1, $b2) = ($linkb =~ /(\S+)\s(\S+)/);

376 377
	    defined $b1 or fatal("b1");
	    defined $b2 or fatal("b2");
378 379 380 381

	    my ($b1x,$b1y) = ($nodes{ $b1 }{"x"}, $nodes{ $b1 }{"y"});
	    my ($b2x,$b2y) = ($nodes{ $b2 }{"x"}, $nodes{ $b2 }{"y"});

382 383 384 385
	    defined $b1x or fatal($b1);
	    defined $b1y or fatal($b1);
	    defined $b2x or fatal($b2);
	    defined $b2y or fatal($b2);
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401

	    my $shared = "";

	    # see if line segments share at least one common endpoint
	    if ($b1 eq $a1) { $shared = $b1; $unshared0 = $b2; $unshared1 = $a2; }
	    elsif ($b1 eq $a2) { $shared = $b1; $unshared0 = $b2; $unshared1 = $a1; }
	    elsif ($b2 eq $a1) { $shared = $b2; $unshared0 = $b1; $unshared1 = $a2; }
	    elsif ($b2 eq $a2) { $shared = $b2; $unshared0 = $b1; $unshared1 = $a1; }

	    if ($shared ne "") {
		if ($unshared0 eq $unshared1) {
		    # They share 2 endpoints,
		    # so they're the same segment;
		    # there's nothing to be done.
		    next;
		}
402

403 404 405
		# if segments share a common endpoint,
		# then see if they are at a greater than 5 degree angle.

406
		my ($adx, $ady) = ($nodes{$unshared0}{"x"} - $nodes{$shared}{"x"},
407
				   $nodes{$unshared0}{"y"} - $nodes{$shared}{"y"} );
408
		my ($bdx, $bdy) = ($nodes{$unshared1}{"x"} - $nodes{$shared}{"x"},
409 410 411 412 413 414 415 416 417 418
				   $nodes{$unshared1}{"y"} - $nodes{$shared}{"y"} );

		my $alen = sqrt( $adx * $adx + $ady * $ady );
		my $blen = sqrt( $bdx * $bdx + $bdy * $bdy );

		# A dot product is |A|*|B|*cos(Theta).
		# We calculate A dot B, then divide by |A|*|B| to get
		# cos(Theta), which we compare with cos(5 degrees).
		my $dotProduct = ($adx * $bdx + $ady * $bdy) / ($alen * $blen);

419 420 421
		# cosine of 10 deg is ~0.9848
		# cosine of 5 deg is ~0.9962
		if ($dotProduct > 0.9962) {
422 423
		    # dprint "overlap '$linka'-'$linkb' $dotProduct\n";
		    # bad overlap.
424 425
		    $overlaps += 0.9;
		} elsif ($dotProduct > 0.9848) {
426
		    # dprint "overlap '$linka'-'$linkb' $dotProduct\n";
427
		    $overlaps += 0.5;
428
		}
429

430 431 432
		next;
	    }

433

434 435
	    # formula derived from solving simultaneous parametric line equations
	    # u is parameter for line A, v is for line B.
436
	    # for line segments to collide, u and v of collision must both be
437 438 439 440
	    # between 0 and 1 (inclusive).

	    my ($k0, $k1, $k2) = ($a2x - $a1x, $b1x - $b2x, $a1x - $b1x);
	    my ($k3, $k4, $k5) = ($a2y - $a1y, $b1y - $b2y, $a1y - $b1y);
441

442 443
	    my $v_n = ($k2 * $k3 - $k0 * $k5);
	    my $v_d = ($k0 * $k4 - $k3 * $k1);
444

445 446
	    if ($v_d < 0.001 && $v_d > -0.001) { next; } # no solution (i.e., lines are parallel)
	    my $v = $v_n / $v_d;
447

448 449 450
	    my $u_n = -($k4 * $v + $k5);
	    my $u_d = $k3;
	    if ($u_d < 0.001 && $u_d > -0.001) { next; } # no solution (i.e., lines are parallel)
451

452
	    my $u = $u_n / $u_d;
453 454

	    if ($u >= 0.0 && $u <= 1.0 &&
455 456 457 458 459 460 461 462 463
		$v >= 0.0 && $v <= 1.0) {
		#dprint "overlap '$linka'-'$linkb' u=$u v=$v\n";
		$overlaps++;
	    }
	} # foreach $linkb
    } # foreach $linka

    dprint "Attempt = $attempt, overlaps = $overlaps.\n";

464 465 466 467 468 469
    #
    # if this is the best so far, stash it in the DB, This gives us
    # a picture quickly, even if its not the best picture. Also gives
    # us something in case the experiment is terminated or modified before
    # the render finishes, which is quite possible on giant experiments.
    #
470
    if (!defined $bestOverlaps || $overlaps < $bestOverlaps) {
471
	dprint "Saving config\n";
472
	$bestOverlaps = $overlaps;
473 474 475 476 477

        # We have to lock the table so as not to cause grief to someone
	# trying to vis this experiment during this window.
	$result =
	    DBQueryWarn("lock tables vis_nodes write");
478

479 480 481 482 483 484 485 486 487 488
	fatal("Failed to lock vis_nodes table.")
	    if (!$result);

	$result =
	    DBQueryWarn("DELETE FROM vis_nodes ".
			"WHERE pid='$pid' AND eid='$eid'");
	fatal("Failed to clear old vis_nodes from DB")
	    if (!$result);

	# Then stash new one.
489
	foreach $node (keys %nodes) {
490
	    $result =
491
		DBQueryWarn("INSERT INTO vis_nodes ".
492 493
			    "(vname, exptidx,pid, eid, vis_type, x, y) VALUES".
			    " ('$node', '$exptidx', '$pid', '$eid', " .
494 495 496
			    "'" . $nodes{ $node }{"type"} . "', " .
			    "'" . $nodes{ $node }{"x"}    . "', " .
			    "'" . $nodes{ $node }{"y"}    . "') ");
497

498 499 500 501 502
	    fatal("Failed to insert new vis_nodes into DB")
		if (!$result);
	}
	$result =
	    DBQueryWarn("unlock tables");
503

504 505 506 507 508 509 510 511 512 513 514 515
	fatal("Failed to unlock vis_nodes table.")
	    if (!$result);

	#
	# Generate thumbnail, if called for. The .png file is put into
	# the work directory, so it is copied off to the users
	# directory. We take that file and stash it in the DB, since
	# that is where the system will read it from.
	#
	if ($thumb) {
	    my $workdir = TBExptWorkDir($pid, $eid);
	    my $fname   = "$workdir/$eid.png";
516

517 518 519 520 521 522 523 524
	    if (system("$THUMB_CMD $pid $eid > $fname")) {
		print STDERR "Error generating thumbnail.\n";
	    }
	    else {
		TBExptSetThumbNail($pid, $eid, `cat $fname`);
	    }
	}
    }
525 526 527 528 529 530

    # if there were no overlaps, we're done.
    if ($overlaps == 0) { last; }
} # for $attempt

### Success!!
531
cleanup();
532

533
exit 0;
534 535 536 537 538 539 540 541 542 543 544 545 546 547


# function to munge node/lan names as they are fed to neato so
# so neato doesn't choke.
# First, looks to see if this name has already been used.
# If not, changes substrings of non-word characters to underscores, and
# appends a unique identifier.

sub mungeName($) {
    my $n = shift;
    if (exists $mungeMap{$n}) {
	return $mungeMap{$n};
    }
    my $nm = $n;
548
    $nm =~ s/\W+/_/g;
549 550 551 552 553 554 555 556 557
    $nm .= "__" . $mungeUID++;
    $mungeMap{$n} = $nm;
    return $nm;
}

sub dprint($) {
    my $n = shift;
    if ($debug > 0) { print STDERR $n; }
}
558 559 560

sub cleanup()
{
561 562 563 564
    ### Delete tempfile
    unlink $tempfile
	if (defined($tempfile));

565 566 567 568 569 570 571 572 573 574
    # Clear our pid from the DB since we are about to exit.
    if ($renderpid) {
	DBQueryFatal("update experiments set prerender_pid=0 ".
		     "where pid='$pid' and eid='$eid'");
    }
}

sub fatal($)
{
    my $msg = shift;
575

576
    cleanup();
577
    DBQueryFatal("DELETE FROM vis_nodes WHERE pid='$pid' AND eid='$eid'");
578 579 580 581 582 583 584 585 586 587 588
    die("*** $0:\n".
	"    $msg\n");
}

sub KillOldRender()
{
    DBQueryFatal("lock tables experiments write");

    my $query_result =
	DBQueryFatal("select prerender_pid from experiments ".
		     "where pid='$pid' and eid='$eid'");
589

590 591 592
    DBQueryFatal("update experiments set ".
		 "prerender_pid=-prerender_pid ".
		 "where pid='$pid' and eid='$eid'");
593

594 595 596 597 598 599 600
    DBQueryWarn("unlock tables");

    my @row    = $query_result->fetchrow_array();
    my $procid = $row[0];

    if ($procid > 0 &&
	! kill('TERM', $procid)) {
601 602 603 604 605 606 607 608
	my $err = $!;

	if ($err == ESRCH) {
	    warn "Prerender process $procid for $pid/$eid already dead";
	} else {
	    DBQueryWarn("update experiments set ".
			"prerender_pid=-prerender_pid ".
			"where pid='$pid' and eid='$eid'");
609

610 611 612
	    SENDMAIL($TBOPS,
		     "Failed to stop prerender for $pid/$eid",
		     "Could not kill(TERM) process $procid: $? $err");
613

614 615 616
	    die("*** $0:\n".
		"Failed to stop prerender for $pid/$eid!\n");
	}
617 618
    }
}