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

#
# EMULAB-COPYRIGHT
5
# Copyright (c) 2000-2003 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 BSD::Resource;
13 14 15 16 17 18

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

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

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

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

# Untaint the path
29
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:@prefix@/libexec/vis';
30 31 32 33 34 35 36
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";
37
my $THUMB_CMD = "render -t 160";
38 39 40 41

sub dprint($);

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

48
my $optlist = "rvtf";
49 50 51 52 53 54 55

%options = ();

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

my $debug = 0;
56
my $thumb = 0;
57
my $foreground = 0;
58

59 60 61 62 63
if ( defined($options{"v"}) ) { 
    $debug++; 
    # pass verbosity along to thumbnail render.
    $THUMB_CMD .= " -v"; 
}
64

65 66 67
if ( defined($options{"t"}) ) { 
    $thumb++; 
}
68 69 70
if ( defined($options{"f"}) ) { 
    $foreground++; 
}
71

72 73
#my ($pid) = $ARGV[0];
#my ($eid) = $ARGV[1];
74 75
my ($pid) = $ARGV[0] =~ /([0-9a-zA-Z_\-]+)/;
my ($eid) = $ARGV[1] =~ /([0-9a-zA-Z_\-]+)/;
76

77 78 79
# for the mungeName function, below.
$mungeUID = 0;

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
# 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
# pid in the DB. We always kill a running prerender. 
#
KillOldRender();

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

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
#
# Okay, go into the background. 
# 
if (! $foreground) {
    if (TBBackGround("prerender.output")) {
	#
	# Parent exits normally
	#
	print STDOUT "Image rendering proceeding in background mode ...\n"; 
	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;
    
    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);

133 134 135 136
### Now, read experiment virtual info from the DB.

# read nodes

137 138 139 140 141
my $result = DBQueryWarn("SELECT vname FROM virt_nodes " .
			 "WHERE pid='$pid' AND eid='$eid'");

fatal("Failed to get virt_nodes info from DB")
    if (!$result);
142 143 144 145 146 147 148 149 150 151 152 153

my $nodes = ();
my $lans  = ();
my $links = ();

# all virt_nodes are visualizer nodes of type "node"
while (my ($vname) = $result->fetchrow) {
    $nodes{$vname}{"type"} = "node";
}

# read lans

154
$result = DBQueryWarn("SELECT vname, member FROM virt_lans " .
155 156
		       "WHERE pid='$pid' AND eid='$eid'");

157 158 159
fatal("Failed to get virt_lans info from DB")
    if (!$result);

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
while (my ($vname, $member) = $result->fetchrow) {
    $member =~ s/\:.*//;
    $lans{$vname}{$member} = 1;
}

# 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").
175
	if (exists $nodes{$lan}) { fatal("LAN $lan name collided."); }
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
	$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));

193 194
open (TOPO, ">$tempfile" ) or
    fatal("Couldn't open temporary file '$tempfile'\n");
195 196 197 198 199 200 201 202 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 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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

# 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.
    
    while (<NEATO>) {
	if (/^\s*(\w+)\s\[([^\]]*)\]/) {
	    # this line is a property set
	    ($cmd, $props) = ($1, $2);
	    $props =~ s/[\=\,]/ /g;
	    
	    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";
	    } 
	    
	    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.
		$nodeProps{$cmd} = {%props}; 
		%props = ();
	    }
	} 
    }

# done with neato process.
    
    close(NEATO);
    
# obtain X,Y for each node from stashed Properties.
    
    foreach $node (keys %nodes) {
	my $mungedName = mungeName( $node );
	if (exists $nodeProps{$mungedName}{"pos"}) {
	    $s = $nodeProps{$mungedName}{"pos"};
	    $s =~ /^\s*(\d+)\s+(\d+)/;    
	    $nodes{ $node }{"x"} = $1;
	    $nodes{ $node }{"y"} = $2; 	
	} else {
	    warn "No position information returned for $node (mungedName=$mungedName)";
	}
    }
    
### Fixup positions (eat free columns and rows)
    
    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;
    }
    
    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;
    }

    # check for overlaps 
    # 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+)/);

317 318 319 320
	defined $a1 or fatal("a1");
	defined $a2 or fatal("a2");
	exists $nodes{ $a1 } or fatal($a1);
	exists $nodes{ $a2 } or fatal($a2);
321 322 323 324

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

325 326 327 328
	defined $a1x or fatal("$linka $a1");
	defined $a1y or fatal($a1);
	defined $a2x or fatal($a2);
	defined $a2y or fatal($a2);
329 330 331 332 333 334 335

	foreach my $linkb (keys %links) {
	    # never check a link against itself
	    if ($linka eq $linkb) { next; }
    
	    my ($b1, $b2) = ($linkb =~ /(\S+)\s(\S+)/);

336 337
	    defined $b1 or fatal("b1");
	    defined $b2 or fatal("b2");
338 339 340 341

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

342 343 344 345
	    defined $b1x or fatal($b1);
	    defined $b1y or fatal($b1);
	    defined $b2x or fatal($b2);
	    defined $b2y or fatal($b2);
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423

	    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;
		}
		
		# if segments share a common endpoint,
		# then see if they are at a greater than 5 degree angle.

		my ($adx, $ady) = ($nodes{$unshared0}{"x"} - $nodes{$shared}{"x"}, 
				   $nodes{$unshared0}{"y"} - $nodes{$shared}{"y"} );
		my ($bdx, $bdy) = ($nodes{$unshared1}{"x"} - $nodes{$shared}{"x"}, 
				   $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);

		# cosine of 10 deg is ~0.9848	       
		# cosine of 5 deg is ~0.9962	       
		if ($dotProduct > 0.9962) { 
		    # dprint "overlap '$linka'-'$linkb' $dotProduct\n";
		    # bad overlap.
		    $overlaps += 0.9; 
		} elsif ($dotProduct > 0.9848) { 
		    # dprint "overlap '$linka'-'$linkb' $dotProduct\n";
		    $overlaps += 0.5; 
		}
		
		next;
	    }

	    
	    # formula derived from solving simultaneous parametric line equations
	    # u is parameter for line A, v is for line B.
	    # for line segments to collide, u and v of collision must both be 
	    # 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);
	    
	    my $v_n = ($k2 * $k3 - $k0 * $k5);
	    my $v_d = ($k0 * $k4 - $k3 * $k1);
	    
	    if ($v_d < 0.001 && $v_d > -0.001) { next; } # no solution (i.e., lines are parallel)
	    my $v = $v_n / $v_d;
	    
	    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)
	    
	    my $u = $u_n / $u_d;
	    
	    if ($u >= 0.0 && $u <= 1.0 && 
		$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";

424 425 426 427 428 429
    #
    # 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.
    #
430 431
    if (!defined $bestOverlaps || $overlaps < $bestOverlaps) {
	$bestOverlaps = $overlaps;
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447

        # 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");
	
	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.
448
	foreach $node (keys %nodes) {
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
	    $result = 
		DBQueryWarn("INSERT INTO vis_nodes ".
			    "(vname, pid, eid, vis_type, x, y) VALUES".
			    " ('$node', '$pid', '$eid', " .
			    "'" . $nodes{ $node }{"type"} . "', " .
			    "'" . $nodes{ $node }{"x"}    . "', " .
			    "'" . $nodes{ $node }{"y"}    . "') ");
	
	    fatal("Failed to insert new vis_nodes into DB")
		if (!$result);
	}
	$result =
	    DBQueryWarn("unlock tables");
	
	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";
	
	    if (system("$THUMB_CMD $pid $eid > $fname")) {
		print STDERR "Error generating thumbnail.\n";
	    }
	    else {
		TBExptSetThumbNail($pid, $eid, `cat $fname`);
	    }
	}
    }
484 485 486 487 488 489

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

### Success!!
490
cleanup();
491

492
exit 0;
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516


# 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;
    $nm =~ s/\W+/_/g; 
    $nm .= "__" . $mungeUID++;
    $mungeMap{$n} = $nm;
    return $nm;
}

sub dprint($) {
    my $n = shift;
    if ($debug > 0) { print STDERR $n; }
}
517 518 519

sub cleanup()
{
520 521 522 523
    ### Delete tempfile
    unlink $tempfile
	if (defined($tempfile));

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
    # 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;
    
    cleanup();
    DBQueryFatal("DELETE FROM vis_nodes WHERE pid='$pid' AND eid='$eid'");    
    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'");
    
    DBQueryFatal("update experiments set ".
		 "prerender_pid=-prerender_pid ".
		 "where pid='$pid' and eid='$eid'");
		 
    DBQueryWarn("unlock tables");

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

    if ($procid > 0 &&
	! kill('TERM', $procid)) {
	DBQueryWarn("update experiments set ".
		    "prerender_pid=-prerender_pid ".
		    "where pid='$pid' and eid='$eid'");
	
	SENDMAIL($TBOPS,
		 "Failed to stop prerender for $pid/$eid",
		 "Could not kill(TERM) process $procid: $? $!");

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