Template.pm.in 79.8 KB
Newer Older
1 2 3 4 5 6 7 8
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
# Copyright (c) 2005, 2006 University of Utah and the Flux Group.
# 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 Experiment;
24
use English;
25
use overload ('""' => 'Stringify');
26 27 28

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

39 40
# Cache of template instances to avoid regenerating them.
my %templates   = ();
41
my $debug	= 1;
42

43 44 45 46
# Flags for functions below.
sub STARTRUN_FLAGS_FIRSTRUN()	{ 0x1 ;}
sub STARTRUN_FLAGS_SWAPMOD()	{ 0x2 ;}

47 48 49 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
#
# 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 Stoller's avatar
Leigh Stoller committed
81 82 83 84 85 86 87 88 89 90
# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

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

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

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

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

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

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

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

151 152
    return undef
	if (!defined($template_instance));
153

154
    return $template_instance->template();
155 156
}

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

177
#
178
# Refresh a template instance by reloading from the DB.
179
#
180
sub Refresh($)
181
{
182
    my ($self) = @_;
183

184 185
    return -1
	if (! ref($self));
186

187 188 189 190 191 192
    my $guid = $self->guid();
    my $vers = $self->vers();
    
    my $query_result =
	DBQueryWarn("select * from experiment_templates ".
		    "where guid='$guid' and vers='$vers'");
193 194

    return -1
195 196 197
	if (!$query_result || !$query_result->numrows);
	
    $self->{'TEMPLATE'} = $query_result->fetchrow_hashref();
198 199 200
    return 0;
}

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

210 211
    return undef
	if (ref($class));
212

213 214 215 216 217 218 219 220 221 222 223 224 225
    # 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;
226 227
    }

228 229 230
    DBQueryWarn("lock tables experiments write, ".
		"            experiment_templates write")
	or return undef;
231

232 233 234 235 236 237 238
    #
    # 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'");
239

240 241 242 243
	if (!$query_result) {
	    DBQueryWarn("unlock tables");
	    return undef;
	}
244

245 246 247
	$vers = ($query_result->fetchrow_array())[0];
	$vers++;
    }
248

249 250 251 252
    # 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'};
253

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

261 262 263 264 265 266 267 268 269
    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;
270 271
    }

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

275 276
    # Append the rest
    $query .= ",created=now(),guid='$guid',vers='$vers',eid='$eid'";
277

278 279 280 281 282 283 284
    if (! DBQueryWarn($query)) {
	DBQueryWarn("unlock tables");
	return undef;
    }
    DBQueryWarn("unlock tables");

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

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

296
    return "[Template: $guid/$vers]";
297 298
}

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

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

310 311
    my $guid = $self->guid();
    my $vers = $self->vers();
312

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

    $query .= " where guid='$guid' and vers='$vers'";
317 318 319

    return -1
	if (! DBQueryWarn($query));
320 321

    return Refresh($self);
322 323
}

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

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

336 337
    my $guid = $self->guid();
    my $vers = $self->vers();
338 339 340 341 342 343
    my $path = $self->path();

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

345
    DeleteAllMetadata($self) == 0
346
	or return -1;
347

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

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

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

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

402 403 404 405 406
    if (ref($self)) {
	($uid, $access_type) = @_;
    }
    else {
	($guid, $uid, $access_type) = @_;
407

408 409 410 411 412 413 414 415 416
	$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!");
    }
417

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

426 427
    my $pid = $self->pid();
    my $gid = $self->gid();
428

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
    #
    # 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);
447 448
}

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

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

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

473 474 475
    while (my ($vers, $parent_vers) = $query_result->fetchrow_array()) {
	$children{$parent_vers} = []
	    if (!exists($children{$parent_vers}));
476

477 478 479 480 481 482 483 484 485 486 487 488 489 490
	# 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);
491

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

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

507
    @$resultp = @result;
508 509 510 511
    return 0;
}

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

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

525
    my $data_string = `cat $inputfile`;
526 527 528
    return -1
	if ($?);

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

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

549 550 551 552
	DBQueryWarn("lock tables experiment_template_inputs write, ".
		    "            experiment_template_input_data write")
	    or return -1;

553 554 555 556
	my $query_result =
	    DBQueryWarn("select idx from experiment_template_input_data ".
			"where md5='$md5'");

557 558 559 560
	if (!$query_result) {
	    DBQueryWarn("unlock tables");
	    return -1;
	}
561 562

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

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

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

598 599 600 601 602 603 604
    # Must be a real reference. 
    return -1
	if (! ref($self));

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

    return 0;
}

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

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

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

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

    # Special ...
    $internal = 1
668
	if (defined($type));
669

670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
    # 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);
    my $safevalue = DBQuoteSpecial($value);
686 687 688

    my $query_result =
	DBQueryWarn("insert into experiment_template_metadata_items set ".
689
		    "   guid='$guid', vers='$version', uid='$creator', ".
690
		    "   template_guid='$template_guid', ".
691
		    "   name=$safename, value=$safevalue, created=now()");
692 693 694 695 696
    return -1
	if (!$query_result);

    DBQueryWarn("insert into experiment_template_metadata set ".
		"   parent_guid='$template_guid', ".
697
		"   parent_vers='$template_vers', ".
698 699
		"   metadata_guid='$guid', ".
		"   metadata_vers='$version', ".
700
		"   metadata_type=$metadata_type, ".
701
		"   internal=$internal")
702
	or return -1;
703 704 705 706 707 708 709 710

    # 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' ".
711 712 713
			    "where parent_guid='$template_guid' and ".
			    "      parent_vers='$template_vers' and ".
			    "      name=$safename");
714 715 716 717
	    return -1
		if (!$query_result);
	}
    }
718 719 720 721
    
    return 0;
}

722 723 724
#
# Lookup a metadata value by name, optionally returning guid/vers.
#
725
sub LookupMetadata($$;$$$)
726
{
727
    my ($self, $name, $pguid, $pvers, $ptype) = @_;
728 729 730 731 732 733 734 735 736 737 738

    # 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 =
739
	DBQueryWarn("select metadata_guid,metadata_vers,metadata_type ".
740 741 742 743 744 745 746 747 748 749 750 751
		    "   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);

752 753
    my ($metadata_guid, $metadata_vers, $metadata_type) =
	$query_result->fetchrow_array();
754 755 756 757
    $$pguid = $metadata_guid
	if (defined($pguid));
    $$pvers = $metadata_vers
	if (defined($pvers));
758 759
    $$ptype = $metadata_type
	if (defined($ptype));
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
    
    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();
    my $parent_guid;
    my $parent_vers;
781
    my $metadata_type;
782
    my $already_exists =
783 784
	$self->LookupMetadata($name,
			      \$parent_guid, \$parent_vers, \$metadata_type);
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
    return -1
	if ($already_exists <= 0);

    $name  = DBQuoteSpecial($name);
    $value = DBQuoteSpecial($value);

    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', ".
		     "     template_guid='$template_guid', uid='$creator', ".
		     "     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 ...
    #
831 832 833 834 835 836 837 838 839
    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 Stoller's avatar
Leigh Stoller committed
840
	    Template::mysystem("$makegraph $template_guid");
841 842 843 844 845 846 847 848 849 850 851 852 853
	}
	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' ".
854 855 856
			"where parent_guid='$template_guid' and ".
			"      parent_vers='$template_vers' and ".
			"      name=$name")
857 858
		or return -1
	}
859 860 861 862 863
    }
    return 0;
}

#
864
# Add a formal parameter to a template.
865
#
866
sub NewFormalParameter($$$$$)
867
{
868
    my ($self, $name, $value, $description, $dbuid) = @_;
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892

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

893 894 895 896 897 898
    if (defined($description) && $description ne "") {
	$self->NewMetadata($name,
			   $description, $dbuid, "parameter_description")
	    == 0 or return -1;
    }

899 900 901
    return 0;
}

902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
#
# 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;
}

932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
#
# 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;
}

966
#
967
# Delete (all) template metadata
968
#
969
sub DeleteAllMetadata($)
970
{
971 972 973 974 975 976 977 978
    my ($self) = @_;

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

    my $template_guid = $self->guid();
    my $template_vers = $self->vers();
979 980 981 982 983

    my $query_result =
	DBQueryWarn("select metadata_guid ".
		    "    from experiment_template_metadata ".
		    "where parent_guid='$template_guid' and ".
984
		    "      parent_vers='$template_vers'");
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017

    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 ".
1018
		"      parent_vers='$template_vers'")
1019 1020 1021 1022 1023
	or return -1;

    return 0;
}

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 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
#
# 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;
}

1066 1067 1068 1069
#
# Copy exiting template metadata to a child. This is likely to change
# since we probably want to share at some point.
#
1070
sub CopyMetadata($$$)
1071
{
1072
    my ($self, $parent, $copier) = @_;
1073 1074 1075

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

1078 1079 1080
    my $from_guid = $parent->guid();
    my $from_vers = $parent->vers();
    my $to_vers   = $self->vers();
1081 1082 1083 1084 1085

    #
    # Copy the toplevel items.
    #
    my $query_result =
1086
	DBQueryWarn("select name,value,metadata_type,internal,i.parent_guid ".
1087 1088 1089 1090 1091
		    "  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 ".
1092
		    "      m.parent_vers='$from_vers'")
1093 1094
	or return -1;

1095
    while (my ($name,$value,$type,$internal,$hasparent) =
1096 1097
	   $query_result->fetchrow_array()) {

1098 1099
	my $guid;
	my $version = 1;
1100
	my $metadata_type = "NULL";
1101 1102
	my $parent_guid;
	my $parent_vers;
1103 1104 1105 1106
	
	$name   = DBQuoteSpecial($name);
	$value  = DBQuoteSpecial($value);

1107 1108 1109 1110 1111 1112 1113 1114
	#
	# 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");

1115 1116 1117 1118
	    #
	    # XXX Skip parameters that were deleted or whose description
	    # was modified after being created.
	    #
1119 1120 1121 1122
	    if ($type eq "parameter_description") {
		my $param_result = 
		    DBQueryWarn("select * ".
				"   from experiment_template_parameters ".
1123 1124 1125
				"where parent_guid='$from_guid' and ".
				"      parent_vers='$to_vers' and ".
				"      name=$name");
1126 1127 1128 1129 1130 1131

		return -1
		    if (!$param_result);
		
		next
		    if (!$param_result->numrows);
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155

		#
		# 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;
		}
1156 1157 1158 1159
	    }
	    $metadata_type = "'$type'";
	}

1160
	return -1
1161
	    if (!defined($guid) && NewGUID(\$guid) < 0);
1162 1163 1164

	DBQueryWarn("insert into experiment_template_metadata set ".
		    "   parent_guid='$from_guid', ".
1165
		    "   parent_vers='$to_vers', ".
1166 1167
		    "   metadata_guid='$guid', ".
		    "   metadata_vers='$version', ".
1168 1169
		    "   metadata_type=$metadata_type, ".
		    "   internal=$internal")
1170 1171 1172
	    or return -1;

	DBQueryWarn("insert into experiment_template_metadata_items set ".
1173
		    "   guid='$guid', vers='$version', uid='$copier', ".
1174
		    "   template_guid='$from_guid', ".
1175 1176 1177
		    (! defined($parent_guid) ? "" :
		     "  parent_guid='$parent_guid',".
		     "  parent_vers='$parent_vers',") .
1178 1179 1180
		    "   name=$name, value=$value, created=now()")
	    or return -1;

1181 1182 1183 1184 1185 1186 1187 1188
	#
	# XXX Some metadata is special ...
	#
	if (defined($type)) {
	    if ($type eq "parameter_description") {
		DBQueryWarn("update experiment_template_parameters set ".
			    "   metadata_guid='$guid', ".
			    "   metadata_vers='$version' ".
1189 1190 1191
			    "where parent_guid='$from_guid' and ".
			    "      parent_vers='$to_vers' and ".
			    "      name=$name")
1192 1193 1194 1195
		    or return -1
		}
	}
    }
1196 1197 1198
    return 0;
}

1199 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 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
#
# Return a list of metadata. This should be its own object.
#
sub MetadataList($$)
{
    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();

    #
    # Copy the toplevel items.
    #
    my $query_result =
	DBQueryWarn("select i.* 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='$template_guid' and ".
		    "      m.parent_vers='$template_vers' and ".
		    "      m.hidden=0 and m.metadata_type is null")
	or return -1;

    while (my $rowref = $query_result->fetchrow_hashref()) {
	my $name	= $rowref->{"name"};
	my $value       = $rowref->{"value"};
	my $guid	= $rowref->{"guid"};
	my $vers	= $rowref->{"vers"};

	my $ref = {'name'   => $name,
		   'value'  => $value,
		   'guid'   => "$guid/$vers"};

	$results{$name} = $ref;
    }
    %$prval = %results;
    return 0;
}

1244
#
1245
# Create a new Instance record, using the package below.
1246
#
1247
sub NewInstance($$$)
1248
{
1249
    my ($self, $eid, $creator, $description) = @_;
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261

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

    # We provide this stuff now.
    my %args = ();
    $args{'parent_guid'} = $self->guid();
    $args{'parent_vers'} = $self->vers();
    $args{'pid'}         = $self->pid();
    $args{'eid'}         = $eid;
    $args{'uid'}         = $creator;
1262 1263
    $args{'description'} = $description
	if (defined($description));
1264 1265 1266 1267

    return Template::Instance->Create(\%args);
}

1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
#
# Lookup specific instance by its exptidx. The point of this is to ensure
# that the instance is really associated with the template, since by itself,
# the exptidx is enough to find the instance record.
#
sub LookupInstance($$)
{
    my ($self, $exptidx) = @_;

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

    my $instance = Template::Instance->LookupByExptidx($exptidx);
    return undef
	if (!defined($instance));

    return undef
	if (! ($self->guid() == $instance->guid() &&
	       $self->vers() == $instance->vers()));

    return $instance;
}

1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
#
# Generate a list of instances for a template and save in the template
# structure. The argument indicates whether you want just active, or all
# of them (historical).
#
sub InstanceList($$$)
{
    my ($self, $all, $resultp) = @_;

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

    my $query_result;
    my @instances = ();
    my $guid = $self->guid();
    my $vers = $self->vers();

    if ($all) {
	$query_result = 
	    DBQueryWarn("select idx from experiment_template_instances ".
			"where parent_guid='$guid' and ".
			"      parent_vers='$vers'");
    }
    else {
	$query_result =
	    DBQueryWarn("select i.idx ".
			"  from experiment_template_instances as i ".
			"left join experiments as e on e.idx=i.exptidx ".
			"where i.parent_guid='$guid' and ".
			"      i.parent_vers='$vers' and e.idx is not null");
    }
    return -1
	if (!$query_result);
1326
    
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
    if (!$query_result->numrows) {
	@$resultp = ();
	return 0;
    }
	
    while (my ($idx) = $query_result->fetchrow_array()) {
	my $instance = Template::Instance->LookupByID($idx);
	return -1
	    if (!defined($instance));
	push(@instances, $instance);
    }

    @$resultp = @instances;
    return 0;
}

1343 1344 1345
#
# Copy the datastore from parent template to child template.
#
1346
sub CopyDataStore($$)
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
{
    my ($self, $parent) = @_;

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

    my $from_path = $parent->path();
    my $to_path   = $self->path();

Leigh Stoller's avatar
Leigh Stoller committed
1357 1358
    Template::mysystem("cd $from_path; ".
		       "   $RSYNC -rtgoDlz datastore $to_path") == 0
1359 1360 1361 1362 1363
	or return -1;

    return 0;
}

1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
#
# Import datastore from a directory back into the template. Currently
# used when creating a template from an instance.
#
sub ImportDataStore($$)
{
    my ($self, $from_path) = @_;

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

    my $to_path = $self->path();

    Template::mysystem("$RSYNC -rtgoDlz ${from_path}/ $to_path/datastore") == 0
	or return -1;

    return 0;
}

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
#
# Hide Template, optionally hiding all children.
#
sub Hide($$)
{
    my ($self, $recursive) = @_;

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

    my $guid = $self->guid();
    my $vers = $self->vers();
    
    DBQueryWarn("update experiment_templates set hidden=1 ".
		"where guid='$guid' and ".
		"      vers='$vers'")
	or return -1;
    
    Refresh($self) == 0
	or return -1;

    if ($recursive) {
	$self->Recurse("hidden=1") == 0
	    or return -1;
    }
    # This can fail; it is not critical.
    Template::mysystem("$makegraph $guid");
    
    return 0;
}

#
# Show Template, optionally showing all children.
#
sub Show($$)
{
    my ($self, $recursive) = @_;

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

    my $guid = $self->guid();
    my $vers = $self->vers();
    
    DBQueryWarn("update experiment_templates set hidden=0 ".
		"where guid='$guid' and ".
		"      vers='$vers'")
	or return -1;
    
    Refresh($self) == 0
	or return -1;

    if ($recursive) {
	$self->Recurse("hidden=0") == 0
	    or return -1;
    }
    # This can fail; it is not critical.
    Template::mysystem("$makegraph $guid");
    
    return 0;
}

Leigh Stoller's avatar
Leigh Stoller committed
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
#
# Activate/InActivate a template. What is an active template? Its one the
# user is futzing with and wants at the top of the list. Inactive templates
# are there but not considered important.
#
sub Activate($)
{
    my ($self) = @_;

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

    my $guid = $self->guid();
    my $vers = $self->vers();
    
    DBQueryWarn("update experiment_templates set active=1 ".
		"where guid='$guid' and ".
		"      vers='$vers'")
	or return -1;
    
    Refresh($self) == 0
	or return -1;

    return 0;
}
sub InActivate($)
{
    my ($self) = @_;

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

    my $guid = $self->guid();
    my $vers = $self->vers();
    
    DBQueryWarn("update experiment_templates set active=0 ".
		"where guid='$guid' and ".
		"      vers='$vers'")
	or return -1;
    
    Refresh($self) == 0
	or return -1;

    return 0;
}

1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
# Improve this at some point.
sub Recurse($$)
{
    my ($self, $string) = @_;
    my %children = ();

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

    my $template_guid = $self->guid();
    my $template_vers = $self->vers();
    
    my $query_result =
	DBQueryWarn("select vers,parent_vers from experiment_templates ".
		    "where guid='$template_guid' ".
		    "order by vers");
    return -1
	if (!$query_result);

    # Build up lists of childen.
    while (my ($vers,$parent_vers) = $query_result->fetchrow_array()) {
	next
	    if (!defined($parent_vers));

	$children{$parent_vers} = []
	    if (!exists($children{$parent_vers}));
	push(@{ $children{$parent_vers} }, $vers);
    }

Leigh Stoller's avatar
Leigh Stoller committed
1526 1527 1528 1529
    # A leaf node ...
    return 0
	if (!exists($children{$template_vers}));

1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
    # Recurse through all the children of this template.
    my @kids = @{ $children{$template_vers} };

    while (@kids) {
	my $kid     = shift(@kids);

	DBQueryWarn("update experiment_templates set $string ".
		    "where guid='$template_guid' and vers='$kid'")
	    or return -1;

	push(@kids, @{ $children{$kid} })
	    if (exists($children{$kid}));
    }
    return 0;
}

1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
#
# Create directory for template.
#
sub CreateDirectory($)
{
    my ($self) = @_;

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

    my $guid = $self->guid();
    my $vers = $self->vers();
    my $pid  = $self->pid();
    my $eid  = $self->eid();
    my $gid  = $self->gid();
    my $rval = 0;
    
    my $projroot = PROJROOT();
    my $guiddir  = "$projroot/$pid/templates/$guid";
    my $versdir  = "$guiddir/$vers";

    DBQueryWarn("update experiment_templates set ".
		"  path='$versdir' ".
		"where guid='$guid' and vers='$vers'")
	or return -1;

    # Or else the caller does not see the above change!
    Refresh($self) == 0
	or return -1;

    my $unix_gid;
    my $unix_name;
    
    if (! TBGroupUnixInfo($pid, $gid, \$unix_gid, \$unix_name)) {
	print "*** No info for project/group $pid/$gid!\n";
	return -1;
    }
    if (! -e $guiddir) {
	if (! mkdir($guiddir, 0770) ||
	    ! chmod(0770, "$guiddir") ||
	    ! chown($UID, $unix_gid, "$guiddir")) {
	    $rval = $ERRNO;
	    print "*** Could not create directory $guiddir: $!\n";
	    mysystem("$RMDIR $guiddir")
		if (-e $guiddir);
	    return $rval;
	}
    }
    if (! mkdir($versdir, 0775) ||
	! chmod(0775, "$versdir") ||
	! chown($UID, $unix_gid, "$versdir")) {
	$rval = $ERRNO;
	print "*** Could not create directory $versdir: $!\n";
	return $rval;
    }
1602
    foreach my $token ("tbdata", "archive", "datastore", "logs") {
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
	my $dir = "$versdir/$token";
	
	if (! mkdir($dir, 0770) ||
	    ! chmod(0770, "$dir")) {
	    $rval = $ERRNO;
	    print "*** Could not create directory $dir: $!\n";
	    return $rval;
	}
    }

    my $workdir = TBExptWorkDir($pid, $eid);

    #
    # We need this cause a template has an experiment sitting underneath it.
    #
    if (-e $workdir) {
	print "*** $workdir already exists!\n";
	return -1;
    }
    if (! mkdir($workdir, 0775) ||
	! chown($UID, $unix_gid, "$workdir")) {
	print "*** Could not create $workdir: $!\n";
	return -1;
    }
    
    return 0;
}

1631 1632 1633 1634 1635 1636 1637
############################################################################

package Template::Instance;
use libdb;
use libtestbed;
use libtblog;
use English;
1638
use libArchive;
1639 1640
use overload ('""' => 'Stringify');

1641 1642 1643 1644
# Flags for functions below.
sub STARTRUN_FLAGS_FIRSTRUN()	{ return Template::STARTRUN_FLAGS_FIRSTRUN(); }
sub STARTRUN_FLAGS_SWAPMOD()	{ return Template::STARTRUN_FLAGS_SWAPMOD(); }

1645 1646 1647 1648 1649 1650 1651
#
# Lookup a template experiment and create a class instance to return.
#
sub LookupByID($$)
{
    my ($class, $idx) = @_;

1652
    my $query_result =
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
	DBQueryWarn("select * ".
		    "  from experiment_template_instances ".
		    "where idx='$idx'");

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

    my $self            = {};
    $self->{'DB'}       = $query_result->fetchrow_hashref();

    # Backlink to the template.
    my $template_guid   = $self->{'DB'}->{'parent_guid'};
    my $template_vers   = $self->{'DB'}->{'parent_vers'};
    my $template        = Template->Lookup($template_guid, $template_vers);
    return undef
	if (!defined($template));
    $self->{'TEMPLATE'} = $template;
1670

1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
    bless($self, $class);
    return $self;
}
sub LookupByExptidx($$)
{
    my ($class, $exptidx) = @_;

    my $query_result =
	DBQueryWarn("select * ".
		    "  from experiment_template_instances ".
		    "where exptidx='$exptidx'");

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

    my $self            = {};
    $self->{'DB'}       = $query_result->fetchrow_hashref();

    # Backlink to the template.
    my $template_guid   = $self->{'DB'}->{'parent_guid'};
    my $template_vers   = $self->{'DB'}->{'parent_vers'};
    my $template        = Template->Lookup($template_guid, $template_vers);
    return undef
	if (!defined($template));
    $self->{'TEMPLATE'} = $template;
    
    bless($self, $class);
    return $self;
}

#
# Create a new template instance record. This installs the new record
# in the DB, and returns a class instance. 
#
sub Create($$)
{
    my ($class, $argref) = @_;
1708
    my $description;
1709 1710 1711 1712

    return undef
	if (ref($class));

1713 1714 1715 1716 1717 1718
    # must treat specially.
    if (exists($argref->{'description'})) {
	$description = DBQuoteSpecial($argref->{'description'});
	delete($argref->{'description'});
    }

1719 1720 1721
    my $query = "insert into experiment_template_instances set ".
	join(",", map("$_='" . $argref->{$_} . "'", keys(%{$argref})));

1722 1723 1724
    # Give it an initial start time; updated later.
    $query .= ", "
	if (defined($argref) && scalar(keys%{$argref}));
1725
    $query .= "start_time=now(),continue_time=now() ";
1726 1727
    $query .= ",description=$description"
	if (defined($description));
1728

1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
    my $query_result = DBQueryWarn($query);
    return undef
	if (! $query_result);

    # Grab the insert record.
    my $idx = $query_result->insertid;

    return Template::Instance->LookupByID($idx);
}
# accessors
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'DB'}->{$_[1]}); }
sub idx($)           { return field($_[0], 'idx'); }
sub exptidx($)       { return field($_[0], 'exptidx'); }
sub guid($)          { return field($_[0], 'parent_guid');}
sub vers($)          { return field($_[0], 'parent_vers');}
sub pid($)           { return field($_[0], 'pid'); }
sub eid($)           { return field($_[0], 'eid'); }
sub uid($)           { return field($_[0], 'uid'); }
sub runidx($)        { return field($_[0], 'runidx'); }
sub start_time($)    { return field($_[0], 'start_time'); }
sub stop_time($)     { return field($_[0], 'stop_time'); }
sub pause_time($)    { return field($_[0], 'pause_time'); }
sub continue_time($) { return field($_[0], 'continue_time'); }
sub runtime($)       { return field($_[0], 'runtime'); }
1753 1754
sub locked($)        { return field($_[0], 'locked'); }
sub locker_pid($)    { return field($_[0], 'locker_pid'); }
1755
sub description($)   { return field($_[0], 'description'); }
1756
sub template($)      { return ((!ref($_[0])) ? -1 : $_[0]->{'TEMPLATE'}); }
1757

1758 1759
# The path is the path of the experiment.
sub path($)    { return TBExptUserDir($_[0]->pid(), $_[0]->eid()); }
1760
sub workdir($) { return TBExptWorkDir($_[0]->pid(), $_[0]->eid()); }
1761

1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self)  = @_;
    my $guid    = $self->guid();
    my $vers    = $self->vers();
    my $idx     = $self->idx();
    my $exptidx = $self->exptidx();
    my $eid     = $self->eid();

    return "[Instance:$idx exptidx:$exptidx Template:$guid/$vers]";
}

#
# Refresh instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

    return -1
	if (! ref($self));

    my $idx = $self->idx();
    
    my $query_result =
	DBQueryWarn("select * from experiment_template_instances ".
		    "where idx='$idx'");

    return -1
	if (!$query_result || !$query_result->numrows);
	
    $self->{'DB'} = $query_result->fetchrow_hashref();
    return 0;
}

#
# Update an instance record.
#
sub Update($$;$)
{
    my ($self, $start_time, $argref) = @_;

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

    my $idx   = $self->idx();
    my $query = "update experiment_template_instances set ";

1814
    $query .= "start_time=now(),continue_time=now(),runtime=0 "
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
	if ($start_time);

    if (defined($argref) && scalar(keys%{$argref})) {
	$query .= ","
	    if ($start_time);
	
	$query .= join(",",
		       map("$_='" . $argref->{$_} . "'", keys(%{$argref})));
    }
    $query .= " where idx='$idx'";

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

    return Refresh($self);
}
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918

#
# Locking to prevent concurrent access
#
sub TryLock($$)
{
    my ($self, $ptoken) = @_;

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

    my $idx = $self->idx();

    DBQueryWarn("lock tables experiment_template_instances write")
	or return -1;

    my $query_result =
	DBQueryWarn("select locked,locker_pid ".
		    "    from experiment_template_instances ".
		    "where idx='$idx'");

    if (! $query_result) {
	DBQueryWarn("unlock tables");
	return -1;
    }
    my ($locked,$locker_pid) = $query_result->fetchrow_array();

    if (defined($locked)) {
	return 0
	    if (defined($locker_pid) && $locker_pid == $PID);
	
	DBQueryWarn("unlock tables");
	return -1;
    }

    DBQueryWarn("update experiment_template_instances set ".
		"  locked=now(), locker_pid='$PID' ".
		"where idx='$idx'")
	or return -1;

    DBQueryWarn("unlock tables");
    $self->Refresh();
    $$ptoken = $PID;
    return 0;
}
sub UnLock($$)
{
    my ($self, $token) = @_;

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

    my $idx = $self->idx();

    DBQueryWarn("lock tables experiment_template_instances write")
	or return -1;

    my $query_result =
	DBQueryWarn("select locked,locker_pid ".
		    "    from experiment_template_instances ".
		    "where idx='$idx'");

    if (! $query_result) {
	DBQueryWarn("unlock tables");
	return -1;
    }
    my ($locked,$locker_pid) = $query_result->fetchrow_array();

    return 0
	if (!defined($locked));

    if ($locker_pid != $token) {
	DBQueryWarn("unlock tables");
	return -1;
    }

    DBQueryWarn("update experiment_template_instances set ".
		"  locked=NULL, locker_pid=0 ".
		"where idx='$idx'")
	or return -1;
    
    DBQueryWarn("unlock tables");
    $self->Refresh();
    return 0;
}

1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
# Set the start time ...
sub Start($)
{
    my ($self) = @_;

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

    return $self->Update(1);
}
1930 1931
# Set the stop time ...
sub Stop($;$)
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
{
    my ($self, $argref) = @_;

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

    my $idx = $self->idx();
    
    #
    # Do the Run record first
    #
    my $runidx = $self->runidx();

    return -1
1947
	if (defined($runidx) && StopCurrentRun($self) < 0);
1948 1949

    # And then the instance.
1950 1951 1952 1953 1954 1955
    DBQueryWarn("update experiment_template_instances set stop_time=now() ".
		"where idx='$idx'")
	or return -1;
    
    return Refresh($self);
}
1956

1957 1958 1959 1960 1961 1962
#
# Finalize.
#
sub Finalize($;$)
{
    my ($self, $argref) = @_;
1963

1964
    # Must be a real reference. 
1965
    return -1
1966 1967 1968
	if (! ref($self));

    my $idx = $self->idx();
1969
    
1970 1971 1972 1973 1974 1975 1976 1977
    #
    # Do the Run record first
    #
    my $runidx = $self->runidx();

    return -1
	if (defined($runidx) && FinalizeCurrentRun($self) < 0);

1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
    return Refresh($self);
}

#
# Is an instance currently instantiated (a current experiment).
#
sub Instantiated($)
{
    my ($self) = @_;

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

    my $exptidx = $self->exptidx();

    my $query_result =
	DBQueryWarn("select pid,eid from experiments where idx='$exptidx'");

    return -1
	if (! $query_result);
1999 2000

    return $query_result->numrows;
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015
}

#
# Return the underlying experiment object.
#
sub Experiment($)
{
    my ($self) = @_;

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

    return Experiment->LookupByIndex($self->exptidx());
}
2016 2017 2018 2019 2020 2021 2022