libosload_new.pm.in 68 KB
Newer Older
1
2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2000-2015 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
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#
# Osload library. Basically the backend to the osload script, but also used
# where we need finer control of loading of nodes.
#
package libosload_new;

use strict;
use Exporter;
use vars qw(@EXPORT $AUTOLOAD $MAXRETRIES);
use base qw( Exporter );

@EXPORT = qw( $MAXRETRIES );

# Must come after package declaration!
use libtestbed; # for TBGenSecretKey();
use libdb;
use libreboot;
use libtblog;
use Node;
use NodeType;
use Image;
use User;
use OSinfo;
use English;
use event;
use Data::Dumper;
49
use File::stat;
50
51
52
53
54
55
56
57
58
use IO::Handle;
use overload ('""' => 'Stringify');

# Configure variables
my $TB		= "@prefix@";
my $TESTMODE    = @TESTMODE@;
my $TBOPS       = "@TBOPSEMAIL@";
my $ELABINELAB  = @ELABINELAB@;
my $PROJROOT    = "@PROJROOT_DIR@";
59
60
my $WITHPROVENANCE= @IMAGEPROVENANCE@;
my $WITHDELTAS	= @IMAGEDELTAS@;
61
my $IMAGEINFO	= "$TB/sbin/imageinfo";
62

63
# Paths to binaries
64
my $TBUISP	    = "$TB/bin/tbuisp";
65

66
67
68
69
70
# XXX windows load
my $MAKECONF	    = "$TB/sbin/dhcpd_makeconf";
my $IMAGEX_OSNAME   = "IMAGEX-MFS";
my $IMAGEX_PXEPATH  = "/tftpboot/pxelinux/winpe";

71
72
73
74
75
76
#
# Max number of retries (per node) before its deemed fatal. This allows
# for the occasional pxeboot failure.
#
$MAXRETRIES  = 1;

77
78
79
80
81
82
83
#
# Hack constant factor (slop) to add to the max reload wait time for any node
# This is set based on testbed-wide factors (like multicast being dog slow!)
# XXX should this be exported like MAXRETRIES?
#
my $TBLOADWAIT  = (10 * 60);

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# Locals
my $remote_mult     = 5;        # Wait lots longer for remote nodes!

#
# The point of this is to create a data structure that we can
# pass around. 
#
sub New($$$;@)
{
    my ($class,@nodelist) = @_;

    my $self              = {};
    $self->{'HASH'}       = {};
    $self->{'CHILDREN'}   = {};
    $self->{'NODES'}      = {};
    $self->{'FLAGS'}      = {};
    $self->{'NODEFLAGS'}  = {};
    $self->{'NODEINFO'}   = {};
    $self->{'OSMAP'}      = {};
    $self->{'FAILED'}     = {};
    $self->{'FAILCOUNT'}  = 0;
    $self->{'TYPECACHE'}  = {};
    $self->{'TYPEOBJECTS'} = {};

    foreach my $node (@nodelist) {
	$self->{'NODES'}->{$node->node_id()} = $node;

	# Init some per-node stuff.
    }

    bless($self, $class);

    # We need this guy right away!
    $self->debug(0);

    return $self;
}
# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

    foreach my $key (keys(%{ $self })) {
	$self->{$key} = undef;
    }
}
sub nodelist($)		{ return $_[0]->{'NODES'}; }
sub failedlist($)	{ return $_[0]->{'FAILED'}; }
sub user($)		{ return $_[0]->{'USER'}; }
sub experiment($)	{ return $_[0]->{'EXPT'}; }
sub incrfailcount($)    { $_[0]->{'FAILCOUNT'}++ }
sub failed($)           { return $_[0]->{'FAILCOUNT'}; }

136
137
sub dprint($$;@) {
    my ($self,$level,@args) = @_;
138
    print STDERR "$self " . join('',@args) . "\n"
139
	if ($self->debug() > $level);
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
}
sub dprintts($@) {
    my ($self,@args) = @_;
    TBDebugTimeStamp("$self " . join('',@args))
	if ($self->debug());
}

# Grab a node by node_id.
sub node($$)
{
    my ($self, $node_id) = @_;

    if (exists($self->{'NODES'}->{$node_id})) {
	return $self->{'NODES'}->{$node_id};
    }

    tbwarn "$self nodeobject lookup failed for $node_id!\n";
    return undef;
}

# Get/set a type object by node.
sub typeobject($$;$)
{
    my ($self, $nodeobject, $typeobject) = @_;
    my $node_id = $nodeobject->node_id();

    if (defined($typeobject)) {
	$self->{TYPEOBJECTS}->{$node_id} = $typeobject;
	return $typeobject;
    }

    if (exists($self->{TYPEOBJECTS}->{$node_id})) {
	return $self->{TYPEOBJECTS}->{$node_id};
    }
    return undef;
}

# Store/retrieve misc reload info for this node
sub nodeinfo($$$;$)
{
    my ($self,$nodeobject,$key,$data) = @_;
    if (!defined($nodeobject)) {
	tbwarn "$self nodeinfo called with $key and no node!\n";
    }
    my $node_id = $nodeobject->node_id();

    if (defined($data)) {
	$self->{NODEINFO}->{$node_id}->{$key} = $data;
188
	$self->dprint(3,"nodeinfo($node_id,$key) <- $data)");
189
190
191
192
193
	return $data;
    }
    if (exists($self->{NODEINFO}->{$node_id}->{$key})) {
	my $retval = $self->{NODEINFO}->{$node_id}->{$key};
	my $pretval = defined($retval) ? $retval : "undef";
194
	$self->dprint(3,"nodeinfo($node_id,$key) -> $pretval");
195
196
197
198
199
200
	return $retval;
    }
    return undef;
}
sub nodeinfo_unset($$$)
{
201
    my ($self,$nodeobject,$key) = @_;
202
    if (!defined($nodeobject)) {
203
	tbwarn "$self nodeinfo_unset called with $key and no node!\n";
204
205
206
    }
    my $node_id = $nodeobject->node_id();
    
207
    $self->dprint(3,"nodeinfo_unset($nodeobject,$key)");
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
    if (exists($self->{NODEINFO}->{$node_id}->{$key})) {
	delete $self->{NODEINFO}->{$node_id}->{$key};
    }
    
    return 0;
}

# Store/retrieve osload flags.  Check the per-node flags first, then
# the global flags.
sub nodeflag($$$;$)
{
    my ($self,$nodeobject,$flagname,$flagval) = @_;

    my $retval;

    my $node_id = $nodeobject->node_id();
    if (defined($flagval)) {
	$self->{NODEFLAGS}->{$node_id}->{$flagname} = $flagval;
	$retval = $flagval;
    }
    elsif (exists($self->{NODEFLAGS}->{$node_id}->{$flagname})) {
	$retval = $self->{NODEFLAGS}->{$node_id}->{$flagname};
    }
    elsif (exists($self->{FLAGS}->{$flagname})) {
	$retval = $self->{FLAGS}->{$flagname};
    }

    my $pretval = defined($retval) ? $retval : "undef";
236
    $self->dprint(2,"nodeflag($node_id,$flagname) -> $pretval");
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279

    return $retval;
}
    
# Get/Set the osid->osinfo mapping. Nice to keep this to avoid lookups.
sub osmap($$;$)
{
    my ($self, $osid, $osinfo) = @_;

    if (defined($osinfo)) {
	return $self->{'OSMAP'}->{$osid} = $osinfo;
    }
    elsif (exists($self->{'OSMAP'}->{$osid})) {
	return $self->{'OSMAP'}->{$osid};
    }
    return undef;
}

# To avoid writing out all the methods.
sub AUTOLOAD {
    my $self = shift;
    my $type = ref($self) or die("$self is not an object\n");

    my $name = $AUTOLOAD;
    $name =~ s/.*://;   # strip fully-qualified portion

    if (@_) {
	return $self->{'HASH'}->{$name} = shift;
    }
    elsif (exists($self->{'HASH'}->{$name})) {
	return $self->{'HASH'}->{$name};
    }
    print STDERR "libosload_new: tried to access unknown slot $name\n";
    return undef;
}

#
# Create a type (or class) specific object to handle those nodes.
#
sub NewType($$)
{
    my ($self, $type) = @_;

280
    $self->dprint(2,"NewType($type): trying to create type object");
281
282
283
284
285

    my $packname = "libosload_${type}";
    my $newtype  = eval { $packname->New($self); };
    # Not loaded?
    if ($@) {
286
	$self->dprint(2,"NewType($type): simple module load failed: " . $@);
287
	eval "require libosload_${type}";
288
289
	$newtype  = eval { $packname->New($self); };
	if ($@) {
290
	    $self->dprint(1,"$self NewType($type): module load failed: " . $@);
291
292
293
294
295
	    return undef;
	}
    }
    $self->{'TYPECACHE'}->{$type} = $newtype;
    
296
    $self->dprint(3,"NewType($type): created type object $newtype");
297
298
299
300
301
302
303
304
305
306
307
308
309
    
    return $newtype;
}

#
# Return the cached type object.
#
sub TypeLookup($$;$)
{
    my ($self, $nodeobject, $forcedtype) = @_;

    my $type  = $nodeobject->type();
    my $class = $nodeobject->class();
310
    my $node_id = $nodeobject->node_id();
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349

    if (defined($forcedtype)) {
	return $self->{'TYPECACHE'}->{$forcedtype}
            if (exists($self->{'TYPECACHE'}->{$forcedtype}));
    }
    else {
	return $self->{'TYPECACHE'}->{$type}
            if (exists($self->{'TYPECACHE'}->{$type}));

	return $self->{'TYPECACHE'}->{$class}
            if (exists($self->{'TYPECACHE'}->{$class}));
    }

    return undef;
}

sub ChildCreate($$;$)
{
    my ($self,$data,$child_writer_ptr) = @_;

    #
    # Create a pipe to read back results from the child we will create.
    #
    my $PARENT_READER = new IO::Handle; # Need a new handle for each child
    my $CHILD_WRITER = new IO::Handle; # Need a new handle for each child
    if (! pipe($PARENT_READER, $CHILD_WRITER)) {
	tberror "creating pipe: $!";
	return -1;
    }
    if (defined($child_writer_ptr)) {
	$$child_writer_ptr = $CHILD_WRITER;
    }
    $CHILD_WRITER->autoflush(1);

    if (my $childpid = fork()) {
	close($CHILD_WRITER);

	$self->{CHILDREN}->{$childpid} = [ $PARENT_READER, $data ];

350
	$self->dprint(4,"ChildCreate: created $childpid");
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401

	return $childpid;
    }

    #
    # Child keeps going. 
    #
    close($PARENT_READER);
    TBdbfork();

    return 0;
}

sub ChildReap($)
{
    my ($self,$childpid) = @_;

    my $childdataptr;
    if (exists($self->{CHILDREN}->{$childpid})) {
	$childdataptr = $self->{CHILDREN}->{$childpid};
    }
    else {
	tberror "$self ChildReap: no such child pid $childpid!"; # INTERNAL
	return -1;
    }
    my ($PARENT_READER, $data) = @$childdataptr;

    #
    # Read back the results.
    # 
    my @output = ();
    while (<$PARENT_READER>) {
	push @output, $_;
    }
    
    #
    # And get the actual exit status.
    # 
    waitpid($childpid, 0);
    return ($data,$? >> 8,@output);
}

#
# XXX -- shoudl teh API change to use the object more?
#
sub osload($$$) {
    my ($self, $args, $result) = @_;
    my $CHILD_WRITER;

    $self->dprintts("osload starting on nodes " . join(' ',@{$args->{'nodelist'}}));

402
    # set some default flags
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
    my %flags = ();
    $flags{waitmode}    = 1;
    $flags{usecurrent}  = 0;
    $flags{noreboot}    = 0;
    $flags{asyncmode}   = 0;
    $flags{zerofree}    = 0;
    $flags{prepare}     = 0;
    $flags{swapinfo}    = 0;

    # These come in from the caller.
    my @imageids;
    my @nodes       = ();
    my %nodeflags   = ();

    # Locals
    my $mereuser    = 0;
    my $rowref;
    my @images;
    my $this_user;

    if (!defined($args->{'nodelist'})) {
	tberror "Must supply a node list!"; # INTERNAL
	return -1;
    }
    @nodes = sort(@{ $args->{'nodelist'} });

    #
    # Although the object can support multiple osloads in flight at once,
    # don't allow multiple reloads per node in different osload invocations!
    #
    foreach my $node (@nodes) {
	if (exists($self->{NODES}->{$node})) {
	    tberror "$self is already loading $node!\n";
	    return -1;
	}
    }
439
440
441
442

    # override our defaults
    foreach my $flag (keys(%$args)) {
	$flags{$flag} = $args->{$flag};
443
    }
444
    # handle some of the flags specially
445
446
447
448
449
450
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
    if (defined($args->{'imageid'})) {
	@imageids = split(/,/, $args->{'imageid'});
    }
    if (defined($args->{'imageids'})) {
	@imageids = @{$args->{'imageids'}};
    }
    if (defined($args->{'nodeflags'})) {
	%nodeflags = %{$args->{'nodeflags'}};
    }

    $self->{FLAGS} = \%flags;

    if (!$self->debug() || $flags{asyncmode}) {
	#
	# Start a new logging sub-process
	#
	my $old_env = \%ENV;
	local %ENV;
	copy_hash %ENV, $old_env;
	tblog_sub_process("osload", @nodes);
    }

    #
    # Figure out who called us. Root and admin types can do whatever they
    # want. Normal users can only change nodes in experiments in their
    # own projects.
    #
    if ($UID) {
	$this_user = User->ThisUser();
	return -1
	    if (!defined($this_user));

	if (!$this_user->IsAdmin()) {
	    $mereuser = 1;

	    if (! TBNodeAccessCheck($UID, TB_NODEACCESS_LOADIMAGE, @nodes)) {
		tberror("Not enough permission to load images on one or ".
			"more nodes!");
		return -1;
	    }
	}
    }

    foreach my $i (0 .. $#imageids) {
	my $imageid = $imageids[$i];
	$images[$i] = Image->Lookup($imageid);
	my $image = $images[$i];
	if (!defined($image)) {
	    tberror("Could not map $imageid to its object!");
	    return -1;
	}

	#
	# Check permission to use the imageid.
	# 
	if ($mereuser &&
	    ! $image->AccessCheck($this_user, TB_IMAGEID_READINFO)) {
	    tberror "You do not have permission to load $image";
	    return -1;
	}

	#
	# If there's a maxiumum number of concurrent loads listed for the image,
	# check to see if we'll go over the limit, by checking to see how many
	# other nodes are currently booting thie image's default_osid. This is
	# NOT intended to be strong enforcement of license restrictions, just a
	# way to catch mistakes.
	#
	if (!TBImageLoadMaxOkay($image->imageid(), scalar(@nodes), @nodes)) {
	    tberror 
	    "Would exceed maxiumum concurrent instances ".
		"limitation for $image";
	    return -1;
	}

	# 
	# XXX should we do this?
	# Load up the imageinfo before we fork to minimize queries and maximize
	# mem sharing.
	#
525
	#$self->GetImageInfo($image,...);
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
    }

    #
    # This is somewhat hackish. To promote parallelism during os_setup, we
    # want to fork off the osload from the parent so it can do other things.
    # The problem is how to return status via the results vector. Well,
    # lets do it with some simple IPC. Since the results vector is simply
    # a hash of node name to an integer value, its easy to pass that back.
    #
    # We return the pid to the caller, which it can wait on either directly
    # or by calling back into this library if it wants to actually get the
    # results from the child!
    # 
    if ($flags{asyncmode}) {
	my $retval = $self->ChildCreate([ $result,$args ],\$CHILD_WRITER);
	if ($retval < 0) {
	    tberror "$self: create child: $!";
	    return -1;
	}
	elsif ($retval) {
	    foreach my $node (@nodes) {
		# All nodes start out as being failed from the parent's perspective; altered later as needed.
		$result->{$node} = -1;
	    }
	    return $retval;
	}
	#
	# Child continues
	#
    }

557
    my %access_keys = ();
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
    # Loop for each node.
    foreach my $node (@nodes) {
	# All nodes start out as being successful; altered later as needed.
	$result->{$node} = 0;

	# Try to find the node before doing anything else.
	my $nodeobject = Node->Lookup($node);
	if (!defined($nodeobject)) {
	    tberror "$node: Could not map to object!";
	    goto failednode;
	}

	#
	# Look for type specific module first.
	#
	my $forcedtype;
	$nodeobject->NodeAttribute('osload_objtype',\$forcedtype);
	if (!defined($forcedtype)) {
	    $nodeobject->NodeTypeAttribute('osload_objtype',\$forcedtype);
	}
	my $object = $self->TypeLookup($nodeobject,$forcedtype);
	if (!defined($object)) {
	    $object = $self->NewType(defined($forcedtype) ? $forcedtype 
				                          : $nodeobject->type());
	    if (defined($forcedtype) && !defined($object)) {
		#
		# If they shoot themselves in the foot, their fault!
		# Don't fall back to real type or class!
		#
		die_noretry("$self: could not find type object for forced type $forcedtype -- check your attributes!");
	    }
	    elsif (!defined($object)) {
		#
		# Otherwise use the class.
		#
		$object = $self->NewType($nodeobject->class());
		if ($@) {
David Johnson's avatar
David Johnson committed
595
		    die_noretry("$self: no type/class specific osload module for $node");
596
597
598
		}
	    }

599
	    $self->dprint(2,"osload($node): used typeobject $object");
600
601
602
603
604
605
606
607
608
609
610
	}

	# Save off this type object for this node
	$self->typeobject($nodeobject,$object);

	# Construct a local copy of per-image flags overridden by per-node
	# flags
	my %nargs = ();
	foreach my $k (keys(%flags)) {
	    $nargs{$k} = $flags{$k};
	}
611
	foreach my $k (keys(%{$nodeflags{$node}})) {
612
613
	    $nargs{$k} = $nodeflags{$node}{$k};
	}
614
615
616
617
618

	# XXX: this probably belongs in the code calling into libosload?
	# Check to see if the node is tainted.  If so, then the disk
	# needs to be cleaned up (zeroed).
	if ($nodeobject->IsTainted()) {
619
	    $nargs{'zerofree'} = 2;
620
621
	}

622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
	# Wait, don't do this -- waitmode is global; nowait is per-node!
	#
        # XXX hack to handle that we would see a 'nowait' flag per-node,
	# but a 'waitmode' flag globally.  Since we now just have per-node flags
	# available to the type-specific objects, we just override waitmode.
	#if (exists($nargs{nowait})) {
	#    $nargs{waitmode} = $nargs{nowait};
	#}

	#
	# Add the node with the given images and arguments
	#
	if ($object->AddNode($nodeobject,\@images,\%nargs)) {
	    goto failednode;
	}
	# We also need to add it to ourself for non-type-specific metadata
	# storage
	if ($self->AddNode($nodeobject,\@images,\%nargs)) {
	    goto failednode;
	}
	$self->typeobject($nodeobject,$object);
	
	#
	# Setup a bunch of database state before setting up the actual reload:
	# setting the boot osid, adjusting the partitions table, setting up
	# swapinfo.
	#
	if ($object->PreSetupReload($nodeobject)) {
	    goto failednode;
	}
652

653
654
655
656
657
	#
	# This is a bad place for this, but it has to go somewhere, and handling
	# remote nodes is not really a type-specific thing!  It's more a 
	# feature mixin than a type-specific class!
	#
658
659
660
661
662
663
	foreach my $image (@images) {
	    # This is passed along so that remote node can request the file.
	    # Make sure the image object has an access key defined.
	    if (defined($image->access_key()) && $image->access_key() ne '') {
		$access_keys{$image} = $image->access_key();
	    }
David Johnson's avatar
David Johnson committed
664
	    elsif ($nodeobject->isremotenode() && !defined($access_keys{$image})) {
665
666
		$access_keys{$image} = TBGenSecretKey();
		
David Johnson's avatar
David Johnson committed
667
668
		if ($image->Update({'access_key' => $access_keys{$image}}) != 0) {
		    tberror "$self ($node): Could not initialize image access key";
669
670
671
672
		    goto failednode;
		}
	    }
	}
673
674
675
676

	#
	# Setup the reload, finally!
	#
677
	print "$object: setting up reload for $node\n";
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709

	if (!$TESTMODE) {
	    if ($object->SetupReload($nodeobject)) {
		tberror("$self ($node): Could not set up reload. Skipping.");
		goto failednode;
	    }

	    if ($object->Reload($nodeobject)) {
		tberror("$self ($node): direct reload failed. Skipping.");
		goto failednode;
	    }
	}

	next;
	
      failednode:
	$object->RemoveNode($nodeobject);
	$self->RemoveNode($nodeobject);
	$result->{$node} = -1;
	$self->incrfailcount();
    }

    #
    # Remove any failed nodes from the list we are going to operate on.
    #
    my @temp = ();
    foreach my $node (@nodes) {
	push(@temp, $node)
	    if (! $result->{$node});
    }
    @nodes = @temp;

710
711
    TBDebugTimeStamp("osload: database setup done");

712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
    # Exit if not doing an actual reload.
    if ($TESTMODE) {
	print "$self: Stopping in Testmode!\n";
	goto done;
    }

    if (! @nodes) {
	tbnotice "$self: Stopping because of previous failures!";
	goto done;
    }

    # Fire off a mass reboot and quit if not in waitmode.
    if (!$flags{waitmode}) {
	my ($reboot_nodes, $noreboot_nodes)
	    = $self->GetNodesRequiringReboot(@nodes);
	if (@$reboot_nodes) {
	    print "$self: Rebooting nodes.\n";

	    my %reboot_args     = ();
	    my %reboot_failures = ();

	    $reboot_args{'debug'}    = $self->debug();
	    $reboot_args{'waitmode'} = 0;
	    $reboot_args{'nodelist'} = [ @$reboot_nodes ];

	    if (nodereboot(\%reboot_args, \%reboot_failures)) {
		foreach my $node (@$reboot_nodes) {
		    if ($reboot_failures{$node}) {
			$result->{$node} = $reboot_failures{$node};
			$self->incrfailcount();
		    }
		}
	    }
	}
	goto done;
    }

    #
    # The retry vector is initialized to the number of retries we allow per
    # node, afterwhich its a fatal error.
    #
    foreach my $node (@nodes) {
	my $nodeobject = $self->node($node);
	my $typeobject = $self->typeobject($nodeobject);
	$self->nodeinfo($nodeobject,'retries',$typeobject->GetMaxRetries());
    }

    #
    # XXX not all type objects will need/want events to signal completion,
    # so we could eventually separate this out, but not for now.
    #
    # Callback for our event handler. We use a "closure" so it can
    # reference the list of nodes that we are currently waiting on.
    #
    my $eventnodes = undef;
    my $handler = sub {
	my ($handle, $notification, undef) = @_;
    
	my $node_id = event_notification_get_objname($handle,$notification);
	my $event   = event_notification_get_eventtype($handle,$notification);

	return
	    if (!defined($eventnodes));

776
	$eventnodes->{'GOTONE'} = 1;
777
	if (exists($eventnodes->{$node_id})) {
778
	    my $et = time();
779
	    if ($self->debug()) {
780
781
782
		print "$self: eventhandler: $node_id => $event @ $et\n"
	    }
	    $eventnodes->{$node_id} = $et;
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
	}
    };
    my $evhandle = $self->SetupEventHandler($handler);
    if (!defined($evhandle)) {
	tbnotice "$self: Stopping because event registration failed!";
	foreach my $node (@nodes) {
	    $result->{$node} = -1;
	    $self->incrfailcount();
	}
	goto done;
    }

    while (@nodes) {
	my ($reboot_nodes, $noreboot_nodes)
	    = $self->GetNodesRequiringReboot(@nodes);
	if (@$reboot_nodes) {
	    # Reboot them all.
	    print "$self: ".
		"Issuing reboot for @$reboot_nodes and then waiting ...\n";

	    # Prime the event handler above.
	    $eventnodes = {} if (!defined($eventnodes));
	    foreach my $node (@$reboot_nodes) {
		$eventnodes->{$node} = 0;
	    }
808
	    $self->dprintts("event handler enabled");
809
810
811
812
813
814
815
816
817
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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
	    
	    my %reboot_args     = ();
	    my %reboot_failures = ();

	    $reboot_args{'debug'}    = $self->debug();
	    $reboot_args{'waitmode'} = 0;
	    $reboot_args{'nodelist'} = [ @$reboot_nodes ];

	    if (nodereboot(\%reboot_args, \%reboot_failures)) {
		#
		# If we get any failures in the reboot, we want to
		# alter the list of nodes accordingly for the next phase.
		# 
		my @temp = ();
		
		foreach my $node (@$reboot_nodes) {
		    if ($reboot_failures{$node}) {
			$result->{$node} = $reboot_failures{$node};
			$self->incrfailcount();
		    }
		    else {
			push(@temp, $node);
		    }
		}
		@nodes = (@temp,@$noreboot_nodes);
	    }
	}

	# Now wait for them.
	my $startwait   = time;
	my @failednodes = $self->WaitTillReloadDone($startwait,
						    $flags{waitmode},
						    $eventnodes,
						    $evhandle,
						    @nodes);
				
	@nodes = ();
    
	while (@failednodes) {
	    my $node = shift(@failednodes);
	    my $nodeobject = $self->node($node);
	    my $typeobject = $self->typeobject($nodeobject);

	    my $retries = $self->nodeinfo($nodeobject,'retries');
	    if ($retries) {
		tbnotice "$self ($node): Trying again ...";

		# Possible race with reboot?
		if ($typeobject->SetupReload($nodeobject) < 0) {
		    tberror("$self ($node): Could not set up reload. Skipping.");
		    $result->{$node} = -1;
		    $self->incrfailcount();
		    $typeobject->ReloadDone($nodeobject);
		    next;
		}

		if ($typeobject->Reload($nodeobject) < 0) {
		    tberror("$self ($node): direct reload failed. Skipping.");
		    $result->{$node} = -1;
		    $self->incrfailcount();
		    $typeobject->ReloadDone($nodeobject);
		    next;
		}

		push(@nodes, $node);

		# Retry until count hits zero.
		$self->nodeinfo($nodeobject,'retries',$retries - 1);
	    }
	    else {
		tberror ({sublevel => -1}, 
			 "$self: $node failed to boot too many times. Skipping!");
		$result->{$node} = -1;
		$typeobject->ReloadDone($nodeobject);
		$self->incrfailcount();
	    }
	}
    }
  done:
    my $failures = $self->failed();
    print "$self: Done! There were $failures failures.\n";

    if ($flags{asyncmode}) {
892
	$self->dprint(3,"osload: asyncmode osload writing results");
893
894
895
896
897
898
	#
	# We are a child. Send back the results to the parent side
	# and *exit* with status instead of returning it.
	# 
	foreach my $node (keys(%{ $result })) {
	    my $status = $result->{$node};
899
	    $self->dprint(3,"osload: asyncmode osload writing result ($node,$status)");
900
901
902
903
	    print $CHILD_WRITER "$node,$status\n";
	}
	close($CHILD_WRITER);

904
	$self->dprintts("osload: asyncmode finished");
905
906
907
908

	exit($failures);
    }

909
    $self->dprintts("osload: finished");
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
    return $failures;
}

sub GetMaxRetries($)
{
    return $MAXRETRIES;
}

#
# Add a node to the list.  This should of course be overridden -- this is just
# a basic version for the libosload_new main package!  And of course, 
# libosload_common does override it.
#
sub AddNode($$$$)
{
    my ($self, $nodeobject, $imagelist, $args) = @_;
    my $node_id = $nodeobject->node_id();

928
    $self->dprint(0,"AddNode($node_id): starting");
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945

    $self->{'NODES'}->{$node_id}    = $nodeobject;
    $self->{'NODEFLAGS'}->{$node_id}    = $args;
    $self->{'IMAGES'}->{$node_id}   = $imagelist;

    return 0;
}

# Wait for a reload to finish by watching its state
sub WaitTillReloadDone($$$$$@)
{
    my ($self, $startwait, $waitmode,
	$eventnodes, $evhandle, @nodes) = @_;
    my %done	= ();
    my $count   = @nodes;
    my @failed  = ();

946
    $self->dprintts("WaitTillReloadDone(" . join(',',@nodes) . ") starting");
947
948
949
950
951
952
953
954
955
956
957
958
959

    foreach my $node ( @nodes ) {
	my $nodeobject = $self->node($node);
	if (1 && !$self->nodeflag($nodeobject,'nowait')) {
	    $done{$node} = 0;
	}
	else {
	    $done{$node} = 1;
	    --$count;
	    print "$self: not waiting for reload of $node.\n";
	}
    }

960
    $self->dprint(1,"WaitTillReloadDone(" . join(',',@nodes) . "): waiting for nodes to finish reloading (".`date`.")")
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
991
992
993
994
995
996
	if ($count && $self->debug());

    # figure out our per-node max wait times
    foreach my $node (@nodes) {
	my $nodeobject = $self->node($node);
	my $typeobject = $self->typeobject($nodeobject);
	my $maxwait;

	#
	# If we have to zero fill free space, then the
	# wait time has to be proportional to the disk
	# size.  In other words, a really, really, really
	# long time.  Lets assume 20MB/sec to blast zeros,
	# so 50 seconds/GB.  What the heck, lets call it
	# 1GB/minute.  Did I mention how this would take
	# a really long time?
	#
	# Else, if we have a remote node, we wait another multiplier.
	#
	if ($self->nodeflag($nodeobject,'zerofree')) {
	    my $disksize = $nodeobject->disksize();

	    $disksize = 20
		if (!$disksize);
	    $maxwait = ($disksize * 60);
	} elsif ($nodeobject->isremotenode()) {
	    $maxwait = $typeobject->ComputeMaxLoadWaitTime($nodeobject) * $remote_mult ;
	} else {
	    $maxwait = $typeobject->ComputeMaxLoadWaitTime($nodeobject);
	}

	$self->nodeinfo($nodeobject,'maxwait',$maxwait);
    }

    # Start a counter going, relative to the time we rebooted the first
    # node.
997
    $self->dprintts("starting reload-done wait");
998
999
1000
    my $waittime  = 0;
    my $minutes   = 0;

1001
1002
1003
1004
1005
1006
1007
1008
1009
    #
    # Should-be-parameters:
    #
    # REBOOTWAIT: time in minutes to make a transition after reboot
    # MAXEVENTS: max events to grab in any event_poll loop
    #
    my $REBOOTWAIT = 5;
    my $MAXEVENTS = 500;

1010
    my $ecount = 1;
1011
1012
1013
    while ($count > 0) {
	# Wait first to make sure reboot is done, and so that we don't
	# wait one more time after everyone is up.
1014
1015
1016
	if ($ecount > 0) {
	    sleep(5)
	}
1017
	my $ecount = $MAXEVENTS;
1018
1019
1020
1021
	do {
	    $eventnodes->{'GOTONE'} = 0;
	    event_poll($evhandle);
	} while ($eventnodes->{'GOTONE'} && --$ecount > 0);
1022
1023
1024
	if ($ecount < $MAXEVENTS) {
	    $self->dprint(2, "got ", $MAXEVENTS-$ecount, " events\n");
	}
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
	foreach my $node (@nodes) {
	    if (! $done{$node}) {
		my $nodeobject = $self->node($node);
		my $typeobject = $self->typeobject($nodeobject);
		my $maxwait = $self->nodeinfo($nodeobject,'maxwait');

		#
		# If we did a direct reload via typeobject->Reload(), we 
		# need to ask teh typeobject when the reload finishes (or
		# at least try, so it can 1) garbage collect the childpid
		# state, and 2) potentially tell us what happened!).
		#
		# Of course, if the typeobject tells us not to expect anything,
		# we don't worry about it, and instead query via the methods
		# below.
		#
		my ($typewaitstatus,$typeretval,@typeoutput) = 
		    $typeobject->WaitForNode($nodeobject);
1043
		$self->dprint(2,"$typeobject->WaitForNode($node) -> $typewaitstatus");
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
		if ($typewaitstatus > 0) {
		    --$count;
		    if ($typeretval) {
			$done{$node} = $waitmode;
			push @failed, $node;
		    }
		    else {
			# success!
			$count--;
			$done{$node} = 1;
			$typeobject->ReloadDone($nodeobject);
		    }
		    next;
		}
		elsif ($typewaitstatus == 0) {
		    # we need to keep waiting for this node, so don't check
		    # the db
		    ;
		}
		else {
		    # we haven't done a direct reload, so poll the db
		    my $query_result =
			DBQueryWarn("select * from current_reloads ".
				    "where node_id='$node'");

		    #
		    # There is no point in quitting if this query fails. Just
		    # try again in a little bit.
		    # 
		    if (!$query_result) {
			tbwarn "$self ($node): Query failed; waiting a bit.";
			next;
		    }

		    #
		    # We simply wait for stated to clear the current_reloads entry.
		    #
		    if (!$query_result->numrows) {
1082
			$self->dprint(1,"$self: WaitTillReloadDone($node): left reloading mode at ".`date`)
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
			    if ($self->debug());
		    
			$count--;
			$done{$node} = 1;
			$typeobject->ReloadDone($nodeobject);
			next;
		    }
		}

		#
		# All of the eventstate stuff belongs in stated. Sheesh.
		#
		my $eventstate;
		if ($nodeobject->GetEventState(\$eventstate)) {
1097
		    $self->dprint(2,"$self ($node): Could not get event state");
1098
1099
1100
1101
1102
1103
1104
		}
	
		# Soon we will have stated's timeouts take care of
		# rebooting once or twice if we get stuck during
		# reloading.
		$waittime = time - $startwait;
		
1105
1106
1107
		# If the node doesn't made a transition within $REBOOTWAIT
		# minutes of booting, we declare it stuck.
		my $isstuck = ($minutes > $REBOOTWAIT &&
1108
1109
			       exists($eventnodes->{$node}) &&
			       $eventnodes->{$node} == 0);
1110

1111
		if ($waittime > $maxwait ||
1112
1113
1114
		    $eventstate eq TBDB_NODESTATE_TBFAILED() ||
		    $eventstate eq TBDB_NODESTATE_PXEFAILED() ||
		    $isstuck) {
1115
1116
1117
1118
1119
1120

		    #
		    # If we are in reloading, then we obviously missed
		    # a state transition in our handler. Probably just
		    # need to increase $MAXEVENTS above.
		    #
1121
1122
		    if ($isstuck &&
			$eventstate eq TBDB_NODESTATE_RELOADING()) {
1123
1124
1125
1126
1127
1128
			tbnotice("$self: missed state transition to RELOADING".
				 " for $node; faking it.");
			$eventnodes->{$node} = time();
			goto okay;
		    }

1129
1130
1131
1132
		    my $t = (int ($waittime / 60));
		    tbnotice "$self: $node appears wedged; ".
			"it has been $t minutes since it was rebooted.";

1133
1134
		    if ($eventstate eq TBDB_NODESTATE_TBFAILED() ||
			$eventstate eq TBDB_NODESTATE_PXEFAILED()) {
1135
1136
1137
1138
			tbnotice("$self: $node is stuck in $eventstate.");
		    }
		    elsif ($eventstate eq TBDB_NODESTATE_RELOADING()) {
			tbnotice("$self: $node did not finish reloading.");
1139
		    }
1140
		    elsif ($isstuck) {
1141
1142
1143
			tbnotice("$self: $node failed to make a state ".
				 "transition after $REBOOTWAIT minutes; ".
				 "stuck in $eventstate.");
1144
1145
1146
1147
1148
1149
1150
1151
		    }
		    TBNodeConsoleTail($node, *STDERR);

		    $count--;
		    $done{$node} = $waitmode;
		    push(@failed, $node);
		    next;
		}
1152
	      okay:
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
		if (int($waittime / 60) > $minutes) {
		    $minutes = int($waittime / 60);
		    print STDERR "$self ($node): still waiting; ".
			"it has been $minutes minute(s)\n";
		}
	    }
	}
    }

    if ($waitmode > 1) {
	$startwait = time;
	foreach my $node (@nodes) {
	    print STDERR
		"$self ($node): waiting for node to finish booting\n";
	    if ($done{$node} < $waitmode) {
		my $actual_state;

		if (!TBNodeStateWait($node,
				     $startwait,
				     (60*6),
				     \$actual_state,
				     (TBDB_NODESTATE_TBFAILED,
				      TBDB_NODESTATE_PXEFAILED,
				      TBDB_NODESTATE_ISUP))) {
		    $done{$node} = $waitmode;
		} else {
		    push(@failed, $node);
		}
	    }
	}
    }

1185
    $self->dprintts("WaitTillReloadDone(" . join(',',@nodes) . "): finished");
1186
1187
1188
1189

    return @failed;
}

1190
1191
1192
1193
1194
1195
1196
1197
#
# Grab the size and update the database.
#
sub GetImageSize($$$)
{
    my ($self, $image, $node) = @_;
    my $imagesize = 0;
    my $imagepath = $image->FullImageFile();
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
    #
    # Perform a few validity checks: imageid should have a file name
    # and that file should exist.
    #
    if (!defined($imagepath)) {
	tberror "No filename associated with $image!";
	return -1;
    }

    if (! -R $imagepath) {
	#
	# There are two reasons why a legit image might not be readable.
	# One is that we are in an elabinelab and the image has just not
	# been downloaded yet. The other is that we are attempting to
	# access a shared (via the grantimage mechanism) image which the
	# caller cannot directly access.
	#
	# For either case, making a proxy query request via frisbee will
	# tell us whether the image is accessible and, if so, its size.
	# "imageinfo" makes that call for us.
	#
	my $frisimageid = $image->pid() . "/" . $image->imagename();
	my $sizestr = `$IMAGEINFO -qs -N $node $frisimageid`;
	if ($sizestr =~ /^(\d+)$/) {
	    $imagesize = $1;
	} else {
	    tberror "$image: access not allowed or image does not exist.";
	    return -1;
	}
    } else {
	$imagesize = stat($imagepath)->size;
    }

    #
    # A zero-length image cannot be right and will result in much confusion
    # if allowed to pass: the image load will succeed, but the disk will be
    # unchanged, making it appear that os_load loaded the default image.
    #
    if ($imagesize == 0) {
	tberror "$imagepath is empty!";
	return -1;
    }
    $image->SetFullSize($imagesize);
    return 0;
}
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276

#
# Return two array references (possbily empty) of:
# [all nodes requiring reboot, all nodes not requiring reboot]
#
sub GetNodesRequiringReboot($@) {
    my ($self,@nodes) = @_;
    my (@reboot, @noreboot);

    foreach my $node_id (@nodes) {
	my $nodeobject = $self->node($node_id);
	my $typeobject = $self->typeobject($nodeobject);
	if (!$typeobject->nodeflag($nodeobject,'noreboot')) {
	    push @reboot, $nodeobject->node_id();
	}
	else {
	    push @noreboot, $nodeobject->node_id();
	}
    }

    return (\@reboot, \@noreboot);
}

#
# This gets called in the parent, to wait for an async osload that was
# launched earlier (asyncmode). The child will print the results back
# on the the pipe that was opened between the parent and child. They
# are stuffed into the original results array.
# 
sub osload_wait($$)
{
    my ($self,$childpid) = @_;

1277
    $self->dprintts("osload_wait($childpid): starting");
1278
1279
1280
1281
1282
1283
1284
1285
1286

    my ($data,$retval,@output) = $self->ChildReap($childpid);
    my ($result,$args) = @$data;

    foreach my $line (@output) {
	chomp($line);

	if ($line =~ /^([-\w]+),([-\d])+$/) {
	    $result->{$1} = $2;
1287
	    print STDERR "$self osload_wait($1): child returned $2 status.\n";
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
	}
	else {
	    tberror "$self osload_wait: improper response from child: $_"; # INTERNAL
	}
    }

    $self->dprintts("osload_wait($childpid) finished");

    return $retval;
}

#
# Save signature files and boot partition info for all nodes in an experiment
# (or just the listed nodes).  We call this when swapping in an experiment or
# when reloading nodes in an experiment.
#
# Note that this is not strictly an os loading function, we do it on swapins
# of nodes which already have the correct OS as well.  But we stick it here
# because it is about os loading in principle.
#
sub osload_setupswapinfo($$$;@)
{
    my ($self, $pid, $eid, @nodelist) = @_;
    my %nodeinfo = ();
    my $allnodes;
    my $clause = "";

    if (!@nodelist) {
	@nodelist = ExpNodes($pid, $eid, 1, 0);
	$clause .= "r.pid='$pid' and r.eid='$eid'";
	$allnodes = 1;
    } else {
	$clause .= "r.node_id in (" . join(",", map("'$_'", @nodelist)) . ")";
	$allnodes = 0;
    }
    map { $nodeinfo{$_} = 0 } @nodelist;

    # XXX only know how to do this for local PCs right now
    $clause .= " and nt.class='pc' and nt.isremotenode=0";

    #
    # Note that we are using the def_boot_osid from the nodes table to identify
    # the image of interest.  This is because the osid field is set by stated
    # after a node has reached the BOOTING state the first time, and may be
    # set to an MFS at other times.
    #
    my $query_result = DBQueryWarn(
1335
1336
1337
	"select r.node_id,r.vname,r.pid,r.eid,r.erole,n.osid,p.partition,".
	"       p.imageid,p.imageid_version,p.imagepid,i.imagename,".
	"       iv.loadpart,e.savedisk ".
1338
1339
1340
	"from reserved as r ".
	"left join nodes as n on n.node_id=r.node_id ".
	"left join node_types as nt on nt.type=n.type ".
1341
1342
1343
1344
1345
1346
	"left join partitions as p on p.node_id=n.node_id and ".
	"          p.osid=n.def_boot_osid ".
        "left join images as i on i.imageid=p.imageid and ".
	"          i.version=p.imageid_version ".
        "left join image_versions as iv on iv.imageid=i.imageid and ".
	"          iv.version=i.version ".
1347
1348
1349
1350
1351
1352
1353
        "left join experiments as e on e.pid=r.pid and e.eid=r.eid ".
	"where $clause");
    if (!$query_result) {
	return 1;
    }

    while (my ($node, $vname, $rpid, $reid, $erole, $osid, $part, $imageid,
1354
	       $imageid_version, $imagepid, $imagename, $lpart, $savedisk) =
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
	   $query_result->fetchrow_array()) {

	my $nodeobject = Node->Lookup($node);

	# If the node is not imageable, skip it.
	next
	    if (! $nodeobject->imageable());
	
	my $dtype = $nodeobject->disktype();
	my $dunit = $nodeobject->bootdisk_unit();

	#
	# XXX not a disk-based OSID.  This can happen during frisbee loads
	#
	if (!defined($imageid)) {
	    print "*** swapinfo: OS $osid is not disk-based!?\n";
	    next
		if (!$allnodes);
	    return 1;
	}
1375
1376
1377
1378
1379
1380
1381
	my $image = Image->Lookup($imageid, $imageid_version);
	if (!defined($image)) {
	    print "*** swapinfo: Image $imageid,$imageid_version not found!\n";
	    next
		if (!$allnodes);
	    return 1;
	}
1382
1383
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
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

	#
	# Weed out otherwise ineligible nodes:
	#	- from experiments that are not saving disk state
	#	- non-'node' role machines (i.e., delaynodes, virthosts)
	# They are removed from nodeinfo entirely so we do not complain about
	# them below.  This is the only reason we are doing this here rather
	# than as part of the above query.
	#
	if (!defined($savedisk) || $savedisk == 0 || $erole ne "node") {
	    delete $nodeinfo{$node};
	    next;
	}

	# Sanity checks
	if (!defined($nodeinfo{$node})) {
	    next
		if (!$allnodes);
	    print "*** swapinfo: Got partition info for invalid node $node!?\n";
	    return 1;
	}
	if ($nodeinfo{$node} != 0) {
	    print "*** swapinfo: Got redundant partition info for $node!?\n";
	    return 1;
	}

	my $disk = "$dtype$dunit";
	$nodeinfo{$node} =
	    [$vname, $rpid, $reid, $disk, $part, $imagepid, $imagename, $lpart];
    }

    #
    # Copy over the signature file for the image used on every node under
    # the name <vname>.sig.  Likewise, we record the partition that the
    # image resides in under <vname>.part.
    #
    # Note that we actually copy the signature over as <imagename>.sig and
    # then symlink the <vname>.sig's to it.  This not only saves space,
    # but makes it easier to determine what is loaded on each node.
    #
    # Finally note that we are using imagename rather than imageid (which
    # is a numeric UUID).  The latter is really closer to what we want, but
    # was added later and needs to be reconciled with our idea of 'unique'
    # (the signature).
    #
    my %gotsig = ();
    for my $node (keys(%nodeinfo)) {
	my $infop = $nodeinfo{$node};
	if ($infop == 0) {
	    print "*** swapinfo: WARNING: got no partition info for $node!\n";
	    next;
	}
	my ($vname, $rpid, $reid, $disk, $part, $imagepid, $imagename, $lpart) = @{$infop};

	#
	# If imageid is not "fully qualified" with the project name,
	# generate a name that is.
	#
	my $rimagename = $imagename;
	if ($rimagename !~ /^$imagepid-/) {
	    $rimagename = "$imagepid-$imagename";
	}

	# XXX backward compat
	my $infodir = "/$PROJROOT/$rpid/exp/$reid/swapinfo";
	if (! -d "$infodir" && !mkdir($infodir, 0770)) {
	    print "*** swapinfo: no swap info directory $infodir!\n";
	    next
		if (!$allnodes);
	    return 1;
	}

	#
	# First make sure we get rid of any old signature for the node
	# in case any of the following steps fail.
	#
	unlink("$infodir/$vname.sig", "$infodir/$vname.part");

	#
	# Now copy over the base signature if needed, either because
	# it doesn't exist in the swapinfo directory or is out of date.
	#
	my $mustcopy = 0;
	my ($sigdir, $signame);
	if ($imagepid eq TBOPSPID()) {
	    $sigdir = "$TB/images/sigs";
	} else {
	    $sigdir = "/$PROJROOT/$imagepid/images/sigs";
	}
	$signame = "$imagename.ndz.sig";
	$signame =~ s/^$imagepid-//;
	if (! -d $sigdir || ! -f "$sigdir/$signame") {
	    print "*** swapinfo: WARNING: ".
		"no image signature for $rimagename, ".
		"cannot save swapout state!\n";
	    next;
	}
	my $basesig = "$infodir/$rimagename.sig";
	if (! -r $basesig) {
	    $mustcopy = 1;
	} elsif (!defined($gotsig{$basesig})) {
David Johnson's avatar
David Johnson committed
1483
1484
1485
1486
	    my (undef,undef,undef,undef,undef,undef,undef,undef,
		undef,$fromtime,undef,undef,undef) = stat("$sigdir/$signame");
	    my (undef,undef,undef,undef,undef,undef,undef,undef,
		undef,$totime,undef,undef,undef) = stat($basesig);
1487
1488
1489
1490
1491
1492
1493
1494
1495
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
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
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
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
	    if ($fromtime > $totime) {
		print "*** swapinfo: WARNING: ".
		    "$rimagename.sig out of date, updating...\n";
		$mustcopy = 1;
	    } elsif ($fromtime < $totime) {
		print "*** swapinfo: WARNING: ".
		    "$rimagename.sig newer than source $sigdir/$signame!\n";
	    }
	}
	if ($mustcopy) {
	    unlink($basesig);
	    if (system("/bin/cp -p $sigdir/$signame $basesig")) {
		print "*** swapinfo: WARNING: ".
		      "could not create signature $basesig, ".
		      "cannot save swapout state!\n";
		next;
	    }
	}
	$gotsig{$basesig} = 1;

	if (system("/bin/ln -s $rimagename.sig $infodir/$vname.sig")) {
	    print "*** swapinfo: WARNING: ".
		"could not create signature $infodir/$vname.sig, ".
		    "cannot save swapout state!\n";
	    next;
	}

	if (!open(FD, "> $infodir/$vname.part")) {
		print "*** swapinfo: WARNING: ".
		      "could not create partition file $infodir/$vname.part, ".
		      "cannot save swapout state!\n";
		unlink("$infodir/$vname.sig");
		next;
	}
	print FD "DISK=$disk ";
	print FD "LOADPART=$lpart ";
	print FD "BOOTPART=$part\n";
	close(FD);
    }

    #
    # Now get rid of usused signature files
    # Note that we can only use the gotsig hash if we are loading all nodes
    # in an experiment (else we don't know whether a sig is used or not).
    #
    if ($allnodes) {
	my $infodir = "/$PROJROOT/$pid/exp/$eid/swapinfo";
	my @allsigs = `ls $infodir/*.sig`;
	chomp(@allsigs);
	for my $sig (@allsigs) {
	    if (! -l $sig && !defined($gotsig{$sig})) {
		# untaint the file name
		if ($sig =~ /^($infodir\/[-\w\.\+]+\.sig)$/) {
		    $sig = $1;
		    print "removing unused signature file $sig ...\n";
		    unlink($sig);
		}
	    }
	}
    }
}

sub SetupEventHandler($$)
{
    my ($self,$handler) = @_;
    
    my $port = @BOSSEVENTPORT@;
    my $URL  = "elvin://localhost:$port";
    
    # Connect to the event system, and subscribe the the events we want
    my $EVhandle = event_register($URL, 0);
    
    if (!$EVhandle) {
	print STDERR "*** event: Unable to register with event system\n";
	return undef;
    }

    my $tuple = address_tuple_alloc();
    if (!$tuple) {
	print STDERR "*** event: Could not allocate an address tuple\n";
	return undef;
    }

    # These are the states that indicate things are happening.
    my @states = (TBDB_NODESTATE_RELOADSETUP(),
		  TBDB_NODESTATE_RELOADING());

    %$tuple = ( objtype   => TBDB_TBEVENT_NODESTATE(),
		eventtype => join(",", @states),
	      );
    
    if (!event_subscribe($EVhandle, $handler, $tuple)) {
	print STDERR "*** event: Could not subscribe to events\n";
	return undef;
    }
    return $EVhandle;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;

    return 'libosload_new';
}


package libosload_common;
use base qw(libosload_new);

use libtestbed;
use libdb;
use libtblog;
use Node;
use Image;
use English;
use Data::Dumper;
use overload ('""' => 'Stringify');

sub New($$$)
{
    my ($class, $parent, $type) = @_;

    my $self = $class->SUPER::New();

    $self->{'TYPE'}      = $type;
    $self->{'PARENT'}    = $parent;
    $self->{'IMAGES'}    = {};

    bless($self, $class);

    if (defined($parent)) {
	$self->debug($parent->debug());
    }

    return $self;
}

# Access methods for the objects defined below, which are 
sub type($)		{ return $_[0]->{'TYPE'}; }
sub parent($)		{ return $_[0]->{'PARENT'}; }
sub GetImages($$)       { return $_[0]->{'IMAGES'}{$_[1]->node_id()}; }

#
# If specific images were not specified, load the info for the default image
# setup the images list accordingly.
#
sub _LoadDefaultImages($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

1641
    $self->dprint(3,"loading default images for $node_id");
1642
1643
1644

    my $default_imageid = $nodeobject->default_imageid();
    if (!defined($default_imageid)) {
1645
	tberror("$node_id: No default imageid defined!");
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
	return -1;
    }
    my @default_imageids = split(/,/, $default_imageid);
    my @default_images;
    foreach my $default_imageid (@default_imageids) {
	my $default_image = Image->Lookup($default_imageid);
	if (!defined($default_image)) {
	    tberror("Could not find $default_imageid in the DB!");
	    return -1;
	}
	push @default_images, $default_image;
    }
    # XXX -- should do elsewhere?  Seems wrong.
    $self->nodeflag($nodeobject,'prepare',1);

    $self->{'IMAGES'}->{$node_id} = \@default_images;

    return 0;
}

sub _LoadCurrentImages($$) 
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

1671
    $self->dprint(3,"loading current images for $node_id");
1672
1673

    my $def_boot_osid  = $nodeobject->def_boot_osid();
1674
1675
    my $def_boot_vers  = $nodeobject->def_boot_osid_vers();
    my $osinfo = OSinfo->Lookup($def_boot_osid, $def_boot_vers);
1676
1677
1678
1679
1680
1681
    if (! defined($osinfo)) {
	tberror("Could not find OS $def_boot_osid in the DB!");
	return undef;
    }
    my $best_image = $osinfo->MapToImage($nodeobject->type());
    if (!defined($best_image)) {
1682
	tberror("Could not map $osinfo to an image for $node_id!");
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
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
	return undef;
    }

    $self->{'IMAGES'}->{$node_id} = [ $best_image ];

    return 0;
}

#
# First load any node type attributes of form 'osload_*'.  Then, load any
# node attributes of form 'osload_*'.
#
sub _LoadAttributeArgs($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

    my $attrhashref = $nodeobject->GetNodeTypeAttributes();
    foreach my $k (keys(%{$attrhashref})) {
	if ($k =~ /^osload_.*$/) {
	    $self->nodeinfo($nodeobject,$k,$attrhashref->{$k}->{"value"});
	}
    }

    $attrhashref = $nodeobject->GetNodeAttributes();
    foreach my $k (keys(%{$attrhashref})) {
	if ($k =~ /^osload_.*$/) {
	    $self->nodeinfo($nodeobject,$k,$attrhashref->{$k});
	}
    }

    return 0;
}

#
# Add a node to the list.  This should almost never be overridden; it pretty
# much does generic testbed operations.
#
sub AddNode($$$$)
{
    my ($self, $nodeobject, $imagelist, $args) = @_;
    my $node_id = $nodeobject->node_id();

    if (!defined($args)) {
	$args = {};
    }

1730
    $self->dprint(0,"AddNode($node_id)");
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749

    $self->{'NODES'}->{$node_id}    = $nodeobject;
    $self->{'NODEFLAGS'}->{$node_id}    = $args;
    $self->{'IMAGES'}->{$node_id}   = $imagelist;

    if ($self->_LoadAttributeArgs($nodeobject)) {
	return -1;
    }

    my $imagelistref = $self->GetImages($nodeobject);

    if (!defined($imagelistref) || scalar(@$imagelistref) == 0) {
	if ($self->_LoadDefaultImages($nodeobject)) {
	    return -1;
	}
    }

    if ($self->nodeflag($nodeobject,'usecurrent')) {
	if (defined($imagelistref) && scalar(@$imagelistref)) {
1750
	    tbwarn("$self AddNode($node_id): we were given $imagelist, but are " . 
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
		   " going to use the current OS instead!");
	}

	if ($self->_LoadCurrentImages($nodeobject)) {
	    return -1;
	}
    }

    if ($self->_CheckImages($nodeobject)) {
	return -1;
    }

    return 0;
}

sub _CheckImages($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

1771
    $self->dprint(0,"_CheckImages($node_id)");
1772
1773
1774
1775
1776
1777
1778
1779
1780

    my @images = @{$self->GetImages($nodeobject)};
    my @imageids = map { $_->imageid() } @images;
    my @imageidxs = (0 .. $#imageids);

    foreach my $i (@imageidxs) {
	my $imageid = $imageids[$i];
	my $image = $images[$i];

1781
	$self->dprint(1,"_CheckImages($node_id): using $image");
1782
1783

	#
Leigh B Stoller's avatar
Leigh B Stoller committed
1784
1785
1786
1787
	# We can have both a full image and/or a delta image. We
	# always prefer the full image if we have it.
	#
	if (! ($image->HaveFullImage() || $image->HaveDeltaImage())) {
1788
1789
1790
1791
1792
1793
1794
1795
	    #
	    # This should be an error, but until we run imagevalidate
	    # over all images, we want to do it here.
	    #
	    if ($self->GetImageSize($image, $nodeobject)) {
		tberror "$nodeobject: no full or delta image file!";
		goto failednode;
	    }
1796
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
1797
1798
	if (! ($image->size() || $image->deltasize())) {
	    tberror "$image: no size info!";
1799
1800
	    return -1;
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
1801
	$self->dprint(2,"_CheckImages($node_id): imageinfo for $imageid:\n");
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
    }

    return 0;
}

sub SetBootOS($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

1812
    $self->dprint(0,"SetBootOS($node_id): setting boot os");
1813
1814
1815
1816
1817
1818
1819
1820
1821

    my @images = @{$self->GetImages($nodeobject)};
    #
    # When loading multiple images, use the osinfo from the
    # last image
    #
    my $image = $images[-1];
    my $imageid = $image->imageid();

Leigh B Stoller's avatar
Leigh B Stoller committed
1822
    my $defosid = $image->default_osid();
1823
1824
    my $osinfo = OSinfo->Lookup($defosid);
    if (!defined($osinfo)) {
1825
	tberror("$self SetBootOS($node_id): could not map OSID $defosid to its object!");
1826
1827
1828
	return -1;
    }

1829
    print "$self SetBootOS($node_id): changing default OS to $osinfo\n";
1830
    if (!$TESTMODE) {
1831
	if ($nodeobject->OSSelect($osinfo,"def_boot_osid",$self->debug())) {
1832
	    tberror "$self SetBootOS($node_id): os_select $defosid failed!";
1833
1834
1835
1836
	    return -1;
	}
    }

1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
    #
    # Change the node's default command line as necessary.
    # XXX we only do this for delay nodes.
    #
    if ($nodeobject->erole() eq "delaynode") {
	my ($ocmdline,$ncmdline);
	$ocmdline = $nodeobject->def_boot_cmd_line();
	$ocmdline = ""
	    if (!defined($ocmdline));
	$osinfo->OSBootCmd("delay", \$ncmdline);
	$ncmdline = ""
	    if (!defined($ncmdline));
	if ($ocmdline ne $ncmdline) {
	    print "$self SetBootOS($node_id): changing default command line to '$ncmdline'\n";
	    if (!DBQueryWarn("update nodes set ".
			     "def_boot_cmd_line='$ncmdline' ".
			     "where node_id='$node_id'")) {
		tbwarn "$self SetBootOS($node_id): could not update command line";
	    }
	}
    }

1859
1860
1861
    return 0;
}

1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
#
# Save the current osid, def_boot_osid, and partitions info for this node.
# This is not useful to most nodes, but for nodes where we *know* the reboot
# has failed (and for which we don't want to lie about which OS is actually
# on the node *because* we don't always force a reload if we think we know
# what OS is on "disk" -- like for switches!), we can do a reset if we save
# the old info.
#
# Note that none of this is called by default -- subclasses must manually
# invoke if they need it!
#
sub SaveNodeDiskInfo($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

1878
    $self->dprint(0,"SaveNodeDiskInfo($node_id): saving partition and osid");
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

    #
    # Save the old ones off first!
    #
    my $dbres;
    $dbres = DBQueryFatal("select node_id,partition,osid,imageid,imagepid" . 
			  " from partitions where node_id='$node_id'");
    if (defined($dbres) && $dbres->numrows()) {
	my @rows = ();
	while (my $rowref = $dbres->fetchrow_hashref()) {
	    push @rows,$rowref;
	}
	$self->nodeinfo($nodeobject,'old_partitions',\@rows);
    }

    $dbres = DBQueryFatal("select osid,def_boot_osid" . 
			  " from nodes where node_id='$node_id'");
    if (defined($dbres) && $dbres->numrows()) {
	my $rowref = $dbres->fetchrow_hashref();
	$self->nodeinfo($nodeobject,'old_osid',$rowref->{'osid'});
	$self->nodeinfo($nodeobject,'old_def_boot_osid',
			$rowref->{'def_boot_osid'});
    }
    return 0;
}

#
# Restore osid and partitions info if we saved it off!
#
sub RestoreNodeDiskInfo($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

1913
    $self->dprint(0,"RestoreNodeDiskInfo($node_id): restoring partition and osid");
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940

    my $partref = $self->nodeinfo($nodeobject,'old_partitions');
    if (defined($partref) && @$partref) {
	DBQueryFatal("delete from partitions where node_id='$node_id'");

	foreach my $rowref (@$partref) {
	    my ($part,$osid,$imageid,$imagepid) = 
		( $rowref->{'partition'},$rowref->{'osid'},
		  $rowref->{'imageid'},$rowref->{'imagepid'} );
	    DBQueryFatal("insert into partitions " . 
			 " (node_id,partition,osid,imageid,imagepid)" . 
			 " values" . 
			 " ('$node_id','$part','$osid','$imageid','$imagepid')");
	}
    }

    my $osid = $self->nodeinfo($nodeobject,'old_osid');
    my $def_boot_osid = $self->nodeinfo($nodeobject,'old_def_boot_osid');
    if (defined($osid) && defined($def_boot_osid)) {
	DBQueryFatal("update nodes set osid='$osid'," . 
		     "                 def_boot_osid='$def_boot_osid'" . 
		     " where node_id='$node_id'");
    }

    return 0;
}

1941
1942
1943
1944
1945
sub UpdatePartitions($$) 
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

1946
    $self->dprint(0,"UpdatePartitions($node_id): starting");
1947
1948
1949
1950
1951
1952
1953

    my @images = @{$self->GetImages($nodeobject)};
    my @imageids = map { $_->imageid() } @images;
    my @imageidxs = (0 .. $#imageids);

    my $prepare = $self->nodeflag($nodeobject,'prepare');

1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
    #
    # Most of the DB work related to images is determining what
    # disk partitions should be clobbered and which should survive
    # the loading of all the images. To make this more efficient,
    # we loop through the images updating our parititions hash
    # and then just do one DB partitions table access at the end.
    #
    my %partitions = ();
    my $curmbrvers = 0;

    #
    # XXX assumes a DOS MBR, but this is ingrained in the DB schema
    # as well (i.e., the images.part[1234]_osid fields).
    #
    my $MINPART = 1;
    my $MAXPART = 4;

    #
    # If doing a prepare, all current partition info is going to
    # be invalidated, so we start with an empty hash. Otherwise
    # we read the current DB values to initialize it.
    #
    if (!$prepare) {
	my $dbresult =
1978
1979
1980
1981
1982
	    DBQueryWarn("select p.*,v.mbr_version ".
			" from partitions as p,image_versions as v ".
			" where p.imageid=v.imageid and ".
			"       p.imageid_version=v.version and ".
			"       v.deleted is null ".
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
			"  and p.node_id='$node_id'");
	if (!$dbresult) {
	    tberror "$node_id: Could not read partition table!";
	    return -1;
	}
	while (my $href = $dbresult->fetchrow_hashref()) {
	    if (!$curmbrvers) {
		$curmbrvers = $href->{'mbr_version'};
	    } elsif ($href->{'mbr_version'} &&
		     $href->{'mbr_version'} != $curmbrvers) {
		tbwarn "$node_id: inconsistent MBR version info, ".
		       "invalidating all partitions!";
		%partitions = ();
		last;
	    }
	    $partitions{$href->{'partition'}} = $href;
	}
    }

    #
    # For each image, update the necessary node state.
    #
2005
2006
2007
2008
    foreach my $i (@imageidxs) {
	my $imageid = $imageids[$i];
	my $image = $images[$i];

Leigh B Stoller's avatar
Leigh B Stoller committed
2009
2010
2011
2012
	my $loadpart   = $image->loadpart();
	my $loadlen    = $image->loadlength();
	my $imagepath  = $image->path();
	my $imagepid   = $image->pid();
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022

	#
	# Assign partition table entries for each partition in the image
	# that has an OSID associated with it.
	#
	# This is complicated by the fact that an image that covers only
	# part of the slices should only change the partition table entries
	# for the subset of slices that are written to disk...
	#
	# ...UNLESS, the new image requires a different version of the MBR
2023
2024
	# in which case we must invalidate all existing partitions since
	# the partition boundaries may have changed...
2025
2026
2027
2028
2029
	#
	# ...OR, the prepare flag has been specified, which will tell the
	# client to invalidate all partition metadata on the disk so we
	# might as well mark the partition as "empty".  In particular,
	# this case is used by the reload_daemon when a node is between
2030
2031
2032
2033
	# experiments.  In this case we need to invalidate all existing
	# partition(s) to ensure that a user later on doesn't accidentally
	# get some left over partition OS when they should have been
	# loading a new instance. This case was handled earlier.
2034
2035
2036
2037
	#
	my $startpart = $loadpart == 0 ? $MINPART : $loadpart;
	my $endpart   = $startpart + $loadlen;

2038
2039
2040
2041
	#
	# If image MBR is incompatible with what is on the disk right
	# now, invalidate all the existing partitions ("...UNLESS" above).
	#
Leigh B Stoller's avatar
Leigh B Stoller committed
2042
2043
2044
	if (defined($image->mbr_version())) {
	    if ($image->mbr_version() && $curmbrvers &&
		$image->mbr_version() != $curmbrvers) {
2045
		%partitions = ();
2046
	    }
Leigh B Stoller's avatar
Leigh B Stoller committed
2047
	    $curmbrvers = $image->mbr_version();
2048
2049
2050
2051
2052
2053
2054
2055
	}

	#
	# Now we loop through the image partitions and set/clear
	# the existing partition info as appropriate.
	#
	for (my $i = $startpart; $i < $endpart; $i++) {
	    my $partname = "part${i}_osid";
2056
	    my $partvers = "part${i}_vers";
2057

2058
2059
	    my $osid = $image->DBData()->{$partname};
	    my $vers = $image->DBData()->{$partvers};
2060
	    if (defined($osid)) {
2061
2062
2063
2064
2065
		my $osinfo = OSinfo->Lookup($osid, $vers);
		if (!defined($osinfo)) {
		    tberror "No OSinfo found for osid $osid!\n";
		    return -1;
		}
2066
2067
2068
2069
		my %part = (
		    'node_id' => $node_id,
		    'partition' => $i,
		    'osid' => $osid,
2070
		    'osid_vers' => $osinfo->vers(),
2071
		    'imageid' => $imageid,
2072
		    'imageid_version' => $image->version(),
2073
2074
2075
2076
		    'imagepid' => $imagepid,
		    'mbr_version' => $curmbrvers
		    );
		$partitions{$i} = \%part;
2077
2078
	    }
	    else {
2079
		delete $partitions{$i};
2080
2081
2082
2083
	    }
	}
    }

2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
    #
    # Now that we have processed all images, update the actual DB
    # partitions table entries for this node.
    #
    for (my $i = $MINPART; $i <= $MAXPART; $i++) {
	my $dbresult;

	if (exists($partitions{$i})) {
	    my $href = $partitions{$i};
	    my $osid = $href->{'osid'};
2094
	    my $osvers = $href->{'osid_vers'};
2095
	    my $imid = $href->{'imageid'};
2096
	    my $imvers = $href->{'imageid_version'};
2097
2098
2099
	    my $impid = $href->{'imagepid'};
	    $dbresult =
		DBQueryWarn("replace into partitions ".
2100
2101
			    "(node_id,partition,osid,imageid,imagepid,".
			    " osid_vers,imageid_version) ".
2102
			    "values ".
2103
2104
			    "('$node_id','$i','$osid','$imid','$impid',".
			    " '$osvers','$imvers')");
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
	} else {
	    $dbresult =
		DBQueryWarn("delete from partitions ".
			    "where node_id='$node_id' and partition='$i'");
	}
	if (!$dbresult) {
	    tberror "$node_id: Could not update partitions table";
	    return -1;
	}
    }

2116
2117
2118
2119
2120
2121
2122
2123
    return 0;
}

sub RemoveNode($$)
{
    my ($self, $nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

2124
    $self->dprint(0,"RemoveNode($node_id)");
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150

    $self->{'NODES'}->{$node_id}    = undef;
    $self->{'ARGS'}->{$node_id}     = undef;
    $self->{'IMAGES'}->{$node_id}   = undef;

    return 0;
}

#
# Compute the time to load all images on this node.
#
sub ComputeMaxLoadWaitTime($$)
{
    my ($self,$nodeobject) = @_;

    my $maxwait = 0;

    my @images = @{$self->GetImages($nodeobject)};
    foreach my $image (@images) {
	my $imageid = $image->imageid();
	#
	# Compute a maxwait time based on the image size plus a constant
	# factor for the reboot cycle.  This is used later in
	# WaitTillReloadDone().  Arguably, this should be part of the
	# image DB state, so we store it in the imageinfo array too.
	#
Leigh B Stoller's avatar
Leigh B Stoller committed
2151
	my $chunks = $image->size() >> 20;# size may be > 2^31, shift is unsigned
2152
2153
2154
2155
2156
2157

	# XXX aren't we multi-counting reboots??
	# ok, moved constant factor out.
	$maxwait += int(($chunks / 100.0) * 65);
    }

2158
    return $maxwait + $TBLOADWAIT;
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169