Template.pm.in 94.9 KB
Newer Older
1 2 3
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2005, 2006, 2007 University of Utah and the Flux Group.
5 6 7 8
# All rights reserved.
#
# XXX Need to deal with locking at some point ...
#
9
package Template;
10 11 12 13 14 15 16 17 18 19 20 21 22

use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw ( );

# Must come after package declaration!
use lib '@prefix@/lib';
use libdb;
use libtestbed;
use libtblog;
23
use libArchive;
24 25
use Archive;
use Project;
26
use User;
27
use Experiment;
28
use Group;
29
use Logfile;
30
use English;
31
use HTML::Entities;
32
use overload ('""' => 'Stringify');
33 34 35

# Configure variables
my $TB		= "@prefix@";
36
my $CONTROL	= "@USERNODE@";
37
my $STAMPS      = @STAMPS@;
38
my $MD5         = "/sbin/md5";
39 40 41
my $MKDIR       = "/bin/mkdir";
my $RMDIR       = "/bin/rmdir";
my $RM		= "/bin/rm";
42
my $makegraph   = "$TB/bin/template_graph";
43
my $TEVC	= "$TB/bin/tevc";
44
my $DBCONTROL   = "$TB/sbin/opsdb_control";
45
my $RSYNC	= "/usr/local/bin/rsync";
46

47 48
# Cache of template instances to avoid regenerating them.
my %templates   = ();
49
my $debug	= 1;
50

51 52 53 54
# Flags for functions below.
sub STARTRUN_FLAGS_FIRSTRUN()	{ 0x1 ;}
sub STARTRUN_FLAGS_SWAPMOD()	{ 0x2 ;}

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
#
# Grab a new GUID for a template. We do not have to use it of course.
#
sub NewGUID($)
{
    my ($pidx) = @_;
    my $idx;
    
    DBQueryFatal("lock tables emulab_indicies write");

    my $query_result = 
	DBQueryFatal("select idx from emulab_indicies ".
		     "where name='next_guid'");
	
    if (! $query_result->num_rows) {
	$idx = 10000;
	
	DBQueryFatal("insert into emulab_indicies (name, idx) ".
		     "values ('next_guid', $idx)");
    }
    else {
	($idx) = $query_result->fetchrow_array();
    }
    my $nextidx = $idx + 1;
    
    DBQueryFatal("update emulab_indicies set idx='$nextidx' ".
		 "where name='next_guid'");

    DBQueryFatal("unlock tables");

    $$pidx = $idx;
    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
89 90 91 92 93 94 95 96 97 98
# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

    print STDERR "Running '$command'\n"
	if ($debug);
    return system($command);
}

99
#
100
# Lookup a template and create a class instance to return.
101
#
102
sub Lookup($$;$)
103
{
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    my ($class, $arg1, $arg2) = @_;
    my ($guid, $vers);

    #
    # A single arg is either an index or a "guid,vers" or "guid/vers" string.
    #
    if (!defined($arg2)) {
	if ($arg1 =~ /^([-\w]*),([-\w]*)$/ ||
	    $arg1 =~ /^([-\w]*)\/([-\w]*)$/) {
	    $guid = $1;
	    $vers = $2;
	}
	else {
	    return undef;
	}
    }
    elsif (! (($arg1 =~ /^[-\w]*$/) && ($arg2 =~ /^[-\w]*$/))) {
	return undef;
    }
    else {
	$guid = $arg1;
	$vers = $arg2;
    }
127

128 129 130 131
    # Look in cache first
    return $templates{"$guid/$vers"}
        if (exists($templates{"$guid/$vers"}));
    
132
    my $query_result =
133 134
	DBQueryWarn("select * from experiment_templates ".
		    "where guid='$guid' and vers='$vers'");
135

136 137
    return undef
	if (!$query_result || !$query_result->numrows);
138

139 140 141 142 143
    my $self             = {};
    $self->{'TEMPLATE'}  = $query_result->fetchrow_hashref();
    # Filled lazily.
    $self->{'INSTANCES'} = undef;
    bless($self, $class);
144
    
145 146 147 148
    # Add to cache. 
    $templates{"$guid/$vers"} = $self;
    
    return $self;
149
}
150 151 152 153
# accessors
sub guid($) { return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'guid'}); }
sub vers($) { return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'vers'}); }
sub pid($)  { return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'pid'}); }
154
sub pid_idx($) { return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'pid_idx'}); }
155
sub gid($)  { return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'gid'}); }
156
sub gid_idx($)  { return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'gid_idx'}); }
157
sub eid($)  { return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'eid'}); }
158
sub exptidx($) { return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'exptidx'}); }
159
sub tid($)  { return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'tid'}); }
160
sub path($) { return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'path'}); }
161 162
sub archive_idx($) {
    return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'archive_idx'}); }
163 164 165 166
sub parent_guid($) {
    return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'parent_guid'}); }
sub IsRoot($) {
    return ! defined($_[0]->{'TEMPLATE'}->{'parent_guid'}); }
167 168 169 170 171 172
sub child_guid($) {
    return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'child_guid'}); }
sub child_vers($) {
    return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'child_vers'}); }
sub description($) {
    return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'description'}); }
173 174 175 176
sub logfile($) {
    return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'logfile'}); }
sub logfile_open($) {
    return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'logfile_open'}); }
177 178
sub active($) {
    return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'active'}); }
179 180

#
181
# Lookup a template given an experiment index.
182
#
183
sub LookupByExptidx($$)
184
{
185
    my ($class, $exptidx) = @_;
186

187 188
    # Use the Template Instance routine, and grab the template out of it.
    my $template_instance = Template::Instance->LookupByExptidx($exptidx);
189

190 191
    return undef
	if (!defined($template_instance));
192

193
    return $template_instance->template();
194 195
}

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
#
# Lookup a template given pid,eid. This refers to the template itself,
# not an instance of the template.
#
sub LookupByPidEid($$$)
{
    my ($class, $pid, $eid) = @_;

    my $query_result =
	DBQueryWarn("select guid,vers from experiment_templates ".
		    "where pid='$pid' and eid='$eid'");

    return undef
	if (!$query_result || !$query_result->numrows);

    my ($guid,$vers) = $query_result->fetchrow_array();

    return Template->Lookup($guid, $vers);
}

216 217 218 219 220 221 222 223 224 225 226 227 228 229
#
# Return the underlying experiment object for the template itself.
#
sub GetExperiment($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return undef
	if (! ref($self));

    return Experiment->LookupByIndex($self->exptidx());
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
230
#
231
# Refresh a template instance by reloading from the DB.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
232
#
233
sub Refresh($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
234
{
235
    my ($self) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
236

237 238
    return -1
	if (! ref($self));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
239

240 241 242 243 244 245
    my $guid = $self->guid();
    my $vers = $self->vers();
    
    my $query_result =
	DBQueryWarn("select * from experiment_templates ".
		    "where guid='$guid' and vers='$vers'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
246 247

    return -1
248 249 250
	if (!$query_result || !$query_result->numrows);
	
    $self->{'TEMPLATE'} = $query_result->fetchrow_hashref();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
251 252 253
    return 0;
}

254
#
255 256
# Create a new template. This installs the new record in the DB,
# and returns an instance. There is some bookkeeping along the way.
257
#
258
sub Create($$)
259
{
260 261
    my ($class, $argref) = @_;
    my ($guid, $vers);
262

263 264
    return undef
	if (ref($class));
265

Leigh B. Stoller's avatar
Leigh B. Stoller committed
266 267 268 269 270 271 272 273 274
    my $pid = $argref->{'pid'};
    my $gid = $argref->{'gid'};
    # Need the group object since we want to use its idx.
    my $group = Group->LookupByPidGid($pid, $gid);
    if (!defined($group)) {
	tberror("Could not map $pid/$gid to its object!");
	return undef;
    }

275 276 277 278 279 280 281 282 283 284 285 286 287
    # See if this a child of an existing template.
    if (defined($argref->{'parent_guid'})) {
	$guid = $argref->{'parent_guid'};
    }
    else {
	#
	# Grab a new GUID before we lock other tables.
	#
	if (NewGUID(\$guid) < 0) {
	    tberror("Could not get a new GUID!");
	    return undef;
	}
	$vers = 1;
288 289
    }

290 291 292
    DBQueryWarn("lock tables experiments write, ".
		"            experiment_templates write")
	or return undef;
293

294 295 296 297 298 299 300
    #
    # Find unused version number now that tables are locked. 
    #
    if (! defined($vers)) {
	my $query_result =
	    DBQueryWarn("select MAX(vers) from experiment_templates ".
			"where guid='$guid'");
301

302 303 304 305
	if (!$query_result) {
	    DBQueryWarn("unlock tables");
	    return undef;
	}
306

307 308 309
	$vers = ($query_result->fetchrow_array())[0];
	$vers++;
    }
310

311 312 313
    # We make up an eid using the guid and version. This is the eid for the
    # hidden experiment behind each template. 
    my $eid = "T${guid}-${vers}";
314 315 316

    $argref->{'pid_idx'} = $group->pid_idx();
    $argref->{'gid_idx'} = $group->gid_idx();
317

318
    #
319
    # Sanity check; make sure this eid is not in use. Tables are still locked.
320 321
    #
    my $query_result =
322 323
	DBQueryWarn("select pid,eid from experiments ".
		    "where eid='$eid' and pid='$pid'");
324

325 326 327 328 329 330 331 332 333
    if (!$query_result) {
	DBQueryWarn("unlock tables");
	return undef;
    }
    
    if ($query_result->numrows) {
	DBQueryWarn("unlock tables");
	tberror("Experiment ID $eid in project $pid is already in use!");
	return undef;
334 335
    }

336 337
    my $query = "insert into experiment_templates set ".
	join(",", map("$_='" . $argref->{$_} . "'", keys(%{$argref})));
338

339 340
    # Append the rest
    $query .= ",created=now(),guid='$guid',vers='$vers',eid='$eid'";
341

342 343 344 345 346 347 348
    if (! DBQueryWarn($query)) {
	DBQueryWarn("unlock tables");
	return undef;
    }
    DBQueryWarn("unlock tables");

    return Template->Lookup($guid, $vers);
349 350 351
}

#
352
# Stringify for output.
353
#
354
sub Stringify($)
355
{
356 357 358
    my ($self) = @_;
    my $guid   = $self->guid();
    my $vers   = $self->vers();
359

360
    return "[Template: $guid/$vers]";
361 362
}

363
#
364
# Update a template record given an array reference of slot/value pairs.
365
#
366
sub Update($$)
367
{
368
    my ($self, $argref) = @_;
369

370 371 372
    # Must be a real reference. 
    return -1
	if (! ref($self));
373

374 375
    my $guid = $self->guid();
    my $vers = $self->vers();
376

377 378 379 380
    my $query = "update experiment_templates set ".
	join(",", map("$_='" . $argref->{$_} . "'", keys(%{$argref})));

    $query .= " where guid='$guid' and vers='$vers'";
381 382 383

    return -1
	if (! DBQueryWarn($query));
384 385

    return Refresh($self);
386 387
}

388
#
389 390
# Delete a template (all tables). Note that other parts of the template
# like instances must already be gone when this is called.
391
#
392
sub Delete($)
393
{
394
    my ($self) = @_;
395

396
    # Must be a real reference. 
397
    return -1
398
	if (! ref($self));
399

400 401
    my $guid = $self->guid();
    my $vers = $self->vers();
402 403 404 405 406 407
    my $path = $self->path();

    if (defined($path) && $path ne "" && -e $path) {
	mysystem("$RM -rf $path") == 0
	    or return -1;
    }
408

409
    DeleteAllMetadata($self) == 0
410
	or return -1;
411

412 413
    DeleteInputFiles($self) == 0
	or return -1;
414

415 416 417 418 419
    my $logfile = $self->GetLogFile();
    if (defined($logfile)) {
	$logfile->Delete();
    }

420 421 422 423
    # The graph can be removed if this is the last template version.
    my $query_result =
	DBQueryWarn("select vers from experiment_templates ".
		    "where guid='$guid' and vers!='$vers'");
424 425 426
    return -1
	if (! $query_result);

427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    if (! $query_result->numrows) {
	DBQueryWarn("delete from experiment_template_graphs ".
		    "where parent_guid='$guid'")
	    or return -1;
    }

    # Make sure the experiment_templates table is always last, in case
    # something goes wrong. 
    my @tables = ("experiment_template_parameters",
		  "experiment_templates");

    foreach my $table (@tables) {
        if ($table eq "experiment_templates") {
            DBQueryWarn("delete from $table ".
			"where guid='$guid' and vers='$vers'")
		or return -1;
        }
        else {
            DBQueryWarn("delete from $table ".
			"where parent_guid='$guid' and parent_vers='$vers'")
		or return -1;
        }
    }
    $self->{'TEMPLATE'} = undef;
451 452 453
    return 0;
}

454 455 456
#
# Logfiles. This all needs to change.
#
457
# Open a new logfile and return it.
458
#
459
sub CreateLogFile($$)
460
{
461
    my ($self, $prefix) = @_;
462 463

    # Must be a real reference. 
464
    return undef
465 466 467 468 469 470 471
	if (! ref($self));

    my $vers     = $self->vers();
    my $guid     = $self->guid();
    my $pid      = $self->pid();
    my $projroot = PROJROOT();
    my $logdir   = "$projroot/$pid/templates/logs";
472
    my $linkname = "$logdir/$prefix.${guid}-${vers}.log";
473

474
    return undef
475 476
	if (! -d $logdir && !mkdir($logdir, 0775));

477
    my $logname  = `mktemp $logdir/$prefix.${guid}-${vers}.XXXXXX`;
478 479 480
    return undef
	if ($?);
    chomp($logname);
481

482 483 484 485 486
    # Create a Logfile.
    my $logfile = Logfile->Create($self->gid_idx(), $logname);
    if (!defined($logfile)) {
	unlink($logname);
	return undef;
487
    }
488 489 490 491 492 493 494 495 496
    # This is untainted.
    $logname = $logfile->filename();

    unlink($linkname)
	if (-e $linkname);
    if (Template::mysystem("touch $logname")) {
	$logfile->Delete();
	unlink($logname);
	return undef;
497 498 499
    }
    if (! link($logname, $linkname)) {
	print STDERR "*** Cannot link $logname,$linkname: $!\n";
500 501 502
	$logfile->Delete();
	unlink($logname);
	return undef;
503
    }
504
    return $logfile;
505 506 507 508 509 510 511
}

#
# Set the experiment to use the logfile. It becomes the "current" spew.
#
sub SetLogFile($$)
{
512
    my ($self, $logfile) = @_;
513 514 515

    # Must be a real reference. 
    return -1
516
	if (! ref($self) || !ref($logfile));
517

518 519 520 521 522 523
    # Kill the old one. Eventually we will save them.
    my $oldlogfile = $self->GetLogFile();
    if (defined($oldlogfile)) {
	$oldlogfile->Delete();
    }
    return $self->Update({'logfile' => $logfile->logid()});
524 525 526 527 528
}

#
# Get the experiment logfile.
#
529
sub GetLogFile($)
530
{
531
    my ($self) = @_;
532 533

    # Must be a real reference. 
534
    return undef
535 536 537
	if (! ref($self));

    # Must do this to catch updates to the logfile variables.
538
    return undef
539 540
	if ($self->Refresh());

541
    return undef
542 543
	if (! $self->logfile());

544
    return Logfile->Lookup($self->logfile());
545 546 547 548 549 550 551 552 553 554 555 556 557
}

#
# Mark the log as open so that the spew keeps looking for more output.
# 
sub OpenLogFile($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

558 559 560 561 562
    my $logfile = $self->GetLogFile();
    return -1
	if (!defined($logfile));

    return $logfile->Open();
563 564 565 566 567 568 569 570 571 572 573 574 575
}

#
# And close it ...
#
sub CloseLogFile($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

576 577 578 579 580
    my $logfile = $self->GetLogFile();
    return -1
	if (!defined($logfile));

    return $logfile->Close();
581 582 583 584 585 586 587 588 589 590 591 592 593
}

#
# And clear it ...
#
sub ClearLogFile($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

594 595 596 597 598 599 600
    my $logfile = $self->GetLogFile();
    return -1
	if (!defined($logfile));

    $logfile->Delete() == 0
	or return -1;

601 602 603 604
    my $guid = $self->guid();
    my $vers = $self->vers();

    if (!DBQueryWarn("update experiment_templates set ".
605
		     "    logfile=NULL ".
606 607 608 609 610 611
		     "where guid='$guid' and vers='$vers'")) {
	return -1;
    }
    return $self->Refresh();
}

612
#
613
# Template permission checks. Using the experiment access check stuff.
614
#
615 616 617
# Usage: AccessCheck($guid, $uid, $access_type)
#	 returns 0 if not allowed.
#        returns 1 if allowed.
618
#
619
sub AccessCheck($$$;$)
620
{
621
    my ($self, $guid, $user, $access_type);
622 623 624 625 626 627
    my $mintrust;
    
    #
    # If called as a method, no guid argument is provided. 
    #
    $self = shift();
628

629
    if (ref($self)) {
630
	($user, $access_type) = @_;
631 632
    }
    else {
633
	($guid, $user, $access_type) = @_;
634

635 636 637 638 639 640 641 642 643
	$self = Template->Lookup($guid, 1);
	return 0
	    if (! $self);
    }
    
    if ($access_type < TB_EXPT_MIN ||
	$access_type > TB_EXPT_MAX) {
	tbdie("Invalid access type: $access_type!");
    }
644

645 646 647
    #
    # Admins do whatever they want!
    #
648
    if (TBAdmin()) {
649 650
	return 1;
    }
651

652 653 654 655 656 657 658 659 660 661
    #
    # Transition to using user objects instead of uids
    #
    if (! ref($user)) {
	my $uid = MapNumericUID($user);

	$user = User->Lookup($uid);
	return 0
	    if (! defined($user));
    }
662

663
    #
664
    # A template may be destroyed by the creator or the project/group leader.
665 666 667 668 669 670 671 672
    #
    if ($access_type == TB_EXPT_READINFO) {
	$mintrust = PROJMEMBERTRUST_USER;
    }
    else {
	$mintrust = PROJMEMBERTRUST_LOCALROOT;
    }

673 674 675 676 677 678 679
    #
    # Map to group object.
    #
    my $group = Group->Lookup($self->gid_idx());
    return 0
	if (!defined($group));

680 681 682 683 684
    #
    # Either proper permission in the group, or group_root in the project.
    # This lets group_roots muck with other people's experiments, including
    # those in groups they do not belong to.
    #
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
    my $membership = $group->LookupUser($user);
    return 1
	if (defined($membership) &&
	    TBMinTrust($membership->trust(), $mintrust));

    my $project = $group->GetProject();
    return 0
	if (!defined($project));

    $membership = $project->LookupUser($user);
    return 1
	if (defined($membership) &&
	    TBMinTrust($membership->trust(), PROJMEMBERTRUST_GROUPROOT));

    return 0;
700 701
}

702
#
703
# Return a list of all children of the given template.
704
#
705
sub Children($$)
706
{
707
    my ($self, $resultp) = @_;
708

709 710 711
    # Must be a real reference. 
    return -1
	if (! ref($self));
712

713 714 715 716 717 718 719 720 721 722
    my $guid      = $self->guid();
    my %children  = ();
    my @allkids   = ();
    my @kids      = ();
    my @result    = ();
    
    my $query_result =
	DBQueryWarn("select vers,parent_vers from experiment_templates ".
		    "where parent_guid='$guid' ".
		    "order by vers desc");
723
    return -1
724
	if (!$query_result);
725

726 727 728
    while (my ($vers, $parent_vers) = $query_result->fetchrow_array()) {
	$children{$parent_vers} = []
	    if (!exists($children{$parent_vers}));
729

730 731 732 733 734 735 736 737 738 739 740 741 742 743
	# List of all children for the parent.
	push(@{ $children{$parent_vers} }, $vers);
    }

    # Start with direct children of this template.
    unshift(@allkids, @{ $children{$self->vers()} })
	if (exists($children{$self->vers()}));

    # Descend the tree getting all children recursively.
    while (@allkids) {
	my $kid   = pop(@allkids);

	# New kid to return
	push(@kids, $kid);
744

745 746 747 748 749 750
	# New children of kid
	unshift(@allkids, @{ $children{$kid} })
	    if (exists($children{$kid}));
    }
    # Most recent templates first.
    @kids = sort {$b <=> $a} @kids;
751

752 753 754 755 756 757 758
    # Now convert to template objects.
    foreach my $vers (@kids) {
	my $template = Template->Lookup($guid, $vers);
	return -1
	    if (! $template);
	push(@result, $template);
    }
759

760
    @$resultp = @result;
761 762 763 764
    return 0;
}

#
765 766 767 768 769
# Add an input file to the template. The point of this is to reduce
# duplication by taking an md5 of the input file, and sharing that
# record/file.
# 
sub AddInputFile($$)
770
{
771 772
    my ($self, $inputfile) = @_;
    my $input_data_idx;
773

774 775 776
    # Must be a real reference. 
    return -1
	if (! ref($self));
777

778
    my $data_string = `cat $inputfile`;
779 780 781
    return -1
	if ($?);

782 783 784 785
    my $guid = $self->guid();
    my $vers = $self->vers();
    my $pid  = $self->pid();
    my $tid  = $self->tid();
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801

    if ($data_string) {
	# As you can see, we md5 the raw data.
	$data_string = DBQuoteSpecial($data_string);
	if (length($data_string) >= DBLIMIT_NSFILESIZE()) {
	    tberror("Input file is too big (> " . DBLIMIT_NSFILESIZE() . ")!");
	    return -1;
	}

	#
	# Grab an MD5 of the file to see if we already have a copy of it.
	# Avoids needless duplication.
	#
	my $md5 = `$MD5 -q $inputfile`;
	chomp($md5);

802 803 804 805
	DBQueryWarn("lock tables experiment_template_inputs write, ".
		    "            experiment_template_input_data write")
	    or return -1;

806 807 808 809
	my $query_result =
	    DBQueryWarn("select idx from experiment_template_input_data ".
			"where md5='$md5'");

810 811 812 813
	if (!$query_result) {
	    DBQueryWarn("unlock tables");
	    return -1;
	}
814 815

	if ($query_result->numrows) {
816
	    ($input_data_idx) = $query_result->fetchrow_array();
817 818 819 820 821 822 823
	}
	else {
	    $query_result =
		DBQueryWarn("insert into experiment_template_input_data ".
			    "(idx, md5, input) ".
			    "values (NULL, '$md5', $data_string)");
	    
824 825 826 827 828
	    if (!$query_result) {
		DBQueryWarn("unlock tables");
		return -1;
	    }
	    $input_data_idx = $query_result->insertid;
829 830
	}

831 832 833 834
	$query_result =
	    DBQueryWarn("insert into experiment_template_inputs ".
			" (idx, parent_guid, parent_vers, ".
			"  pid, tid, input_idx) values ".
835
			" (NULL, '$guid', '$vers', '$pid', '$tid', ".
836 837
			"  '$input_data_idx')");
	DBQueryWarn("unlock tables");
838
	return -1
839
	    if (!$query_result);
840 841 842 843
    }
    return 0;
}

844
#
845
# Delete all input files, say for a template create/modify that fails.
846
#
847
sub DeleteInputFiles($)
848
{
849
    my ($self) = @_;
850

851 852 853 854 855 856 857
    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $guid = $self->guid();
    my $vers = $self->vers();
    
858 859
    DBQueryWarn("lock tables experiment_template_inputs as i write, ".
		"            experiment_template_inputs as j write, ".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
860
		"            experiment_template_inputs write, ".
861 862 863 864 865 866 867 868 869 870 871 872 873 874
		"            experiment_template_input_data write")
	or return -1;

    #
    # The point of this query is to see if any of the input files in this
    # template are shared with some other template, and thus should not
    # be deleted from the input_data table.
    #
    my $query_result =
	DBQueryWarn("select i.idx,i.input_idx,count(j.input_idx) as count ".
		    "   from experiment_template_inputs as i ".
		    "left join experiment_template_inputs as j on ".
		    "     j.input_idx=i.input_idx ".
		    "where i.parent_guid='$guid' and ".
875
		    "      i.parent_vers='$vers' ".
876 877 878 879 880 881 882 883 884 885 886 887 888
		    "group by j.input_idx having count > 1");

    if (! $query_result) {
	DBQueryWarn("unlock tables");
	return -1;
    }

    while (my ($input_idx, $data_idx) = $query_result->fetchrow_array()) {
	DBQueryWarn("delete from experiment_template_input_data ".
		    "where idx='$data_idx'");
    }
    $query_result = 
	DBQueryWarn("delete from experiment_template_inputs ".
889
		    "where parent_guid='$guid' and parent_vers='$vers'");
890 891 892 893 894 895 896 897
    DBQueryWarn("unlock tables");
    
    return -1
	if (! $query_result);

    return 0;
}

898
#
899
# Add a metadata record. 
900
#
901
sub NewMetadata($$$$;$)
902
{
903
    my ($self, $name, $value, $creator, $type) = @_;
904
    my $guid;
905 906
    my $version  = 1;
    my $internal = 0;
907
    my $metadata_type;
908

909
    # Must be a real reference. 
910
    return -1
911 912 913 914
	if (! ref($self));

    my $template_guid = $self->guid();
    my $template_vers = $self->vers();
915 916
    my $creator_uid   = $creator->uid();
    my $creator_dbid  = $creator->uid_idx();
917 918 919 920 921 922

    return -1
	if (NewGUID(\$guid) < 0);

    # Special ...
    $internal = 1
923
	if (defined($type));
924

925
    # Current set of allowed types;
926
    my @okay_types = ("tid", "template_description", "parameter_description",
927
		      "annotation", "instance_description", "run_description");
928 929 930 931 932 933 934 935 936 937 938 939 940

    if (defined($type)) {
	if (! grep {$_ eq $type} @okay_types) {
	    tberror("Illegal metadata type: $type");
	    return -1;
	}
	$metadata_type = "'$type'";
    }
    else {
	$metadata_type = "NULL";
    }

    my $safename  = DBQuoteSpecial($name);
941 942
    # HTML entity encode; yep, plain text only.
    my $safevalue = DBQuoteSpecial(encode_entities($value));
943 944 945

    my $query_result =
	DBQueryWarn("insert into experiment_template_metadata_items set ".
946 947
		    "   guid='$guid', vers='$version', ".
		    "   uid='$creator_uid', uid_idx='$creator_dbid', ".
948
		    "   template_guid='$template_guid', ".
949
		    "   name=$safename, value=$safevalue, created=now()");
950 951 952 953 954
    return -1
	if (!$query_result);

    DBQueryWarn("insert into experiment_template_metadata set ".
		"   parent_guid='$template_guid', ".
955
		"   parent_vers='$template_vers', ".
956 957
		"   metadata_guid='$guid', ".
		"   metadata_vers='$version', ".
958
		"   metadata_type=$metadata_type, ".
959
		"   internal=$internal")
960
	or return -1;
961 962 963 964

    # Some metadata is special ...
    if (defined($type)) {
	if ($type eq "parameter_description") {
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
	    DBQueryWarn("update experiment_template_parameters set ".
			"   metadata_guid='$guid', ".
			"   metadata_vers='$version' ".
			"where parent_guid='$template_guid' and ".
			"      parent_vers='$template_vers' and ".
			"      name=$safename")
		or return -1;
 	}
	elsif ($type eq "instance_description" &&
	       $name =~ /^__instance_description_(\d*)$/) {
	    my $exptidx = $1;
	    
	    DBQueryWarn("update experiment_template_instances set ".
			"  description=$safevalue ".
			"where exptidx='$exptidx'")
		or return -1;
	}
	elsif ($type eq "run_description" &&
	       $name =~ /^__run_description_(\d*)_(\d*)$/) {
	    my $exptidx = $1;
	    my $runidx  = $2;
	    
	    DBQueryWarn("update experiment_runs set ".
			"  description=$safevalue ".
			"where exptidx='$exptidx' and idx='$runidx'")
		or return -1;
991 992
	}
    }
993 994 995 996
    
    return 0;
}

997 998 999
#
# Lookup a metadata value by name, optionally returning guid/vers.
#
1000
sub LookupMetadata($$;$$$)
1001
{
1002
    my ($self, $name, $pguid, $pvers, $ptype) = @_;
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $template_guid = $self->guid();
    my $template_vers = $self->vers();

    $name = DBQuoteSpecial($name);

    my $query_result =
1014
	DBQueryWarn("select metadata_guid,metadata_vers,metadata_type ".
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
		    "   from experiment_template_metadata as m ".
		    "left join experiment_template_metadata_items as i on ".
		    "     m.metadata_guid=i.guid and m.metadata_vers=i.vers ".
		    "where m.parent_guid='$template_guid' and ".
		    "      m.parent_vers='$template_vers' and ".
		    "      i.name=$name");
    
    return -1
	if (!$query_result);
    return 0
	if (!$query_result->numrows);

1027 1028
    my ($metadata_guid, $metadata_vers, $metadata_type) =
	$query_result->fetchrow_array();
1029 1030 1031 1032
    $$pguid = $metadata_guid
	if (defined($pguid));
    $$pvers = $metadata_vers
	if (defined($pvers));
1033 1034
    $$ptype = $metadata_type
	if (defined($ptype));
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
    
    return 1;
}

#
# Modify a metadata record; these are versioned of course.
#
sub ModifyMetadata($$$$)
{
    my ($self, $name, $value, $creator) = @_;
    my $guid;
    my $version = 1;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $template_guid = $self->guid();
    my $template_vers = $self->vers();
1054 1055
    my $creator_uid   = $creator->uid();
    my $creator_dbid  = $creator->uid_idx();
1056 1057
    my $parent_guid;
    my $parent_vers;
1058
    my $metadata_type;
1059
    my $already_exists =
1060 1061
	$self->LookupMetadata($name,
			      \$parent_guid, \$parent_vers, \$metadata_type);
1062 1063 1064
    return -1
	if ($already_exists <= 0);

1065 1066
    my $safename  = DBQuoteSpecial($name);
    my $safevalue = DBQuoteSpecial(encode_entities($value));
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086

    DBQueryWarn("lock tables experiment_template_metadata_items write")
	or return -1;
    
    my $query_result =
	DBQueryWarn("select MAX(vers) ".
		    " from experiment_template_metadata_items ".
		    "where guid='$parent_guid'");
    if (!$query_result) {
	DBQueryWarn("unlock tables");
	return -1;
    }
    my ($metadata_vers) = $query_result->fetchrow_array();
    $metadata_vers++;

    #
    # Insert new item.
    #
    if (!DBQueryWarn("insert into experiment_template_metadata_items set ".
		     "     guid='$parent_guid',vers='$metadata_vers', ".
1087 1088
		     "     template_guid='$template_guid', ".
		     "     uid='$creator_uid', uid_idx='$creator_dbid', ".
1089 1090
		     "     parent_guid='$parent_guid',".
		     "     parent_vers='$parent_vers'," .
1091
		     "     name=$safename, value=$safevalue, created=now()")) {
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
	DBQueryWarn("unlock tables");
	return -1;
    }
    DBQueryWarn("unlock tables");

    if (!DBQueryWarn("update experiment_template_metadata ".
		     "  set metadata_vers='$metadata_vers' ".
		     "where metadata_guid='$parent_guid' and ".
		     "      metadata_vers='$parent_vers'")) {
	DBQueryWarn("delete from experiment_template_metadata_items ".
		    "where guid='$parent_guid',vers='$metadata_vers'");
	return -1;
    }

    #
    # XXX Some metadata is special ...
    #
1109 1110
    if (defined($metadata_type)) {
	if ($metadata_type eq "tid") {
1111
	    DBQueryWarn("update experiment_templates set tid=$safevalue ".
1112 1113 1114 1115 1116 1117
			"where guid='$template_guid' and ".
			"      vers='$template_vers'")
		or return -1;
	    
	    Refresh($self);
	    # This can fail; it is not critical.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1118
	    Template::mysystem("$makegraph $template_guid");
1119 1120
	}
	elsif ($metadata_type eq "template_description") {
1121 1122
	    DBQueryWarn("update experiment_templates set ".
			"   description=$safevalue ".
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
			"where guid='$template_guid' and ".
			"      vers='$template_vers'")
		or return -1;
	    
	    Refresh($self);	
	}
	elsif ($metadata_type eq "parameter_description") {
	    DBQueryWarn("update experiment_template_parameters set ".
			"   metadata_guid='$parent_guid', ".
			"   metadata_vers='$metadata_vers' ".
1133 1134
			"where parent_guid='$template_guid' and ".
			"      parent_vers='$template_vers' and ".
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
			"      name=$safename")
		or return -1;
	}
	elsif ($metadata_type eq "instance_description" &&
	       $name =~ /^__instance_description_(\d*)$/) {
	    my $exptidx = $1;
	    
	    DBQueryWarn("update experiment_template_instances set ".
			"  description=$safevalue ".
			"where exptidx='$exptidx'")
		or return -1;
	}
	elsif ($metadata_type eq "run_description" &&
	       $name =~ /^__run_description_(\d*)_(\d*)$/) {
	    my $exptidx = $1;
	    my $runidx  = $2;
	    
	    DBQueryWarn("update experiment_runs set ".
			"  description=$safevalue ".
			"where exptidx='$exptidx' and idx='$runidx'")
		or return -1;
1156
	}
1157 1158 1159 1160 1161
    }
    return 0;
}

#
1162
# Add a formal parameter to a template.
1163
#
1164
sub NewFormalParameter($$$$$)
1165
{
1166
    my ($self, $name, $value, $description, $user) = @_;
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $template_guid = $self->guid();
    my $template_vers = $self->vers();
    my $pid = $self->pid();
    my $tid = $self->tid();

    if (defined($value)) {
      $value = DBQuoteSpecial($value);
    }
    else {
      $value = "NULL";
    }

    DBQueryWarn("insert into experiment_template_parameters set ".
		"  parent_guid='$template_guid', ".
		"  parent_vers='$template_vers', ".
		"  pid='$pid', tid='$tid', ".
		"  name='$name', value=$value")
	or return -1;

1191 1192
    if (defined($description) && $description ne "") {
	$self->NewMetadata($name,
1193
			   $description, $user, "parameter_description")
1194 1195 1196
	    == 0 or return -1;
    }

1197 1198 1199
    return 0;
}

1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
#
# Get list of template formal parameters.
#
sub FormalParameterList($$)
{
    my ($self, $prval) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my %results = ();
    my $template_guid = $self->guid();
    my $template_vers = $self->vers();

    my $query_result =
	DBQueryWarn("select name,value from experiment_template_parameters ".
		    "where parent_guid='$template_guid' and ".
		    "      parent_vers='$template_vers'");

    return -1
	if (!$query_result);

    while (my ($name,$value) = $query_result->fetchrow_array()) {
	$results{$name} = $value;
    }
    %$prval = %results;
    return 0;
}

1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
#
# Get description for formal parameters; this needs to be its own object.
#
sub FormalParameterDescription($$)
{
    my ($self, $name, $prval) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $result = undef;
    my $template_guid = $self->guid();
    my $template_vers = $self->vers();
    $name = DBQuoteSpecial($name);

    my $query_result =
	DBQueryWarn("select m.value from experiment_template_parameters as p ".
		    "left join experiment_template_metadata_items as m on ".
		    "     m.guid=p.metadata_guid and m.vers=p.metadata_vers ".
		    "where p.parent_guid='$template_guid' and ".
		    "      p.parent_vers='$template_vers' and ".
		    "      p.name=$name");

    return -1
	if (!$query_result);

    if ($query_result->numrows) {
	($result) = $query_result->fetchrow_array();
    }
    $$prval = $result;
    return 0;
}

1264
#
1265
# Delete (all) template metadata
1266
#
1267
sub DeleteAllMetadata($)
1268
{
1269 1270 1271 1272 1273 1274 1275 1276
    my ($self) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $template_guid = $self->guid();
    my $template_vers = $self->vers();
1277 1278 1279 1280 1281

    my $query_result =
	DBQueryWarn("select metadata_guid ".
		    "    from experiment_template_metadata ".
		    "where parent_guid='$template_guid' and ".
1282
		    "      parent_vers='$template_vers'");
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315

    return -1
	if (!$query_result);

    while (my ($metadata_guid) = $query_result->fetchrow_array()) {
	my @versions = ();

	#
	# Delete all versions for each record. This is wrong if we ever
	# want to share entries between templates.
	#
	my $metadata_result =
	    DBQueryWarn("select vers from experiment_template_metadata_items ".
			"where guid='$metadata_guid'");

	return -1
	    if (!$metadata_result);

	next
	    if (!$metadata_result->numrows);

	while (my ($metadata_vers) = $metadata_result->fetchrow_array()) {
	    push(@versions, $metadata_vers);
	}

	my $clause = join(" or ", map("vers='$_'", @versions));

	DBQueryWarn("delete from experiment_template_metadata_items ".
		    "where guid='$metadata_guid' and ($clause)")
	    or return -1;
    }
    DBQueryWarn("delete from experiment_template_metadata ".
		"where parent_guid='$template_guid' and ".
1316
		"      parent_vers='$template_vers'")
1317 1318 1319 1320 1321
	or return -1;

    return 0;
}

1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
#
# Delete a specific template metadata item from the template, but we leave
# actual items behind. 
#
sub DeleteMetadata($$)
{
    my ($self, $name) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $template_guid = $self->guid();
    my $template_vers = $self->vers();
    $name = DBQuoteSpecial($name);

    my $query_result =
	DBQueryWarn("select metadata_guid,metadata_vers ".
		    "   from experiment_template_metadata as m ".
		    "left join experiment_template_metadata_items as i on ".
		    "     m.metadata_guid=i.guid and m.metadata_vers=i.vers ".
		    "where m.parent_guid='$template_guid' and ".
		    "      m.parent_vers='$template_vers' and ".
		    "      i.name=$name");
    
    return -1
	if (!$query_result);
    return -1
	if (!$query_result->numrows);

    my ($metadata_guid, $metadata_vers) = $query_result->fetchrow_array();
    
    DBQueryWarn("update experiment_template_metadata set hidden=1 ".
		"where parent_guid='$template_guid' and ".
		"      parent_vers='$template_vers' and ".
		"      metadata_guid='$metadata_guid' and ".
		"      metadata_vers='$metadata_vers'")
	or return -1;

    return 0;
}

1364 1365 1366 1367
#
# Copy exiting template metadata to a child. This is likely to change
# since we probably want to share at some point.
#
1368
sub CopyMetadata($$$)
1369
{
1370
    my ($self, $parent, $copier) = @_;
1371 1372 1373

    # Must be a real reference. 
    return -1
1374
	if (! (ref($self) && ref($parent)));