GeniAggregate.pm.in 113 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1
2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2008-2018 University of Utah and the Flux Group.
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 
# {{{GENIPUBLIC-LICENSE
# 
# GENI Public License
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
# 
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
# 
# }}}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
29
30
31
32
#
package GeniAggregate;

#
33
# Some simple aggregate stuff.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
34
35
36
#
use strict;
use Exporter;
37
38
use vars qw(@ISA @EXPORT @EXPORT_OK
	    $ACTION_FLAGS_SYNCVLANS $ACTION_FLAGS_NOEVENTSTART);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
39

40
41
@ISA    = qw(Exporter);
@EXPORT = qw();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
42
43
44
45
46
47

# Must come after package declaration!
use GeniDB;
use GeniCredential;
use GeniCertificate;
use GeniSliver;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
48
use GeniSlice;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
49
use GeniRegistry;
50
use GeniUtil;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
51
use GeniUser;
52
use GeniComponent;
53
use GeniHRN;
54
use GeniResponse;
55
use GeniEvent;
56
use GeniXML;
57
use GeniCM;
58
use emutil;
59
use event;
60
use EmulabConstants;
Leigh B Stoller's avatar
Leigh B Stoller committed
61
use EmulabFeatures;
62
use User;
63
use Node;
64
65
use Logfile;
use libtestbed;
66
use Data::Dumper;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
67
68
69
use English;
use overload ('""' => 'Stringify');
use XML::Simple;
70
71
72
use POSIX qw(strftime);
use Time::Local;
use Date::Parse;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
73
74
75
76
77
78
79
80

# Configure variables
my $TB		   = "@prefix@";
my $TBOPS          = "@TBOPSEMAIL@";
my $TBAPPROVAL     = "@TBAPPROVALEMAIL@";
my $TBAUDIT   	   = "@TBAUDITEMAIL@";
my $BOSSNODE       = "@BOSSNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
81
82
my $MAINSITE       = @TBMAINSITE@;
my $ELABINELAB     = @ELABINELAB@;
83
my $PGENIDOMAIN    = "@PROTOGENI_DOMAIN@";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
84
85
my $SIGNCRED	   = "$TB/sbin/signgenicred";
my $VERIFYCRED	   = "$TB/sbin/verifygenicred";
86
my $NODEREBOOT	   = "$TB/bin/node_reboot";
87
my $EVENTSYS	   = "$TB/bin/eventsys_control";
88
my $VNODESETUP     = "$TB/sbin/vnode_setup";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
89
my $POWER          = "$TB/bin/power";
90
my $OSLOAD         = "$TB/bin/os_load";
91
my $OSSETUP        = "$TB/libexec/os_setup";
92
my $SNMPIT         = "$TB/bin/snmpit";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
93
94
95
my $NAMEDSETUP     = "$TB/sbin/named_setup";
my $EXPORTS_SETUP  = "$TB/sbin/exports_setup";
my $GENTOPOFILE    = "$TB/libexec/gentopofile";
96
my $GENELISTS      = "$TB/sbin/genelists";
97
my $IMAGE_SETUP    = "$TB/sbin/image_setup";
Leigh B Stoller's avatar
Leigh B Stoller committed
98
my $ARPLOCKDOWN    = "$TB/sbin/arplockdown";
99
my $TARFILES_SETUP = "$TB/bin/tarfiles_setup";
100
my $ELAB_SETUP     = "$TB/sbin/elabinelab";
101
my $TBADB          = "$TB/bin/tbadb";
102
my $PUSHROOTKEY	   = "$TB/sbin/pushrootkey";
103
my $TEVC	   = "$TB/bin/tevc";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
104
105
106

# Cache of instances to avoid regenerating them.
my %aggregates     = ();
107
BEGIN { use GeniUtil; GeniUtil::AddCache(\%aggregates); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
108

109
# Action() flags.
110
111
$ACTION_FLAGS_SYNCVLANS	        = 0x01;
$ACTION_FLAGS_NOEVENTSTART	= 0x02;
112

113
@EXPORT_OK = qw($ACTION_FLAGS_SYNCVLANS $ACTION_FLAGS_NOEVENTSTART);
114

115
116
117
118
119
120
121
122
123
sub DebugTimeStamp($)
{
    my ($message)  = @_;

    if (1) {
	print STDERR "TIMESTAMP: " . TBTimeStamp() . " $message\n";
    }
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
124
#
125
# Lookup by URN, idx, or uuid.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
126
127
128
129
130
131
132
#
sub Lookup($$)
{
    my ($class, $token) = @_;
    my $query_result;
    my $idx;

133
134
135
    if (GeniHRN::IsValid($token)) {
	my ($authority, $type, $id) = GeniHRN::Parse($token);
	return undef if $type ne "sliver";
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153

	if( GeniHRN::Authoritative($token, "@OURDOMAIN@") ) {
	    # Very simple: we put the index of our own aggregates right
	    # in the name.
	    $idx = $id;
	} else {
	    # Look up the aggregate's certificate.
	    $token = GeniHRN::Normalise( $token );
	    $query_result = DBQueryWarn(
		"SELECT geni_aggregates.idx FROM geni_aggregates, " .
		"geni_certificates WHERE geni_aggregates.uuid = " .
		"geni_certificates.uuid AND " .
		"geni_certificates.urn='$token';" );

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

	    ($idx) = $query_result->fetchrow_array();
	}
154
155
    }
    elsif ($token =~ /^\d+$/) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
	$idx = $token;
    }
    elsif ($token =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/) {
	$query_result =
	    DBQueryWarn("select idx from geni_aggregates ".
			"where uuid='$token'");
	    return undef
		if (! $query_result || !$query_result->numrows);

	    ($idx) = $query_result->fetchrow_array();
    }
    else {
	return undef;
    }
    # Look in cache first
    return $aggregates{"$idx"}
        if (exists($aggregates{"$idx"}));

    $query_result =
	DBQueryWarn("select * from geni_aggregates where idx='$idx'");
    
    return undef
	if (!$query_result || !$query_result->numrows);

180
181
182
183
184
185
    my $self               = {};
    $self->{'AGGREGATE'}   = $query_result->fetchrow_hashref();
    $self->{'CREDENTIAL'}  = undef;
    $self->{'SLICE'}       = undef;
    $self->{'PARENT'}      = undef;
    $self->{'CERTIFICATE'} = undef;
186
187
188

    # Bless into sub package if called for.
    my $type = $self->{'AGGREGATE'}->{'type'};
189
    if (defined($type) && $type ne "" && $type ne "Aggregate") {
190
191
192
193
194
	bless($self, $class . "::" . $type);
    }
    else {
	bless($self, $class);
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
195
196
197
198
199
200
201

    #
    # Grab the certificate, since we will probably want it.
    #
    my $uuid = $self->{'AGGREGATE'}->{'uuid'};
    my $certificate = GeniCertificate->Lookup($uuid);
    if (!defined($certificate)) {
202
203
204
205
206
207
208
209
	if ($type eq "Aggregate") {
	    print STDERR
		"Could not find certificate for aggregate $idx ($uuid)\n";
	    return undef;
	}
    }
    else {
	$self->{'CERTIFICATE'} = $certificate;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    }
    
    # Add to cache. 
    $aggregates{$self->{'AGGREGATE'}->{'idx'}} = $self;
    
    return $self;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $uuid = $self->uuid();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
226
    my $hrn  = $self->hrn();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
227
228
    my $idx  = $self->idx();

Leigh B. Stoller's avatar
Leigh B. Stoller committed
229
    return "[GeniAggregate: $hrn, IDX: $idx]";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
230
231
}

Leigh B Stoller's avatar
Leigh B Stoller committed
232
233
234
235
236
237
238
239
240
241
#
# Flush from our little cache, as for the expire daemon.
#
sub Flush($)
{
    my ($self) = @_;

    delete($aggregates{$self->idx()});
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
242
243
244
245
246
#
# Create a Geni aggregate in the DB. This happens on the server side only
# for now. The client side does not actually know its an aggregate, at
# least not yet.
#
247
sub Create($$$$$$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
248
{
249
    my ($class, $slice, $owner, $aggregate_type, $hrn, $nickname) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
250
    my @insert_data = ();
251
    my $certificate;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
252
253

    # Every aggregate gets a new unique index.
254
    my $idx = TBGetUniqueIndex('next_sliver', 1);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
255
256

    # Create a cert pair, which gives us a new uuid.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
257
    my $urn = GeniHRN::Generate( "@OURDOMAIN@", "sliver", $idx );
258
259
260
261
262
263
264
265
266
267
268

    if ($aggregate_type eq "Aggregate") {
	$certificate = GeniCertificate->Create({'urn'   => $urn,
						'hrn'   => $hrn,
						'email' => $TBOPS});

	if (!defined($certificate)) {
	    print STDERR "GeniAggregate::Create: ".
		"Could not generate new certificate and UUID for $hrn\n";
	    return undef;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
269
    }
270
271
    my $uuid        = (defined($certificate) ?
		       $certificate->uuid() : GeniUtil::NewUUID());
272
273
    my $slice_uuid  = $slice->uuid();
    my $owner_uuid  = $owner->uuid();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
274
275
276
    $aggregate_type = "Aggregate"
    	if (! defined($aggregate_type));

Leigh B. Stoller's avatar
Leigh B. Stoller committed
277
278
279
    # Now tack on other stuff we need.
    push(@insert_data, "created=now()");
    push(@insert_data, "idx='$idx'");
280
    push(@insert_data, "hrn=" . DBQuoteSpecial($hrn));
281
    push(@insert_data, "nickname=" . DBQuoteSpecial($nickname));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
282
283
284
    push(@insert_data, "uuid='$uuid'");
    push(@insert_data, "creator_uuid='$owner_uuid'");
    push(@insert_data, "slice_uuid='$slice_uuid'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
285
    push(@insert_data, "type='$aggregate_type'");
286
    # Start out new aggregates, as new.
287
288
    push(@insert_data, "state='new'," .
	 "status_state_timestamp=unix_timestamp(now())");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
289
290
291
292

    # Insert into DB.
    if (!DBQueryWarn("insert into geni_aggregates set " .
		     join(",", @insert_data))) {
293
294
	$certificate->Delete()
	    if (defined($certificate));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
295
296
	return undef;
    }
297
298
299
300
301
    my $aggregate = GeniAggregate->Lookup($idx);
    return undef
	if (!defined($aggregate));

    return $aggregate;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
302
303
304
305
306
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'AGGREGATE'}->{$_[1]}); }
sub idx($)		{ return field($_[0], "idx"); }
sub uuid($)		{ return field($_[0], "uuid"); }
307
sub nickname($)		{ return field($_[0], "nickname"); }
308
sub resource_id($)      { return $_[0]->nickname(); }
309
sub type($)		{ return field($_[0], "type"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
310
311
312
sub slice_uuid($)	{ return field($_[0], "slice_uuid"); }
sub creator_uuid($)	{ return field($_[0], "creator_uuid"); }
sub created($)		{ return field($_[0], "created"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
313
sub registered($)	{ return field($_[0], "registered"); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
314
sub credential_idx($)	{ return field($_[0], "credential_idx"); }
315
sub aggregate_idx($)	{ return field($_[0], "aggregate_idx"); }
316
317
sub speaksfor_uuid($)	{ return field($_[0], "speaksfor_uuid"); }
sub speaksfor_urn($)	{ return field($_[0], "speaksfor_urn"); }
318
sub status($)		{ return field($_[0], "status"); }
319
sub state($)		{ return field($_[0], "state"); }
320
sub status_state_timestamp($) { return field($_[0], "status_state_timestamp"); }
321
sub boot_failure($)     { return field($_[0], "boot_failure"); }
322
sub ErrorLog($)		{ return field($_[0], "errorlog"); }
323
324
325
326
327
328
329
330
331
sub cert($)		{ return GetCertificate($_[0])->cert(); }
# Watch for aggregates that no longer get a certificate.
sub GetCertificate($)
{
    if (!defined($_[0]->{'CERTIFICATE'})) {
	print STDERR "*** No certificate for aggregate: " . $_[0] . "\n";
    }
    return $_[0]->{'CERTIFICATE'};
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
332

333
334
335
# An alias so that slivers look like aggregates.
sub resource_type($)	{ return field($_[0], "type"); }

336
337
338
339
340
341
342
343
344
345
346
# A place to stash a temporary rspec.
sub rspec($;$)
{
    my ($self, $rspec) = @_;

    if (defined($rspec)) {
	$self->{'RSPEC'} = $rspec;
    }
    return $self->{'RSPEC'};
}

347
348
349
350
351
352
353
# Return the URN.
sub urn($)
{
    my ($self) = @_;

    return GeniHRN::Generate("@OURDOMAIN@", "sliver", $self->idx());
}
354
355
# Name compat.
sub sliver_urn($)	{ return $_[0]->urn(); }
356

357
358
359
360
#
# Destroy all the slivers in the aggregate, and then the aggregate if there
# is nothing in it. Leave it around if something goes wrong.
#
361
sub Delete($$)
362
{
363
    my ($self, $purge) = @_;
364
365
366
367
368
369
370
371
372
373
374
375
    my $broken = 0;

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

    my @slivers = ();
    if ($self->SliverList(\@slivers) != 0) {
	print STDERR "Could not get sliver list for $self\n";
	return -1;
    }
    foreach my $sliver (@slivers) {
	if ($sliver->status() eq "broken") {
376
	    print STDERR "Could not delete 'broken' $sliver from $self\n";
377
	    $broken++;
378
	    last;
379
	}
380
	if ($sliver->Delete($purge) != 0) {
381
382
383
	    print STDERR "Could not delete $sliver from $self\n";
	    $sliver->SetStatus("broken");
	    $broken++;
384
	    last;
385
386
387
388
389
	}
    }
    return -1
	if ($broken);
    
390
391
392
393
    if (GeniUsage->DestroyAggregate($self, $purge)) {
	print STDERR "GeniAggregate::Delete: ".
	    "GeniUsage->DestroyAggregate($self) failed\n";
    }
394
395
396
397
398
399
400
401
402
403
    my $idx  = $self->idx();
    my $uuid = $self->uuid();

    DBQueryWarn("delete from geni_credentials where this_uuid='$uuid'")
	or return -1;
    DBQueryWarn("delete from geni_certificates where uuid='$uuid'")
	or return -1;
    DBQueryWarn("delete from geni_aggregates where idx='$idx'")
	or return -1;
    
404
405
406
    # Delete from cache. 
    delete($aggregates{$idx});

407
408
409
    return 0;
}

410
411
412
413
414
415
416
#
# Cons up an hrn.
#
sub hrn($)
{
    my ($self) = @_;

417
418
419
420
421
    my $hrn = field($self, "hrn");

    if (defined($hrn) && $hrn ne "") {
	return $hrn;
    }
422
    return "${PGENIDOMAIN}.aggregate_" . $self->idx();
423
424
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
#
# Look up toplevel aggregate for a locally instantiated slice. 
#
sub SliceAggregate($$)
{
    my ($class, $slice) = @_;

    my $slice_uuid = $slice->uuid();
    my @result = ();

    my $query_result =
	DBQueryWarn("select idx from geni_aggregates ".
		    "where slice_uuid='$slice_uuid' and type='Aggregate'");
    return undef
	if (!$query_result);
    return undef
	if ($query_result->numrows != 1);

    my ($idx) = $query_result->fetchrow_array();
    my $aggregate = GeniAggregate->Lookup($idx);
    return undef
	if (!defined($aggregate));

    return $aggregate;
}

451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
#
# Look up a list of aggregates for a locally instantiated slice. 
# Used by the CM.
#
sub SliceAggregates($$$)
{
    my ($class, $slice, $pref) = @_;

    my $slice_uuid = $slice->uuid();
    my @result = ();

    my $query_result =
	DBQueryWarn("select idx from geni_aggregates ".
		    "where slice_uuid='$slice_uuid'");
    return -1
	if (!$query_result);

    while (my ($idx) = $query_result->fetchrow_array()) {
	my $aggregate = GeniAggregate->Lookup($idx);
	return -1
	    if (!defined($aggregate));
	push(@result, $aggregate);
    }
    @$pref = @result;
    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
478
479
480
481
482
483
484
485
486
487
488
#
# List of slivers for this aggregate.
#
sub SliverList($$)
{
    my ($self, $pref) = @_;
    my @result = ();
    
    return -1
	if (! (ref($self) && ref($pref)));

489
490
    my $idx  = $self->idx();
    my $uuid = $self->uuid();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
491
    my $query_result =
492
493
	DBQueryWarn("select idx from geni_slivers ".
		    "where aggregate_uuid='$uuid'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
494
495
496
497
498
499
500
501
502
503
504
    return -1
	if (!$query_result);

    while (my ($sliver_idx) = $query_result->fetchrow_array()) {
	my $sliver = GeniSliver->Lookup($sliver_idx);
	if (!defined($sliver)) {
	    print STDERR "Could not find sliver object for $sliver_idx\n";
	    return -1;
	}
	push(@result, $sliver);
    }
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523

    #
    # And any aggregates that are children.
    #
    $query_result =
	DBQueryWarn("select idx from geni_aggregates ".
		    "where aggregate_idx='$idx'");
    return -1
	if (!$query_result);

    while (my ($aggregate_idx) = $query_result->fetchrow_array()) {
	my $aggregate = GeniAggregate->Lookup($aggregate_idx);
	if (!defined($aggregate_idx)) {
	    print STDERR
		"Could not find aggregate object for $aggregate_idx\n";
	    return -1;
	}
	push(@result, $aggregate);
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
524
525
526
527
528
    @$pref = @result;
    return 0;
    
}

529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
#
# Look for any slivers with provided state.
#
sub CheckSliverStates($$)
{
    my ($self, $state) = @_;

    my @slivers = ();
    if ($self->SliverList(\@slivers) != 0) {
	print STDERR "Could not get sliver list for $self\n";
	return -1;
    }
    foreach my $sliver (@slivers) {
	next
	    if (ref($sliver) ne "GeniSliver::Node");

	return 1
	    if ($sliver->state() eq $state);
    }
    return 0;
}

551
552
553
554
555
556
557
558
559
560
#
# Set the aggregate for an aggregate.
#
sub SetAggregate($$)
{
    my ($self, $aggregate) = @_;

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

561
562
563
    my $idx      = $self->idx();
    my $agg_idx  = $aggregate->idx();
    my $agg_uuid = $aggregate->uuid();
564
565
566
567
568
569
570
571
572
573
574
575

    return -1
	if (!DBQueryWarn("update geni_aggregates set ".
			 "  aggregate_idx='$agg_idx' ".
			 "where idx='$idx'"));
    
    $self->{'AGGREGATE'}->{'aggregate_idx'} = $agg_idx;
    $self->{'PARENT'} = $aggregate;
    return 0;
}

#
576
# Get the aggregate for an aggregate.
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
#
sub GetAggregate($)
{
    my ($self) = @_;

    return undef
	if (! ref($self));

    return $self->{'PARENT'} if (defined($self->{'PARENT'}));
    return undef
	if (!defined($self->aggregate_idx()));

    my $aggregate = GeniAggregate->Lookup($self->aggregate_idx());
    if (!defined($aggregate)) {
	print STDERR "Could not get aggregate object associated with $self\n";
	return undef;
    }
    $self->{'PARENT'} = $aggregate;
    return $aggregate;
}

598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
#
# Is object in the aggregate.
#
sub IsMember($$)
{
    my ($self, $object) = @_;

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

    my $aggregate = $object->GetAggregate();
    return 0
	if (!$aggregate);
    return -1
	if ($self->idx() != $aggregate->idx());
    return 1;
}

616
#
617
618
# Set the state and status for the aggregate. The goal here is to send
# just a single event when both state/status are being updated.
619
#
620
sub SetStateStatus($$$)
621
{
622
    my ($self, $state, $status) = @_;
623
624
625
626
627

    return undef
	if (! ref($self));

    my $idx = $self->idx();
628
629
630

    my $query_result =
	DBQueryWarn("update geni_aggregates set ".
631
632
		    "  status='$status',state='$state', ".
		    "  status_state_timestamp=unix_timestamp(now()) ".
633
634
		    "where idx='$idx' and ".
		    "      (status!='$status' or state!='$state')");
635
    return -1
636
	if (!defined($query_result));
637
    
638
    $self->{'AGGREGATE'}->{'state'}  = $state;
639
    $self->{'AGGREGATE'}->{'status'} = $status;
640
641
642
643
644

    # Any change, send the event.
    $self->SendStatusEvent()
	if ($self->type() eq "Aggregate" && $query_result->affectedrows);

645
646
647
    return 0;
}

648
649
650
651
652
653
654
655
656
657
#
# Set the status for the aggregate.
#
sub SetStatus($$)
{
    my ($self, $status) = @_;

    return $self->SetStateStatus($self->state(), $status);
}

658
659
660
661
662
663
664
#
# Set the state for the aggregate
#
sub SetState($$)
{
    my ($self, $state) = @_;

665
666
    return $self->SetStateStatus($state, $self->status());
}
667

668
669
670
671
672
sub SendStatusEvent($)
{
    my ($self) = @_;

    my $slice = $self->GetSlice();
673
    return -1
674
	if (!defined($slice));
675
    
676
677
678
    my $blob = {
	"state"   => $self->state(),
	"status"  => $self->status(),
679
680
	# Fall back to current time if no timestamp yet.
	"utc"     => $self->status_state_timestamp() || time(),
681
682
683
684
685
    };
    GeniEvent->SendEvent({"type"    => "SLICESTATUS",
			  "slice"   => $slice->urn(),
			  "urn"     => $slice->urn(),
			  "details" => $blob});
686
687
688
    return 0;
}

689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
#
# Send status events for all nodes in an aggregate and the aggregate itself.
#
sub SendAllStatusEvents($)
{
    my ($self) = @_;
    $self->SendStatusEvent();

    my @slivers = ();
    if ($self->SliverList(\@slivers) != 0) {
	print STDERR "Could not get sliver list for $self\n";
	return -1;
    }
    #
    # It would be nice to send one big event, but events have a fixed
    # max size and we would blow right by it.
    #
    foreach my $sliver (@slivers) {
	next
	    if (ref($sliver) ne "GeniSliver::Node");

	$sliver->SendStatusEvent();
    }
    return 0;
}

715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
#
# And the ErrorLog. These are intended to be short ...
#
sub SetErrorLog($$)
{
    my ($self, $log) = @_;
    my $safe_log = DBQuoteSpecial($log);

    return undef
	if (! ref($self));

    my $idx = $self->idx();
    
    return -1
	if (!DBQueryWarn("update geni_aggregates set ".
			 "  errorlog=$safe_log ".
			 "where idx='$idx'"));
    
    $self->{'AGGREGATE'}->{'errorlog'} = $log;
    return 0;
}

737
sub SetBootFailure($;$)
738
{
739
740
    my ($self, $code) = @_;
    $code = GENIRESPONSE_SETUPFAILURE() if (!defined($code));
741

742
743
744
745
746
747
748
    return undef
	if (! ref($self));

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

    return -1
	if (!DBQueryWarn("update geni_aggregates set ".
749
			 "  boot_failure='$code' ".
750
			 "where idx='$idx'"));
751
    
752
    $self->{'AGGREGATE'}->{'boot_failure'} = $code;
753
754
755
756
757
    return 0;
}

sub ClearBootFailure($)
{
758
759
    my ($self) = @_;

760
761
762
763
764
765
766
767
768
    return undef
	if (! ref($self));

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

    return -1
	if (!DBQueryWarn("update geni_aggregates set ".
			 "  boot_failure='0' ".
			 "where idx='$idx'"));
769
770

    $self->{'AGGREGATE'}->{'boot_failure'} = 0;
771
772
773
    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
#
# Set the registered datetime for the aggregate
#
sub SetRegistered($$)
{
    my ($self, $yesno) = @_;

    return undef
	if (! ref($self));

    my $idx = $self->idx();
    my $val = ($yesno ? "now()" : "NULL");
    
    return -1
	if (!DBQueryWarn("update geni_aggregates set ".
			 "  registered=$val ".
			 "where idx='$idx'"));
    
    return 0;
}

795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
#
# Set the speaksfor stuff.
#
sub SetSpeaksFor($$)
{
    my ($self, $speaksfor) = @_;
    my $idx = $self->idx();
    my $safe_speaksfor_uuid = DBQuoteSpecial($speaksfor->owner_uuid());
    my $safe_speaksfor_urn  = DBQuoteSpecial($speaksfor->owner_urn());

    print "GeniAggregate->SetSpeaksFor($self, $speaksfor)\n";

    return -1
	if (!DBQueryWarn("update geni_aggregates set ".
			 "  speaksfor_uuid=$safe_speaksfor_uuid ".
			 "where idx='$idx'"));

    $self->{'AGGREGATE'}->{'speaksfor_urn'}  = $speaksfor->owner_urn();
    $self->{'AGGREGATE'}->{'speaksfor_uuid'} = $speaksfor->owner_uuid();

    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
#
# Get the slice for the aggregate.
#
sub GetSlice($)
{
    my ($self) = @_;

    return undef
	if (! ref($self));

    return $self->{'SLICE'} if (defined($self->{'SLICE'}));

    if (!defined($self->slice_uuid())) {
	print STDERR "No slice associated with $self\n";
	return undef;
    }
    my $slice = GeniSlice->Lookup($self->slice_uuid());
    if (!defined($slice)) {
	print STDERR "Could not get slice object associated with $self\n";
	return undef;
    }
    $self->{'SLICE'} = $slice;
    return $slice;
}

843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
#
# The expiration time for an aggregate is when the slice expires.
# The DB field is ignored.
#
sub expires($)
{
    my ($self) = @_;

    return undef
	if (! ref($self));

    my $slice = $self->GetSlice();
    return undef
	if (!defined($slice));

    return $slice->expires();
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
#
# Get the creator for the aggregate.
#
sub GetCreator($)
{
    my ($self) = @_;

    return undef
	if (! ref($self));

    if (!defined($self->creator_uuid())) {
	print STDERR "No creator associated with $self\n";
	return undef;
    }
    return GeniUser->Lookup($self->creator_uuid(), 1);
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
878
#
Leigh B Stoller's avatar
Leigh B Stoller committed
879
# Create a signed credential for this aggregate, issued to the provided user
Leigh B. Stoller's avatar
Leigh B. Stoller committed
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
# The credential will grant all permissions for now.
#
# Should we store these credentials in the DB, recording what we hand out?
#
sub NewCredential($$)
{
    my ($self, $owner) = @_;

    return undef
	if (! (ref($self) && ref($owner)));

    my $credential = GeniCredential->Create($self, $owner);
    if (!defined($credential)) {
	print STDERR "Could not create credential for $self, $owner\n";
	return undef;
    }
896
    # Bump expiration to avoid race with aggregate about to expire.
897
    $credential->SetExpiration(time() + (24 * 3600));
898
	
899
900
901
    if (defined($self->nickname())) {
	$credential->AddExtension("nickname", $self->nickname());
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
902
903
904
905
906
907
908
    if ($credential->Sign($self->GetCertificate()) != 0) {
	print STDERR "Could not sign credential for $self, $owner\n";
	return undef;
    }
    return $credential;
}

909
910
911
#
# Get the manifest for an aggregate. Returns the XML string.
#
912
sub GetManifest($$)
913
{
914
    my ($self, $asxml) = @_;
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932

    return undef
	if (! ref($self));

    my $slice      = $self->GetSlice();
    return undef
	if (!defined($slice));
    my $slice_uuid = $slice->uuid();

    my $query_result =
	DBQueryWarn("select manifest from geni_manifests ".
		    "where slice_uuid='$slice_uuid'");
    
    if (!$query_result || !$query_result->numrows) {
	return undef;
    }
    my ($xml) = $query_result->fetchrow_array();

933
934
    my $manifest = GeniXML::Parse($xml);
    if (!defined($manifest)) {
935
936
	return undef;
    }
937

938
939
940
    #
    # Update the manifest ticket to reflect the current expiration time.
    #
941
    my $valid_date = POSIX::strftime("20%y-%m-%dT%H:%M:%SZ",
942
				     gmtime(str2time($slice->expires())));
Jonathon Duerig's avatar
Jonathon Duerig committed
943
944
945
946
947
    if (GeniXML::IsVersion0($manifest)) {
	GeniXML::SetText("valid_until", $manifest, $valid_date);
    } else {
	GeniXML::SetText("expires", $manifest, $valid_date);
    }
948

949
950
951
    return $manifest
	if (!$asxml);
    
952
    $xml = GeniXML::Serialize($manifest);
953
954
955
    return $xml;
}

956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
#
# Store a manifest back.
#
sub UpdateManifest($$)
{
    my ($self, $manifest) = @_;
    my $slice_uuid = $self->slice_uuid();
    my $manifest_string = DBQuoteSpecial(GeniXML::Serialize($manifest));

    #
    # We need the current idx. 
    #
    my $query_result =
	DBQueryWarn("select idx from geni_manifests ".
		    "where slice_uuid='$slice_uuid'");
    return -1
	if (!$query_result);

    if ($query_result->numrows) {
	my ($idx) = $query_result->fetchrow_array();
    
	DBQueryWarn("update geni_manifests set ".
		    "  manifest=$manifest_string " .
		    "where idx=$idx")
	    or return -1;
    }
    else {
	DBQueryWarn("replace into geni_manifests set ".
		    "  manifest=$manifest_string, " .
		    "  idx=NULL, slice_uuid='$slice_uuid', created=now()")
	    or return -1;
    }
    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
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
# Process the manifest. Just hand off to the slivers.
#
sub ProcessManifest($$)
{
    my ($self, $manifest) = @_;

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

    my @slivers = ();
    if ($self->SliverList(\@slivers) != 0) {
	print STDERR "Could not get sliver list for $self\n";
	return -1;
    }

    foreach my $sliver (@slivers) {
	next
	    if (ref($sliver) ne "GeniSliver::Node");

	if ($sliver->ProcessManifest($manifest) != 0) {
	    return -1;
	}
    }
    return 0;
}

1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
#
# Temp. 
#
sub UseOsSetup($)
{
    my ($self) = @_;
    
    my $experiment = Experiment->Lookup($self->slice_uuid());
    return 0
	if (!defined($experiment));
    my $group = $experiment->GetGroup();
    return 0
	if (!defined($group));
    my $user = User->ThisUser();
    
    return EmulabFeatures->FeatureEnabled("GeniOsSetup",
					  $user, $group, undef);
}

1037
sub Start($$;$)
1038
{
1039
    my ($self, $version, $flags) = @_;
1040

1041
1042
1043
    if ($self->UseOsSetup()) {
	return $self->ActionStart($version, $flags);
    }
1044
    return $self->Action($version, "start", $flags);
1045
1046
}

1047
sub Restart($$;$)
1048
{
1049
    my ($self, $version, $flags) = @_;
1050

1051
1052
1053
    if ($self->UseOsSetup()) {
	return $self->ActionRestart($version, $flags);
    }
1054
    return $self->Action($version, "restart", $flags);
1055
1056
}

1057
sub Reload($$;$)
1058
{
1059
    my ($self, $version, $flags) = @_;
1060

1061
1062
1063
    if ($self->UseOsSetup()) {
	return $self->ActionReload($version, $flags);
    }
1064
    return $self->Action($version, "reload", $flags);
1065
1066
}

1067
#
1068
# New version of start that uses libossetup.
1069
1070
1071
1072
#
sub ActionStart($$;$)
{
    my ($self, $version, $flags) = @_;
1073
1074
    my $msg = "SliverStart: ";
    my $bootfailure_code = GENIRESPONSE_SETUPFAILURE();
1075
1076
1077
1078
1079
    $flags      = 0 if (!defined($flags));
    require Lan;
    require OSImage;
    require libossetup;

1080
1081
    #die("Yippie");

1082
1083
    # Clear last error.
    $self->SetErrorLog("");    
1084
    $self->ClearBootFailure();
1085
1086
    # Set new status so ComputeState() knows what is going on.
    $self->SetStatus("working");
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128

    my $experiment = Experiment->Lookup($self->slice_uuid());
    if (!defined($experiment)) {
	$msg .= "Could not map $self to its experiment";
	goto bad;
    }
    my $pid = $experiment->pid();
    my $eid = $experiment->eid();
    my $expstate = $experiment->state();

    my $group = $experiment->GetGroup();
    if (!defined($group)) {
	$msg = "Could not map $self to its experiment group";
	goto bad;
    }
    my $slice = $self->GetSlice();
    if (!defined($slice)) {
	$msg = "Could not map $self to its slice";
	goto bad;
    }
    my $creator = $self->GetCreator();
    if (!defined($creator)) {
	$msg = "Could not map $self to its creator";
	goto bad;
    }
    
    my @slivers = ();
    if ($self->SliverList(\@slivers) != 0) {
	$msg .= "Could not get sliver list for $self";
	goto bad;
    }
    my %nodes    = ();
    my @restarts = ();
    my @failed   = ();
    my $sliver;

    foreach $sliver (@slivers) {
	if (ref($sliver) ne "GeniSliver::Node") {
	    next
		if ($sliver->state() eq "started");

	    $sliver->Start($version) == 0
1129
		or goto bad;
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
	    next;
	}
	#
	# Since this is an aggregate, some slivers may already be
	# in the started state. We skip those.
	#
	next
	    if ($sliver->state() eq "started");

	#
	# If the sliver is stopped, then we do not want to run it through
	# os_setup, we already did that when the sliver was first added.
	# Instead we want to bring it back via Restart (which handles this
	# case).
	#
	if ($sliver->state() eq "stopped") {
	    push(@restarts, $sliver);
	    next;
	}
	
	my $node = Node->Lookup($sliver->resource_id());
	if (!defined($node)) {
	    $msg .= "Could not map $sliver to a node";
	    goto bad;
	}
	my $reservation = $node->Reservation();
	if (!defined($reservation)) {
	    $msg .= "$node no longer belongs to $self";
	    goto bad;
	}
	if (!$reservation->SameExperiment($experiment)) {
	    $msg .= "$node is not reserved to $self";
	    goto bad;
	}
	$nodes{$node->node_id()} = $node;

	# Want to make sure we see fresh logs (and do not store the same log).
	$node->ClearBootLog();
1168
1169
	# Must be defined for below.
	$node->_bootlog(undef);
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190

	# Back pointer, see below.
	$node->_sliver($sliver);

	# Add pnodes for exclusive virtual nodes that are not explicitly
	# part of the rspec. 
	if ($node->isvirtnode() && !$node->OnSharedNode()) {
	    my $physnodeid = $node->phys_nodeid();
	    if (!exists($nodes{$physnodeid})) {	    
		my $pnode = Node->Lookup($physnodeid);
		if (!defined($pnode)) {
		    $msg .= "Could not lookup $physnodeid";
		    goto bad;
		}
		# There is no sliver (might change later if in the rspec).
		$pnode->_sliver(undef);

		# Add to os_setup list.
		$nodes{$pnode->node_id()} = $pnode;

		$pnode->ClearBootLog();
1191
1192
		# Must be defined for below.
		$pnode->_bootlog(undef);
1193
1194
1195
1196
1197
1198
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
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
	    }
	}
    }
    # See "bad" label below.
    $sliver = undef;

    #
    # Download the images. If this fails, we have wasted our time,
    # but we want to do this after we have forked off from the parent
    # and we have returned to the client (rpc).
    #
    # All imported images are globally available, so makes no sense to
    # put them into the project of the slice. In fact, if someone else
    # in another project tried to use the same image, the update will
    # fail when PROTOGENI_LOCALUSER=1 since it was imported by another
    # real user, and the current user will not have write permission
    # on it.
    #
    my $output = 
	GeniUtil::ExecuteQuietAsGeniUser("$IMAGE_SETUP ".
					 "-d -g -p GeniSlices $pid,$eid");
    print STDERR $output;
    if ($?) {
	$msg = "Could not setup images";
	goto bad;
    }

    # The nodes will not boot locally unless there is a DNS record,
    # but we also need it before we can issue the reloads.
    if (system("$NAMEDSETUP")) {
	$msg .= "$NAMEDSETUP failed\n";
	goto bad;
    }

    if ($version >= 2) {
	#
	# Dump the manifest into the experiment directory.
	#
	my $userdir       = $experiment->UserDir();
	my $manifest_file = "$userdir/tbdata/geni_manifest";
	my $manifest      = $self->GetManifest(1);
	if ($manifest && open(MAN, ">$manifest_file")) {
	    print MAN $manifest;
	    close(MAN);
	}

	#
	# Now we need a mapping of node_id to sliver_urn.
	#
	my $mapping_file = "$userdir/tbdata/geni_mapping";
	if (open(MAP, ">$mapping_file")) {
	    foreach my $sliver (@slivers) {
		next
		    if (ref($sliver) ne "GeniSliver::Node");

		print MAP $sliver->resource_id();
		print MAP " ";
		print MAP $sliver->sliver_urn();
		print MAP "\n";
	    }
	    close(MAP);
	}
	
	if (system("$GENELISTS -c")) {
	    $msg .= "$GENELISTS failed\n";
	    goto bad;
	}
1260
	DebugTimeStamp("gentopofile");
1261
1262
1263
1264
	if (system("$GENTOPOFILE $pid $eid")) {
	    $msg .= "$GENTOPOFILE failed\n";
	    goto bad;
	}
1265
	DebugTimeStamp("exports_setup");
1266
1267
1268
1269
	if (system("$EXPORTS_SETUP")) {
	    $msg .= "$EXPORTS_SETUP failed\n";
	    goto bad;
	}
1270
	DebugTimeStamp("arplockdown");
1271
1272
1273
1274
1275
	if (system("$ARPLOCKDOWN ")) {
	    $msg .= "$ARPLOCKDOWN failed\n";
	    goto bad;
	}
	# The nodes will not boot locally unless there is a DNS record.
1276
	DebugTimeStamp("named_setup");
1277
1278
1279
1280
	if (system("$NAMEDSETUP")) {
	    $msg .= "$NAMEDSETUP failed\n";
	    goto bad;
	}
1281
	DebugTimeStamp("setuportvlans");
1282
	if ($experiment->SetupPortLans()) {
1283
	    $bootfailure_code = GENIRESPONSE_SETUPFAILURE_NETWORK();
1284
1285
1286
	    $msg .= "Failed to setup shared vlan ports";
	    goto bad;
	}
1287
1288
1289
1290
1291
1292
1293
1294
	if (!$experiment->skipvlans()) {
	    DebugTimeStamp("syncportvlans");
	    if ($experiment->SyncPortLans()) {
		$bootfailure_code = GENIRESPONSE_SETUPFAILURE_NETWORK();
		$msg .= "Failed to add ports to shared vlans";
		goto bad;
	    }
	    DebugTimeStamp("syncportvlans done");
1295
1296
1297
1298
	}
    }
    $sliver = undef;

1299
1300
1301
1302
1303
1304
    #
    # os_setup requires the expstate to be set appropriately, which we
    # generally do not do on the geni path.
    #
    $experiment->SetState(EXPTSTATE_ACTIVATING());

1305
1306
1307
1308
1309
    #
    # So we are going to fork and let os_setup proceed.
    #
    my $childpid = main::WrapperFork();
    if ($childpid) {
1310
1311
1312
1313
1314
1315
1316
	#
	# This indicates that while not locked, we are still busy.
	# KillMonitor operates using the cancel flag, so we should
	# be fine. 
	#
	$slice->SetMonitorPid($childpid);
	print STDERR "Monitor PID $childpid\n";
1317
1318
	return 0;
    }
1319
1320
1321
1322
    #
    # We want to let snmpit run in parallel with os_setup, like the
    # classic path does. 
    #
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
    my $snmpit_child;

    if (!$experiment->skipvlans()) {
	$snmpit_child = fork();
	if ($snmpit_child) {
	    #
	    # Parent just continues on, but will wait later, we cannot
	    # return to the caller until snmpit is done. 
	    #
	    print STDERR "Forked off snmpit: process $snmpit_child\n";
1333
1334
	}
	else {
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
	    EventFork();
	    my $msg;
	
	    DebugTimeStamp("snmpit started");
	    if ($flags & $ACTION_FLAGS_SYNCVLANS) {
		if (Lan->CompareVlansWithSwitches2($experiment)) {
		    $msg .= "CompareVlansWithSwitches2 failed!\n";
		    goto badsnmpit;
		}
		system("$SNMPIT -X $pid $eid");
1345
		if ($?) {
1346
		    $msg .= "Failed to synchronize vlans";
1347
1348
1349
		    goto badsnmpit;
		}
	    }
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
	    else {
		my @diff = ();
		my @same = ();
	    
		if (Lan->CompareVlansWithSwitches($experiment, \@diff,\@same)) {
		    print STDERR "CompareVlansWithSwitches failed!\n";
		    goto badsnmpit;
		}
		if (@diff) {
		    system("$SNMPIT -f ". join(" ", map("-o $_", @diff)));
		    if ($?) {
			$msg .= "Failed to remove obsolete VLANs.";
			goto badsnmpit;
		    }
		}
		system("$SNMPIT -t $pid $eid");
		if ($?) {
		    $msg .= "Failed to setup vlans";
		    goto badsnmpit;
		}
1370
	    }
1371
1372
1373
1374
1375
1376
1377
1378
	    DebugTimeStamp("snmpit finished");
	    # Avoid END block processing
	    POSIX::_exit(0);
	    
	  badsnmpit:
	    print STDERR "Failed to setup vlans: $msg\n";
	    # Avoid END block processing
	    POSIX::_exit(-1);
1379
1380
	}
    }
1381
1382
    
    my @nodes = keys(%nodes);
1383
1384
1385
1386
1387
    my $rval  = 0;
    if (@nodes) {
	print STDERR "Calling os_setup @nodes\n";
	$rval = system("$OSSETUP $pid $eid @nodes");
	print STDERR "os_setup exited with status $rval\n";
1388
1389
	# Update to get the disk images into the manifest.
	GeniCM::UpdateManifest($slice);
1390
    }
1391

1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
    #
    # Check for cancelation. We skip all the logging and email.
    #
    if ($experiment->Canceled()) {
	print STDERR "ActionStart canceled; terminating early!\n";

	# Mark all thee nodes as canceled (which really means failure).
	foreach my $node (values(%nodes)) {
	    $node->_sliver()->SetStatus("canceled")
		if (defined($node->_sliver()));
	}
	# Reset before return; do not want it left.
	$slice->LockTables();
	# Do this first so others know we are reacting to the cancel.
	$slice->ClearMonitorPid();
	$experiment->SetCancelFlag(0);
	$slice->UnLockTables();
	$msg = "canceled; terminating early";
	goto bad;
    }

1413
    #
1414
1415
1416
    # See what nodes succeeded or failed. We want to hold off setting
    # the new state on the slivers until the end so that we do not flip
    # aggregate status to ready before we actually finish up in here. 
1417
1418
1419
1420
1421
    #
    foreach my $node_id (keys(%nodes)) {
	my $node = $nodes{$node_id};
	$node->Refresh();

1422
	# os_setup will set failed nodes to this state.
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
	if ($node->allocstate() eq TBDB_ALLOCSTATE_DOWN()) {
	    push(@failed, $node);
	    $node->_sliver()->SetState("failed")
		if (defined($node->_sliver()));
	}
	else {
	    $node->_sliver()->SetState("started")
		if (defined($node->_sliver()));
	}
	if (grep {$_ eq $node->eventstate()}
1433
	    (TBDB_NODESTATE_TBFAILED, TBDB_NODESTATE_RELOADFAILED)) {
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
	    my $bootlog;
	    if ($node->GetBootLog(\$bootlog) == 0 && $bootlog ne "") {
		my $logfile = Logfile->CreateFromString($group, $bootlog);
		if (defined($logfile)) {
		    $logfile->SetMetadata([["bootlog"   , $node->node_id()],
					   ["Method",     "reboot $node_id"],
					   ["slice_idx" , $slice->idx()],
					   ["slice_urn" , $slice->urn()],
					   ["slice_uuid", $slice->uuid()]], 1);
                     # Anon users can view the log if they know the secret id. 
		    $logfile->SetPublic(1);
		    $logfile->Store();
		    $node->_bootlog($logfile);
		}
	    }
	}
    }
    #
    # Notify.
    #
    if (@failed) {
	my $name   = $creator->name();
	my $email  = $creator->email();
	my $count  = scalar(@failed);
	my $urn    = $slice->urn();
1459
	my $purl   = $slice->GetPortalURL();
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
	my $logs   = "";

	foreach my $node (@failed) {
	    next
		if (!defined($node->_bootlog()));

	    $logs .= sprintf("%-15s : %s\n",
			     $node->node_id(), $node->_bootlog()->URL());
	}

	SENDMAIL("$name <$email>", "$count nodes failed to boot",
		 "Nodes:\n".
		 "  " . join(" ", @failed) . "\n".
		 "in $urn failed.\n\n" .
1474
1475
		 ($logs ne "" ? "$logs\n\n" : "") .
		 (defined($purl) ? "$purl\n" : ""),
1476
1477
		 $TBOPS, "Cc: $TBOPS");
    }
1478
1479
1480
1481
1482
1483
1484
1485
1486
    #
    # Must wait for snmpit to finish before we do anything else.
    #
    if (defined($snmpit_child)) {
	print STDERR "Waiting for snmpit process to finish\n";

	my $kid = waitpid($snmpit_child, 0);
	if ($kid == $snmpit_child) {
	    if ($?) {
1487
1488
		$msg .= "Failed to set up experimental networks\n";
		$bootfailure_code = GENIRESPONSE_SETUPFAILURE_NETWORK();
1489
1490
1491
1492
1493
1494
1495
		goto bad;
	    }
	    else {
		print STDERR "Waiting for snmpit process done\n";
	    }
	}
	else {
1496
1497
	    $bootfailure_code = GENIRESPONSE_SETUPFAILURE_NETWORK();
	    $msg .= "Waitpid for snmpit process problem: $kid";
1498
1499
1500
	    goto bad;
	}
    }
1501
1502
1503
1504
    if ($rval < 0) {
	# More serious error. Otherwise if its just that some nodes
	# failed, we will catch that below.
	$bootfailure_code = GENIRESPONSE_SETUPFAILURE_OSSETUP();
1505
	$msg .= "Unable to OS setup nodes\n";
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
	goto bad;
    }

    #
    # Before we fire off any async activity, push out any experiment
    # specific root private key.
    #
    my $privkey = $experiment->GetPrivkey();
    if ($privkey) {
	print STDERR "Pushing per-experiment root private key.\n";
	system("$PUSHROOTKEY -e $pid/$eid");
	if ($?) {
	    print STDERR "*** Could not push private key, ".
		"this may cause problems!\n";
	}
    }
    
    # Waiting is done. 
    if ($experiment->elab_in_elab()) {
	#
	# We cannot use ComputeState since it knows about elabinelab,
	# we need to know that all the nodes are ISUP, so we used the
	# @failed list returned from WaitForNodes().n
	#
	if (@failed) {
1531
1532
	    $msg .= "Some nodes did not boot, not doing elabinelab setup";
	    goto bad;
1533
1534
1535
	}
	print STDERR "Setting up elabinelab. This could take a while!\n";
	if (system("$ELAB_SETUP $pid $eid")) {
1536
1537
	    $msg .= "Failed to setup elabinelab!";
	    goto bad;
1538
1539
	}
    }
1540
1541
    elsif (($flags & $ACTION_FLAGS_NOEVENTSTART) == 0 && !@failed) {
	#
1542
1543
1544
	# Start the event scheduler. Note that the experiment is not
	# in the ACTIVE state, so the scheduler will not send the start
	# event. We do that explicitly.
1545
1546
1547
1548
1549
1550
1551
1552
1553
	#
	system("$EVENTSYS start $pid,$eid");
	if ($?) {
	    $msg .= "Failed to (re)start the event system";
	    if ($TB ne "/usr/testbed") {
		# Not sure why this is failing.
		print STDERR "$msg\n";
	    }
	    else {
1554
		$bootfailure_code = GENIRESPONSE_SETUPFAILURE_EVENTSYS();
1555
		goto bad;
1556
1557
	    }
	}
1558
1559
	print STDERR "Starting event time\n";
	system("$TEVC -e $pid/$eid now __ns_sequence start");
1560
    }
1561
1562
1563
1564
1565
1566
    if (0) {
	# Testing.
	@failed = values(%nodes);
    }
    if (@failed) {
	my @node_ids = map { $_->node_id() } @failed;
1567
	$self->SetBootFailure(GENIRESPONSE_SETUPFAILURE_BOOTFAILED());
1568
1569
1570
1571
1572
	$self->SetErrorLog("The following nodes failed to setup: " .
			   join(" ", @node_ids));
    }
    elsif (0) {
	# Testing.
1573
1574
	$self->SetBootFailure(GENIRESPONSE_SETUPFAILURE_NETWORK);
	$self->SetErrorLog("Testing network failure");
1575
1576
1577
1578
1579
    }
    # This has to be last so that SliverStatus() does not hand back a
    # ready or failed state until we are fully done here.
    $self->SetStatus("mixed");
    $self->ComputeState();
1580
1581
    $experiment->SetState($expstate);
    $slice->ClearMonitorPid();
1582
1583
1584
    return 0;

  bad:
1585
    $self->SetBootFailure($bootfailure_code);
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
    if (defined($msg)) {
	$self->SetErrorLog($msg);
	print STDERR "$msg\n";
    }
    # Mark the offending sliver as failed.
    if (defined($sliver)) {
	$sliver->SetStatus("failed");
	$sliver->SetErrorLog($msg)
	    if (defined($msg));
    }
1596
1597
1598
1599
    if ($self->status() eq "working") {
	$self->SetStatus("mixed");
	$self->ComputeState();
    }
1600
1601
    $experiment->SetState($expstate);
    $slice->ClearMonitorPid();
1602
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
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
    return -1;
}

#
# Reload all slivers. 
#
sub ActionReload($$;$)
{
    my ($self, $version, $flags) = @_;
    my @reload = ();

    my @slivers = ();
    if ($self->SliverList(\@slivers) != 0) {
	$self->SetErrorLog("Could not get sliver list for $self");
	return -1;
    }
    foreach my $sliver (@slivers) {
	next
	    if (ref($sliver) ne "GeniSliver::Node" &&
		ref($sliver) ne "GeniSliver::Vhost");
	
	push(@reload, $sliver);
    }

    #
    # Since this was an aggregate level reload, we have already forked
    # from the parent. Hand it off to BatchAction() to take care of the
    # rest, reload is simple so just pass it all the slivers. 
    #
    return $self->BatchAction("reload", @reload);
}

#
# Restart all slivers that need to be restarted.
#
sub ActionRestart($$;$)
{
    my ($self, $version, $flags) = @_;
    my @restart = ();

    my @slivers = ();
    if ($self->SliverList(\@slivers) != 0) {
	$self->SetErrorLog("Could not get sliver list for $self");
	return -1;
    }
    foreach my $sliver (@slivers) {
	next
	    if (ref($sliver) ne "GeniSliver::Node" &&
		ref($sliver) ne "GeniSliver::Vhost");
	
	push(@restart, $sliver);
    }

    #
    # Since this was an aggregate level reload, we have already forked
    # from the parent. Hand it off to BatchAction() to take care of the
    # rest, reload is simple so just pass it all the slivers. 
    #
    return $self->BatchAction("restart", @restart);
}

1663
#
1664
1665
1666
1667
# Start/Restart/reload all the slivers in the aggregate. Start is
# special since it sorta means reboot, and the only thing we reboot
# are nodes. And, since we might have multiple vnodes on a pnode, we
# want to be efficient about it.
1668
1669
1670
#
# XXX Is is assumed that there is a single toplevel aggregate for the
# slice, so we can get all the nodes.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1671
#
1672
sub Action($$$;$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1673
{
1674
    my ($self, $version, $action, $flags) = @_;
1675
    my $msg = "Internal Error: ";
1676
    my $bootfailure_code = GENIRESPONSE_SETUPFAILURE();
1677
1678
    my $restart = ($action eq "restart" ? 1 : 0);
    my $reload  = ($action eq "reload" ? 1 : 0);
1679
    $flags      = 0 if (!defined($flags));
Leigh B Stoller's avatar
Leigh B Stoller committed
1680
    require Lan;
1681
    require OSImage;