Template.pm.in 81.8 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
use Experiment;
25
use English;
26
use HTML::Entities;
27
use overload ('""' => 'Stringify');
28 29 30

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

42 43
# Cache of template instances to avoid regenerating them.
my %templates   = ();
44
my $debug	= 1;
45

46 47 48 49
# Flags for functions below.
sub STARTRUN_FLAGS_FIRSTRUN()	{ 0x1 ;}
sub STARTRUN_FLAGS_SWAPMOD()	{ 0x2 ;}

50 51 52 53 54 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
#
# 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
84 85 86 87 88 89 90 91 92 93
# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

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

94
#
95
# Lookup a template and create a class instance to return.
96
#
97
sub Lookup($$$)
98
{
99
    my ($class, $guid, $vers) = @_;
100

101 102 103 104
    # Look in cache first
    return $templates{"$guid/$vers"}
        if (exists($templates{"$guid/$vers"}));
    
105
    my $query_result =
106 107
	DBQueryWarn("select * from experiment_templates ".
		    "where guid='$guid' and vers='$vers'");
108

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

112 113 114 115 116
    my $self             = {};
    $self->{'TEMPLATE'}  = $query_result->fetchrow_hashref();
    # Filled lazily.
    $self->{'INSTANCES'} = undef;
    bless($self, $class);
117
    
118 119 120 121
    # Add to cache. 
    $templates{"$guid/$vers"} = $self;
    
    return $self;
122
}
123 124 125 126 127 128 129
# 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'}); }
sub gid($)  { return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'gid'}); }
sub eid($)  { return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'eid'}); }
sub tid($)  { return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'tid'}); }
130
sub path($) { return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'path'}); }
131 132
sub archive_idx($) {
    return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'archive_idx'}); }
133 134 135 136
sub parent_guid($) {
    return ((! ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}->{'parent_guid'}); }
sub IsRoot($) {
    return ! defined($_[0]->{'TEMPLATE'}->{'parent_guid'}); }
137 138 139 140 141 142
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'}); }
143 144

#
145
# Lookup a template given an experiment index.
146
#
147
sub LookupByExptidx($$)
148
{
149
    my ($class, $exptidx) = @_;
150

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

154 155
    return undef
	if (!defined($template_instance));
156

157
    return $template_instance->template();
158 159
}

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
#
# 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);
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
180
#
181
# Refresh a template instance by reloading from the DB.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
182
#
183
sub Refresh($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
184
{
185
    my ($self) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
186

187 188
    return -1
	if (! ref($self));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
189

190 191 192 193 194 195
    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
196 197

    return -1
198 199 200
	if (!$query_result || !$query_result->numrows);
	
    $self->{'TEMPLATE'} = $query_result->fetchrow_hashref();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
201 202 203
    return 0;
}

204
#
205 206
# Create a new template. This installs the new record in the DB,
# and returns an instance. There is some bookkeeping along the way.
207
#
208
sub Create($$)
209
{
210 211
    my ($class, $argref) = @_;
    my ($guid, $vers);
212

213 214
    return undef
	if (ref($class));
215

216 217 218 219 220 221 222 223 224 225 226 227 228
    # 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;
229 230
    }

231 232 233
    DBQueryWarn("lock tables experiments write, ".
		"            experiment_templates write")
	or return undef;
234

235 236 237 238 239 240 241
    #
    # 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'");
242

243 244 245 246
	if (!$query_result) {
	    DBQueryWarn("unlock tables");
	    return undef;
	}
247

248 249 250
	$vers = ($query_result->fetchrow_array())[0];
	$vers++;
    }
251

252 253 254 255
    # 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}";
    my $pid = $argref->{'pid'};
256

257
    #
258
    # Sanity check; make sure this eid is not in use. Tables are still locked.
259 260
    #
    my $query_result =
261 262
	DBQueryWarn("select pid,eid from experiments ".
		    "where eid='$eid' and pid='$pid'");
263

264 265 266 267 268 269 270 271 272
    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;
273 274
    }

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

278 279
    # Append the rest
    $query .= ",created=now(),guid='$guid',vers='$vers',eid='$eid'";
280

281 282 283 284 285 286 287
    if (! DBQueryWarn($query)) {
	DBQueryWarn("unlock tables");
	return undef;
    }
    DBQueryWarn("unlock tables");

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

#
291
# Stringify for output.
292
#
293
sub Stringify($)
294
{
295 296 297
    my ($self) = @_;
    my $guid   = $self->guid();
    my $vers   = $self->vers();
298

299
    return "[Template: $guid/$vers]";
300 301
}

302
#
303
# Update a template record given an array reference of slot/value pairs.
304
#
305
sub Update($$)
306
{
307
    my ($self, $argref) = @_;
308

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

313 314
    my $guid = $self->guid();
    my $vers = $self->vers();
315

316 317 318 319
    my $query = "update experiment_templates set ".
	join(",", map("$_='" . $argref->{$_} . "'", keys(%{$argref})));

    $query .= " where guid='$guid' and vers='$vers'";
320 321 322

    return -1
	if (! DBQueryWarn($query));
323 324

    return Refresh($self);
325 326
}

327
#
328 329
# Delete a template (all tables). Note that other parts of the template
# like instances must already be gone when this is called.
330
#
331
sub Delete($)
332
{
333
    my ($self) = @_;
334

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

339 340
    my $guid = $self->guid();
    my $vers = $self->vers();
341 342 343 344 345 346
    my $path = $self->path();

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

348
    DeleteAllMetadata($self) == 0
349
	or return -1;
350

351 352
    DeleteInputFiles($self) == 0
	or return -1;
353

354 355 356 357
    # 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'");
358 359 360
    return -1
	if (! $query_result);

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    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;
385 386 387
    return 0;
}

388
#
389
# Template permission checks. Using the experiment access check stuff.
390
#
391 392 393
# Usage: AccessCheck($guid, $uid, $access_type)
#	 returns 0 if not allowed.
#        returns 1 if allowed.
394
#
395
sub AccessCheck($$$;$)
396
{
397 398 399 400 401 402 403
    my ($self, $guid, $uid, $access_type);
    my $mintrust;
    
    #
    # If called as a method, no guid argument is provided. 
    #
    $self = shift();
404

405 406 407 408 409
    if (ref($self)) {
	($uid, $access_type) = @_;
    }
    else {
	($guid, $uid, $access_type) = @_;
410

411 412 413 414 415 416 417 418 419
	$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!");
    }
420

421 422 423 424 425 426 427
    #
    # Admins do whatever they want!
    #
    if (TBAdmin($uid)) {
	return 1;
    }
    $uid = MapNumericUID($uid);
428

429 430
    my $pid = $self->pid();
    my $gid = $self->gid();
431

432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
    #
    # An experiment may be destroyed by the experiment creator or the
    # project/group leader.
    #
    if ($access_type == TB_EXPT_READINFO) {
	$mintrust = PROJMEMBERTRUST_USER;
    }
    else {
	$mintrust = PROJMEMBERTRUST_LOCALROOT;
    }

    #
    # 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.
    #
    return TBMinTrust(TBGrpTrust($uid, $pid, $gid), $mintrust) ||
	TBMinTrust(TBGrpTrust($uid, $pid, $pid), PROJMEMBERTRUST_GROUPROOT);
450 451
}

452
#
453
# Return a list of all children of the given template.
454
#
455
sub Children($$)
456
{
457
    my ($self, $resultp) = @_;
458

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

463 464 465 466 467 468 469 470 471 472
    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");
473
    return -1
474
	if (!$query_result);
475

476 477 478
    while (my ($vers, $parent_vers) = $query_result->fetchrow_array()) {
	$children{$parent_vers} = []
	    if (!exists($children{$parent_vers}));
479

480 481 482 483 484 485 486 487 488 489 490 491 492 493
	# 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);
494

495 496 497 498 499 500
	# New children of kid
	unshift(@allkids, @{ $children{$kid} })
	    if (exists($children{$kid}));
    }
    # Most recent templates first.
    @kids = sort {$b <=> $a} @kids;
501

502 503 504 505 506 507 508
    # Now convert to template objects.
    foreach my $vers (@kids) {
	my $template = Template->Lookup($guid, $vers);
	return -1
	    if (! $template);
	push(@result, $template);
    }
509

510
    @$resultp = @result;
511 512 513 514
    return 0;
}

#
515 516 517 518 519
# 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($$)
520
{
521 522
    my ($self, $inputfile) = @_;
    my $input_data_idx;
523

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

528
    my $data_string = `cat $inputfile`;
529 530 531
    return -1
	if ($?);

532 533 534 535
    my $guid = $self->guid();
    my $vers = $self->vers();
    my $pid  = $self->pid();
    my $tid  = $self->tid();
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551

    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);

552 553 554 555
	DBQueryWarn("lock tables experiment_template_inputs write, ".
		    "            experiment_template_input_data write")
	    or return -1;

556 557 558 559
	my $query_result =
	    DBQueryWarn("select idx from experiment_template_input_data ".
			"where md5='$md5'");

560 561 562 563
	if (!$query_result) {
	    DBQueryWarn("unlock tables");
	    return -1;
	}
564 565

	if ($query_result->numrows) {
566
	    ($input_data_idx) = $query_result->fetchrow_array();
567 568 569 570 571 572 573
	}
	else {
	    $query_result =
		DBQueryWarn("insert into experiment_template_input_data ".
			    "(idx, md5, input) ".
			    "values (NULL, '$md5', $data_string)");
	    
574 575 576 577 578
	    if (!$query_result) {
		DBQueryWarn("unlock tables");
		return -1;
	    }
	    $input_data_idx = $query_result->insertid;
579 580
	}

581 582 583 584
	$query_result =
	    DBQueryWarn("insert into experiment_template_inputs ".
			" (idx, parent_guid, parent_vers, ".
			"  pid, tid, input_idx) values ".
585
			" (NULL, '$guid', '$vers', '$pid', '$tid', ".
586 587
			"  '$input_data_idx')");
	DBQueryWarn("unlock tables");
588
	return -1
589
	    if (!$query_result);
590 591 592 593
    }
    return 0;
}

594
#
595
# Delete all input files, say for a template create/modify that fails.
596
#
597
sub DeleteInputFiles($)
598
{
599
    my ($self) = @_;
600

601 602 603 604 605 606 607
    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $guid = $self->guid();
    my $vers = $self->vers();
    
608 609
    DBQueryWarn("lock tables experiment_template_inputs as i write, ".
		"            experiment_template_inputs as j write, ".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
610
		"            experiment_template_inputs write, ".
611 612 613 614 615 616 617 618 619 620 621 622 623 624
		"            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 ".
625
		    "      i.parent_vers='$vers' ".
626 627 628 629 630 631 632 633 634 635 636 637 638
		    "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 ".
639
		    "where parent_guid='$guid' and parent_vers='$vers'");
640 641 642 643 644 645 646 647
    DBQueryWarn("unlock tables");
    
    return -1
	if (! $query_result);

    return 0;
}

648
#
649
# Add a metadata record. 
650
#
651
sub NewMetadata($$$$;$)
652
{
653
    my ($self, $name, $value, $creator, $type) = @_;
654
    my $guid;
655 656
    my $version  = 1;
    my $internal = 0;
657
    my $metadata_type;
658

659
    # Must be a real reference. 
660
    return -1
661 662 663 664
	if (! ref($self));

    my $template_guid = $self->guid();
    my $template_vers = $self->vers();
665 666
    my $creator_uid   = $creator->uid();
    my $creator_dbid  = $creator->uid_idx();
667 668 669 670 671 672

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

    # Special ...
    $internal = 1
673
	if (defined($type));
674

675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
    # Current set of allowed types;
    my @okay_types = ("tid", "template_description", "parameter_description");

    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);
690 691
    # HTML entity encode; yep, plain text only.
    my $safevalue = DBQuoteSpecial(encode_entities($value));
692 693 694

    my $query_result =
	DBQueryWarn("insert into experiment_template_metadata_items set ".
695 696
		    "   guid='$guid', vers='$version', ".
		    "   uid='$creator_uid', uid_idx='$creator_dbid', ".
697
		    "   template_guid='$template_guid', ".
698
		    "   name=$safename, value=$safevalue, created=now()");
699 700 701 702 703
    return -1
	if (!$query_result);

    DBQueryWarn("insert into experiment_template_metadata set ".
		"   parent_guid='$template_guid', ".
704
		"   parent_vers='$template_vers', ".
705 706
		"   metadata_guid='$guid', ".
		"   metadata_vers='$version', ".
707
		"   metadata_type=$metadata_type, ".
708
		"   internal=$internal")
709
	or return -1;
710 711 712 713 714 715 716 717

    # Some metadata is special ...
    if (defined($type)) {
	if ($type eq "parameter_description") {
	    $query_result =
		DBQueryWarn("update experiment_template_parameters set ".
			    "   metadata_guid='$guid', ".
			    "   metadata_vers='$version' ".
718 719 720
			    "where parent_guid='$template_guid' and ".
			    "      parent_vers='$template_vers' and ".
			    "      name=$safename");
721 722 723 724
	    return -1
		if (!$query_result);
	}
    }
725 726 727 728
    
    return 0;
}

729 730 731
#
# Lookup a metadata value by name, optionally returning guid/vers.
#
732
sub LookupMetadata($$;$$$)
733
{
734
    my ($self, $name, $pguid, $pvers, $ptype) = @_;
735 736 737 738 739 740 741 742 743 744 745

    # 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 =
746
	DBQueryWarn("select metadata_guid,metadata_vers,metadata_type ".
747 748 749 750 751 752 753 754 755 756 757 758
		    "   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);

759 760
    my ($metadata_guid, $metadata_vers, $metadata_type) =
	$query_result->fetchrow_array();
761 762 763 764
    $$pguid = $metadata_guid
	if (defined($pguid));
    $$pvers = $metadata_vers
	if (defined($pvers));
765 766
    $$ptype = $metadata_type
	if (defined($ptype));
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
    
    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();
786 787
    my $creator_uid   = $creator->uid();
    my $creator_dbid  = $creator->uid_idx();
788 789
    my $parent_guid;
    my $parent_vers;
790
    my $metadata_type;
791
    my $already_exists =
792 793
	$self->LookupMetadata($name,
			      \$parent_guid, \$parent_vers, \$metadata_type);
794 795 796 797
    return -1
	if ($already_exists <= 0);

    $name  = DBQuoteSpecial($name);
798
    $value = DBQuoteSpecial(encode_entities($value));
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818

    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', ".
819 820
		     "     template_guid='$template_guid', ".
		     "     uid='$creator_uid', uid_idx='$creator_dbid', ".
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
		     "     parent_guid='$parent_guid',".
		     "     parent_vers='$parent_vers'," .
		     "     name=$name, value=$value, created=now()")) {
	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 ...
    #
841 842 843 844 845 846 847 848 849
    if (defined($metadata_type)) {
	if ($metadata_type eq "tid") {
	    DBQueryWarn("update experiment_templates set tid=$value ".
			"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
850
	    Template::mysystem("$makegraph $template_guid");
851 852 853 854 855 856 857 858 859 860 861 862 863
	}
	elsif ($metadata_type eq "template_description") {
	    DBQueryWarn("update experiment_templates set description=$value ".
			"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' ".
864 865 866
			"where parent_guid='$template_guid' and ".
			"      parent_vers='$template_vers' and ".
			"      name=$name")
867 868
		or return -1
	}
869 870 871 872 873
    }
    return 0;
}

#
874
# Add a formal parameter to a template.
875
#
876
sub NewFormalParameter($$$$$)
877
{
878
    my ($self, $name, $value, $description, $user) = @_;
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902

    # 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;

903 904
    if (defined($description) && $description ne "") {
	$self->NewMetadata($name,
905
			   $description, $user, "parameter_description")
906 907 908
	    == 0 or return -1;
    }

909 910 911
    return 0;
}

912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
#
# 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;
}

942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
#
# 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;
}

976
#
977
# Delete (all) template metadata
978
#
979
sub DeleteAllMetadata($)
980
{
981 982 983 984 985 986 987 988
    my ($self) = @_;

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

    my $template_guid = $self->guid();
    my $template_vers = $self->vers();
989 990 991 992 993

    my $query_result =
	DBQueryWarn("select metadata_guid ".
		    "    from experiment_template_metadata ".
		    "where parent_guid='$template_guid' and ".
994
		    "      parent_vers='$template_vers'");
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027

    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 ".
1028
		"      parent_vers='$template_vers'")
1029 1030 1031 1032 1033
	or return -1;

    return 0;
}

1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
#
# 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;
}

1076 1077 1078 1079
#
# Copy exiting template metadata to a child. This is likely to change
# since we probably want to share at some point.
#
1080
sub CopyMetadata($$$)
1081
{
1082
    my ($self, $parent, $copier) = @_;
1083 1084 1085

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

1088 1089 1090
    my $from_guid = $parent->guid();
    my $from_vers = $parent->vers();
    my $to_vers   = $self->vers();
1091 1092
    my $copier_uid  = $copier->uid();
    my $copier_dbid = $copier->uid_idx();
1093 1094 1095 1096 1097

    #
    # Copy the toplevel items.
    #
    my $query_result =
1098
	DBQueryWarn("select name,value,metadata_type,internal,i.parent_guid ".
1099 1100 1101 1102 1103
		    "  from experiment_template_metadata as m ".
		    "left join experiment_template_metadata_items as i on ".
		    "     i.guid=m.metadata_guid and ".
		    "     i.vers=m.metadata_vers ".
		    "where m.parent_guid='$from_guid' and ".
1104
		    "      m.parent_vers='$from_vers'")
1105 1106
	or return -1;

1107
    while (my ($name,$value,$type,$internal,$hasparent) =
1108 1109
	   $query_result->fetchrow_array()) {

1110 1111
	my $guid;
	my $version = 1;
1112
	my $metadata_type = "NULL";
1113 1114
	my $parent_guid;
	my $parent_vers;
1115 1116 1117 1118
	
	$name   = DBQuoteSpecial($name);
	$value  = DBQuoteSpecial($value);

1119 1120 1121 1122 1123 1124 1125 1126
	#
	# XXX Some metadata is special ...
	#
	if (defined($type)) {
	    # XXX Skip the tid and template descriptions.
	    next
		if ($type eq "tid" or $type eq "template_description");

1127 1128 1129 1130
	    #
	    # XXX Skip parameters that were deleted or whose description
	    # was modified after being created.
	    #
1131 1132 1133 1134
	    if ($type eq "parameter_description") {
		my $param_result = 
		    DBQueryWarn("select * ".
				"   from experiment_template_parameters ".
1135 1136 1137
				"where parent_guid='$from_guid' and ".
				"      parent_vers='$to_vers' and ".
				"      name=$name");
1138 1139 1140 1141 1142 1143

		return -1
		    if (!$param_result);
		
		next
		    if (!$param_result->numrows);
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167

		#
		# If the current parameter has a metadata description, it
		# came from the NS file parse. If the version we are
		# copying from has no parent, it has not been modified and
		# so we do not want to take that one; use the current one
		# from the NS file instead. If on the other hand the user
		# modified that description after its NS file parse, we take
		# that since we assume its a better description. Hmm, this
		# sounds awful when described.
		#
		my $param_row = $param_result->fetchrow_hashref();

		if (defined($param_row->{"metadata_guid"})) {
		    next
			if (! $hasparent);
		    
		    $parent_guid = $param_row->{"metadata_guid"};
		    $parent_vers = $param_row->{"metadata_vers"};

		    # and of course we need to use this guid/vers.
		    $guid = $parent_guid;
		    $version = $parent_vers + 1;
		}
1168 1169 1170 1171
	    }
	    $metadata_type = "'$type'";
	}

1172
	return -1
1173
	    if (!defined($guid) && NewGUID(\$guid) < 0);</