prerender.in 15.4 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 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 41 42

sub dprint($);

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

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

%options = ();

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

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

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

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

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

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

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

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

103
#
104 105
# Okay, go into the background.
#
106 107 108 109 110
if (! $foreground) {
    if (TBBackGround("prerender.output")) {
	#
	# Parent exits normally
	#
111
	print STDOUT "Image rendering proceeding in background mode ...\n";
112 113 114 115 116 117 118 119 120 121 122 123 124
	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;
125

126 127 128 129 130 131 132 133
    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);

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

# read nodes

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

fatal("Failed to get virt_nodes info from DB")
    if (!$result);
143 144 145 146

my $nodes = ();
my $lans  = ();
my $links = ();
147
my $fixednodes = ();
148 149

# all virt_nodes are visualizer nodes of type "node"
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
while (my ($vname,$fixed) = $result->fetchrow) {
    dprint "node $vname $fixed\t";
    if (!defined($fixednodes{$vname})) {
	# This node is not a parent node, so we can add it
	$nodes{$vname}{"type"} = "node";
	dprint "added nodes($vname)\t";
    } else {
	dprint "$vname is a fixed host!\t";
    }
    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";
	$fixednodes{$fixed} = $vname;
	if (defined($nodes{$fixed})) {
	    # Remove the node if it is already there
	    delete $nodes{$fixed};
	    dprint "rm nodes($fixed)\t";
	}
    }
    dprint "\n";
171 172 173 174
}

# read lans

175
$result = DBQueryWarn("SELECT vname, member FROM virt_lans " .
176 177
		       "WHERE pid='$pid' AND eid='$eid'");

178 179 180
fatal("Failed to get virt_lans info from DB")
    if (!$result);

181 182
while (my ($vname, $member) = $result->fetchrow) {
    $member =~ s/\:.*//;
183 184 185 186 187 188 189
    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";
190 191 192 193 194 195 196 197 198 199 200 201
}

# 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").
202
	if (exists $nodes{$lan}) { fatal("LAN $lan name collided."); }
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
	$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));

220 221
open (TOPO, ">$tempfile" ) or
    fatal("Couldn't open temporary file '$tempfile'\n");
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

# 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.
262

263 264 265 266 267
    while (<NEATO>) {
	if (/^\s*(\w+)\s\[([^\]]*)\]/) {
	    # this line is a property set
	    ($cmd, $props) = ($1, $2);
	    $props =~ s/[\=\,]/ /g;
268

269 270 271 272 273 274
	    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";
275 276
	    }

277 278 279 280 281 282 283
	    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.
284
		$nodeProps{$cmd} = {%props};
285 286
		%props = ();
	    }
287
	}
288 289 290
    }

# done with neato process.
291

292
    close(NEATO);
293

294
# obtain X,Y for each node from stashed Properties.
295

296 297 298 299
    foreach $node (keys %nodes) {
	my $mungedName = mungeName( $node );
	if (exists $nodeProps{$mungedName}{"pos"}) {
	    $s = $nodeProps{$mungedName}{"pos"};
300
	    $s =~ /^\s*(\d+)\s+(\d+)/;
301
	    $nodes{ $node }{"x"} = $1;
302
	    $nodes{ $node }{"y"} = $2;
303 304 305 306
	} else {
	    warn "No position information returned for $node (mungedName=$mungedName)";
	}
    }
307

308
### Fixup positions (eat free columns and rows)
309

310 311 312 313 314 315 316 317 318 319 320
    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;
    }
321

322 323 324 325 326 327 328 329 330 331 332 333
    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;
    }

334
    # check for overlaps
335 336 337 338 339 340 341 342 343
    # 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+)/);

344 345 346 347
	defined $a1 or fatal("a1");
	defined $a2 or fatal("a2");
	exists $nodes{ $a1 } or fatal($a1);
	exists $nodes{ $a2 } or fatal($a2);
348 349 350 351

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

352 353 354 355
	defined $a1x or fatal("$linka $a1");
	defined $a1y or fatal($a1);
	defined $a2x or fatal($a2);
	defined $a2y or fatal($a2);
356 357 358 359

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

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

363 364
	    defined $b1 or fatal("b1");
	    defined $b2 or fatal("b2");
365 366 367 368

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

369 370 371 372
	    defined $b1x or fatal($b1);
	    defined $b1y or fatal($b1);
	    defined $b2x or fatal($b2);
	    defined $b2y or fatal($b2);
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388

	    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;
		}
389

390 391 392
		# if segments share a common endpoint,
		# then see if they are at a greater than 5 degree angle.

393
		my ($adx, $ady) = ($nodes{$unshared0}{"x"} - $nodes{$shared}{"x"},
394
				   $nodes{$unshared0}{"y"} - $nodes{$shared}{"y"} );
395
		my ($bdx, $bdy) = ($nodes{$unshared1}{"x"} - $nodes{$shared}{"x"},
396 397 398 399 400 401 402 403 404 405
				   $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);

406 407 408
		# cosine of 10 deg is ~0.9848
		# cosine of 5 deg is ~0.9962
		if ($dotProduct > 0.9962) {
409 410
		    # dprint "overlap '$linka'-'$linkb' $dotProduct\n";
		    # bad overlap.
411 412
		    $overlaps += 0.9;
		} elsif ($dotProduct > 0.9848) {
413
		    # dprint "overlap '$linka'-'$linkb' $dotProduct\n";
414
		    $overlaps += 0.5;
415
		}
416

417 418 419
		next;
	    }

420

421 422
	    # formula derived from solving simultaneous parametric line equations
	    # u is parameter for line A, v is for line B.
423
	    # for line segments to collide, u and v of collision must both be
424 425 426 427
	    # 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);
428

429 430
	    my $v_n = ($k2 * $k3 - $k0 * $k5);
	    my $v_d = ($k0 * $k4 - $k3 * $k1);
431

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

435 436 437
	    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)
438

439
	    my $u = $u_n / $u_d;
440 441

	    if ($u >= 0.0 && $u <= 1.0 &&
442 443 444 445 446 447 448 449 450
		$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";

451 452 453 454 455 456
    #
    # 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.
    #
457 458
    if (!defined $bestOverlaps || $overlaps < $bestOverlaps) {
	$bestOverlaps = $overlaps;
459 460 461 462 463

        # 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");
464

465 466 467 468 469 470 471 472 473 474
	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.
475
	foreach $node (keys %nodes) {
476
	    $result =
477 478 479 480 481 482
		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"}    . "') ");
483

484 485 486 487 488
	    fatal("Failed to insert new vis_nodes into DB")
		if (!$result);
	}
	$result =
	    DBQueryWarn("unlock tables");
489

490 491 492 493 494 495 496 497 498 499 500 501
	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";
502

503 504 505 506 507 508 509 510
	    if (system("$THUMB_CMD $pid $eid > $fname")) {
		print STDERR "Error generating thumbnail.\n";
	    }
	    else {
		TBExptSetThumbNail($pid, $eid, `cat $fname`);
	    }
	}
    }
511 512 513 514 515 516

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

### Success!!
517
cleanup();
518

519
exit 0;
520 521 522 523 524 525 526 527 528 529 530 531 532 533


# 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;
534
    $nm =~ s/\W+/_/g;
535 536 537 538 539 540 541 542 543
    $nm .= "__" . $mungeUID++;
    $mungeMap{$n} = $nm;
    return $nm;
}

sub dprint($) {
    my $n = shift;
    if ($debug > 0) { print STDERR $n; }
}
544 545 546

sub cleanup()
{
547 548 549 550
    ### Delete tempfile
    unlink $tempfile
	if (defined($tempfile));

551 552 553 554 555 556 557 558 559 560
    # 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;
561

562
    cleanup();
563
    DBQueryFatal("DELETE FROM vis_nodes WHERE pid='$pid' AND eid='$eid'");
564 565 566 567 568 569 570 571 572 573 574
    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'");
575

576 577 578
    DBQueryFatal("update experiments set ".
		 "prerender_pid=-prerender_pid ".
		 "where pid='$pid' and eid='$eid'");
579

580 581 582 583 584 585 586
    DBQueryWarn("unlock tables");

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

    if ($procid > 0 &&
	! kill('TERM', $procid)) {
587 588 589 590 591 592 593 594
	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'");
595

596 597 598
	    SENDMAIL($TBOPS,
		     "Failed to stop prerender for $pid/$eid",
		     "Could not kill(TERM) process $procid: $? $err");
599

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