libosload_new.pm.in 75.1 KB
Newer Older
1
2
#!/usr/bin/perl -wT
#
Leigh B Stoller's avatar
Leigh B Stoller committed
3
# Copyright (c) 2000-2017 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
#
# 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;
Leigh B Stoller's avatar
Leigh B Stoller committed
43
use Interface;
44
use OSImage;
45
use User;
46
use EmulabConstants;
47
48
49
use English;
use event;
use Data::Dumper;
50
use File::stat;
51
52
53
54
55
56
57
58
59
use IO::Handle;
use overload ('""' => 'Stringify');

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

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

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

75
76
77
78
79
#
# This could also be a sitevar, but let's not right now.
#
my $DEFAULT_DEBUG_LEVEL = 10;

80
81
82
83
84
85
86
#
# 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);

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

119
120
    # We need this guy right away, else we get errors about no debug slot.
    $self->debug(0);
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

    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'}; }

139
140
sub dprint($$;@) {
    my ($self,$level,@args) = @_;
141
    print STDERR "$self " . join('',@args) . "\n"
142
	if ($self->debug() > $level);
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
188
189
190
}
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;
191
	$self->dprint(3,"nodeinfo($node_id,$key) <- $data)");
192
193
194
195
196
	return $data;
    }
    if (exists($self->{NODEINFO}->{$node_id}->{$key})) {
	my $retval = $self->{NODEINFO}->{$node_id}->{$key};
	my $pretval = defined($retval) ? $retval : "undef";
197
	$self->dprint(3,"nodeinfo($node_id,$key) -> $pretval");
198
199
200
201
202
203
	return $retval;
    }
    return undef;
}
sub nodeinfo_unset($$$)
{
204
    my ($self,$nodeobject,$key) = @_;
205
    if (!defined($nodeobject)) {
206
	tbwarn "$self nodeinfo_unset called with $key and no node!\n";
207
208
209
    }
    my $node_id = $nodeobject->node_id();
    
210
    $self->dprint(3,"nodeinfo_unset($nodeobject,$key)");
211
212
213
214
215
216
217
218
219
220
221
222
223
224
    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;
225
    my $dbgop = '';
226
227
228
229
230

    my $node_id = $nodeobject->node_id();
    if (defined($flagval)) {
	$self->{NODEFLAGS}->{$node_id}->{$flagname} = $flagval;
	$retval = $flagval;
231
	$dbgop = 'w';
232
233
234
    }
    elsif (exists($self->{NODEFLAGS}->{$node_id}->{$flagname})) {
	$retval = $self->{NODEFLAGS}->{$node_id}->{$flagname};
235
	$dbgop = 'rn';
236
237
238
    }
    elsif (exists($self->{FLAGS}->{$flagname})) {
	$retval = $self->{FLAGS}->{$flagname};
239
	$dbgop = 'rg';
240
241
242
    }

    my $pretval = defined($retval) ? $retval : "undef";
243
    $self->dprint(2,"nodeflag($node_id,$flagname) ($dbgop) -> $pretval");
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
280
281
282
283
284
285
286

    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) = @_;

287
    $self->dprint(2,"NewType($type): trying to create type object");
288
289
290
291
292

    my $packname = "libosload_${type}";
    my $newtype  = eval { $packname->New($self); };
    # Not loaded?
    if ($@) {
293
	$self->dprint(2,"NewType($type): simple module load failed: " . $@);
294
	eval "require libosload_${type}";
295
296
297
298
299
300
	if ($@) {
	    if ($@ !~ /Can't locate libosload_/) {
		print STDERR "$self NewType($type): module load failed: " . $@;
	    }
	    return undef;
	}
301
302
	$newtype  = eval { $packname->New($self); };
	if ($@) {
303
	    $self->dprint(1,"$self NewType($type): New() failed: " . $@);
304
305
306
307
308
	    return undef;
	}
    }
    $self->{'TYPECACHE'}->{$type} = $newtype;
    
309
    $self->dprint(3,"NewType($type): created type object $newtype");
310
311
312
313
314
315
316
317
318
319
320
321
322
    
    return $newtype;
}

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

    my $type  = $nodeobject->type();
    my $class = $nodeobject->class();
323
    my $node_id = $nodeobject->node_id();
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
350
351
352
353
354
355
356
357
358
359
360
361
362

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

363
	$self->dprint(4,"ChildCreate: created $childpid");
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
402
403
404
405
406
407
408
409
410
411
412
413
414

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

415
    # set some default flags
416
417
418
419
420
421
422
423
    my %flags = ();
    $flags{waitmode}    = 1;
    $flags{usecurrent}  = 0;
    $flags{noreboot}    = 0;
    $flags{asyncmode}   = 0;
    $flags{zerofree}    = 0;
    $flags{prepare}     = 0;
    $flags{swapinfo}    = 0;
424
    $flags{usedefault}  = 1;
425
426
427
428
429

    # These come in from the caller.
    my @imageids;
    my @nodes       = ();
    my %nodeflags   = ();
Leigh B Stoller's avatar
Leigh B Stoller committed
430
431
    # For frisbee events, which come with IP.
    my %iptonode    = ();
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454

    # 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;
	}
    }
455
456
457
458

    # override our defaults
    foreach my $flag (keys(%$args)) {
	$flags{$flag} = $args->{$flag};
459
    }
460
    # handle some of the flags specially
461
462
463
464
465
466
467
468
469
470
    if ($flags{usecurrent}) {
	$flags{usedefault} = 0;
    }
    if (defined($args->{'image'})) {
	@images = split(/,/, $args->{'image'});
	$flags{usedefault} = $flags{usecurrent} = 0;
    }
    elsif (defined($args->{'images'})) {
	@images = @{$args->{'images'}};
	$flags{usedefault} = $flags{usecurrent} = 0;
471
    }
472
    elsif (defined($args->{'imageids'})) {
473
	@imageids = @{$args->{'imageids'}};
474
475
476
477
478
	$flags{usedefault} = $flags{usecurrent} = 0;
    }
    elsif (defined($args->{'imageid'})) {
	@imageids = split(/,/, $args->{'imageid'});
	$flags{usedefault} = $flags{usecurrent} = 0;
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
    }
    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;
	    }
	}
    }

517
518
    if (@imageids) {
	foreach my $imageid (@imageids) {
519
	    my $image = OSImage->Lookup($imageid);
520
521
522
523
524
525
526
527
	    if (!defined($image)) {
		tberror("No such imageid $imageid");
		return -1;
	    }
	    push(@images, $image);
	}
    }

528
    foreach my $i (0 .. $#images) {
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
557
558
	my $image = $images[$i];

	#
	# 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.
	#
559
	#$self->GetImageInfo($image,...);
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
    }

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

591
    my %access_keys = ();
592
593
594
595
596
597
598
599
600
601
602
603
    # 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;
	}

Leigh B Stoller's avatar
Leigh B Stoller committed
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
	# For frisbee events.
	my $interface = Interface->LookupControl($nodeobject);
	if (!defined($interface)) {
	    print STDERR "*** No control interface for $node\n";
	}
	else {
	    my $ctrlip = $interface->IP();
	    if (!defined($ctrlip) || $ctrlip eq "") {
		print STDERR "*** No control IP for $node\n";
	    }
	    else {
		$iptonode{$ctrlip} = $node;
	    }
	}

619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
	#
	# 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
644
		    die_noretry("$self: no type/class specific osload module for $node");
645
646
647
		}
	    }

648
	    $self->dprint(2,"osload($node): used typeobject $object");
649
650
651
652
653
654
655
656
657
658
659
	}

	# 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};
	}
660
	foreach my $k (keys(%{$nodeflags{$node}})) {
661
662
	    $nargs{$k} = $nodeflags{$node}{$k};
	}
663
664
665
666
667

	# 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()) {
668
	    $nargs{'zerofree'} = 2;
669
670
	}

671
672
673
674
675
676
677
678
	# 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};
	#}
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
	if (@images) {
	    my $node_id = $nodeobject->node_id();
	    my @tmp = ();

	    foreach my $image (@images) {
		if ($image->isImageAlias()) {
		    my $im = $image->MapToImage($nodeobject->type());
		    if (!defined($im)) {
			tberror("Could not map $image to an image ".
				"for $node_id!");
			return -1;
		    }
		    $image = $im;
		}
		push(@tmp, $image);
	    }
	    @images = @tmp;
	}
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717

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

719
720
721
722
723
	#
	# 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!
	#
724
725
726
727
728
729
	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
730
	    elsif ($nodeobject->isremotenode() && !defined($access_keys{$image})) {
731
732
		$access_keys{$image} = TBGenSecretKey();
		
David Johnson's avatar
David Johnson committed
733
734
		if ($image->Update({'access_key' => $access_keys{$image}}) != 0) {
		    tberror "$self ($node): Could not initialize image access key";
735
736
737
738
		    goto failednode;
		}
	    }
	}
739
740
741
742

	#
	# Setup the reload, finally!
	#
743
	print "$object: setting up reload for $node\n";
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

	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;

776
777
    TBDebugTimeStamp("osload: database setup done");

778
779
780
781
782
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
808
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
    # 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);
Leigh B Stoller's avatar
Leigh B Stoller committed
838
	my $objtype = event_notification_get_objtype($handle,$notification);
839
840
841
842

	return
	    if (!defined($eventnodes));

843
	$eventnodes->{'GOTONE'} = 1;
Leigh B Stoller's avatar
Leigh B Stoller committed
844
845

	# These events have IP instead of node_id.
846
	if ($objtype eq TBDB_TBEVENT_FRISBEESTATUS()) {
Leigh B Stoller's avatar
Leigh B Stoller committed
847
848
849
850
851
	    return
		if (!exists($iptonode{$node_id}));
	    
	    $node_id = $iptonode{$node_id};
	}
852
	if (exists($eventnodes->{$node_id})) {
853
	    my $et = time();
854
	    if ($self->debug()) {
Leigh B Stoller's avatar
Leigh B Stoller committed
855
		print STDERR "$self: eventhandler: $node_id => $event @ $et\n"
856
857
	    }
	    $eventnodes->{$node_id} = $et;
Leigh B Stoller's avatar
Leigh B Stoller committed
858

859
	    if ($objtype eq TBDB_TBEVENT_FRISBEESTATUS()) {
Leigh B Stoller's avatar
Leigh B Stoller committed
860
861
862
		my $nodeobject = $self->node($node_id);
		my $wbytes = event_notification_get_string($handle,
							   $notification,
863
							   "MBYTES_WRITTEN");
Leigh B Stoller's avatar
Leigh B Stoller committed
864
865
866
867
868
		$self->nodeinfo($nodeobject, 'frisbeestatus',
				{"when"    => $et,
				 "wbytes"  => $wbytes,
				 "image"   => $event});
	    }
869
870
871
872
873
874
875
876
877
878
879
880
	}
    };
    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;
    }

Leigh B Stoller's avatar
Leigh B Stoller committed
881
882
883
884
885
886
887
    # Prime the event handler above.
    $eventnodes = {} if (!defined($eventnodes));
    foreach my $node (@nodes) {
	$eventnodes->{$node} = 0;
    }
    $self->dprintts("event handler enabled");

888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
    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";

	    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);
Leigh B Stoller's avatar
Leigh B Stoller committed
917
918
			# Mark node as being rebooted for waitloop
			$self->nodeinfo($self->node($node), 'rebooted',1);
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
		    }
		}
		@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();
949
		    $typeobject->ReloadDone($nodeobject);
950
951
952
953
954
955
956
		    next;
		}

		if ($typeobject->Reload($nodeobject) < 0) {
		    tberror("$self ($node): direct reload failed. Skipping.");
		    $result->{$node} = -1;
		    $self->incrfailcount();
957
		    $typeobject->ReloadDone($nodeobject);
958
959
960
961
962
963
964
965
966
967
968
969
		    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;
970
		$typeobject->ReloadDone($nodeobject);
971
972
973
974
975
976
977
978
		$self->incrfailcount();
	    }
	}
    }
  done:
    my $failures = $self->failed();
    print "$self: Done! There were $failures failures.\n";

979
980
981
982
983
984
985
986
    #
    # Since we use this in long running daemons, be sure to release
    # the event system connection, or else we stack up lots of handles
    # and socket connections to the event server.
    #
    event_unregister($evhandle)
	if (defined($evhandle));

987
    if ($flags{asyncmode}) {
988
	$self->dprint(3,"osload: asyncmode osload writing results");
989
990
991
992
993
994
	#
	# 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};
995
	    $self->dprint(3,"osload: asyncmode osload writing result ($node,$status)");
996
997
998
999
	    print $CHILD_WRITER "$node,$status\n";
	}
	close($CHILD_WRITER);

1000
	$self->dprintts("osload: asyncmode finished");
1001
1002
1003
1004

	exit($failures);
    }

1005
    $self->dprintts("osload: finished");
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
    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();

1024
    $self->dprint(0,"AddNode($node_id): starting");
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035

    $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($$$$$@)
{
1036
    my ($self, $startwait, $waitmode,
1037
1038
1039
1040
1041
	$eventnodes, $evhandle, @nodes) = @_;
    my %done	= ();
    my $count   = @nodes;
    my @failed  = ();

1042
    $self->dprintts("WaitTillReloadDone(" . join(',',@nodes) . ") starting");
1043
1044
1045

    foreach my $node ( @nodes ) {
	my $nodeobject = $self->node($node);
1046
	if (!$self->nodeflag($nodeobject,'nowait')) {
1047
1048
1049
1050
1051
1052
1053
1054
1055
	    $done{$node} = 0;
	}
	else {
	    $done{$node} = 1;
	    --$count;
	    print "$self: not waiting for reload of $node.\n";
	}
    }

1056
    $self->dprint(1,"WaitTillReloadDone(" . join(',',@nodes) . "): waiting for nodes to finish reloading (".`date`.")")
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
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
	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.
1093
    $self->dprintts("starting reload-done wait");
1094
1095
1096
    my $waittime  = 0;
    my $minutes   = 0;

1097
1098
1099
1100
1101
1102
1103
1104
1105
    #
    # 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;

1106
    my $ecount = 1;
1107
1108
1109
    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.
1110
1111
1112
	if ($ecount > 0) {
	    sleep(5)
	}
1113
	my $ecount = $MAXEVENTS;
1114
1115
1116
1117
	do {
	    $eventnodes->{'GOTONE'} = 0;
	    event_poll($evhandle);
	} while ($eventnodes->{'GOTONE'} && --$ecount > 0);
1118
1119
1120
	if ($ecount < $MAXEVENTS) {
	    $self->dprint(2, "got ", $MAXEVENTS-$ecount, " events\n");
	}
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
	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) = 
1138
		    $typeobject->WaitForNode($nodeobject);
1139
		$self->dprint(2,"$typeobject->WaitForNode($node) -> $typewaitstatus");
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
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
		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) {
1178
			$self->dprint(1,"$self: WaitTillReloadDone($node): left reloading mode at ".`date`)
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
			    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)) {
1193
		    $self->dprint(2,"$self ($node): Could not get event state");
1194
1195
1196
1197
1198
1199
1200
		}
	
		# Soon we will have stated's timeouts take care of
		# rebooting once or twice if we get stuck during
		# reloading.
		$waittime = time - $startwait;
		
1201
		# If the node doesn't made a transition within $REBOOTWAIT
Leigh B Stoller's avatar
Leigh B Stoller committed
1202
		# minutes of booting, we declare it stuck. 
1203
		my $isstuck = ($minutes > $REBOOTWAIT &&
1204
			       exists($eventnodes->{$node}) &&
Leigh B Stoller's avatar
Leigh B Stoller committed
1205
			       $self->nodeinfo($nodeobject, 'rebooted') &&
1206
			       $eventnodes->{$node} == 0);
1207

Leigh B Stoller's avatar
Leigh B Stoller committed
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
		#
		# But, if we are in reloading, then we obviously missed
		# a state transition in our handler. Probably just
		# need to increase $MAXEVENTS above.
		#
		if ($isstuck &&
		    $eventstate eq TBDB_NODESTATE_RELOADING()) {
		    tbnotice("$self: missed state transition to RELOADING".
			     " for $node; faking it.");
		    $eventnodes->{$node} = time();
		    goto okay;
		}

		#
		# Another form of being stuck is no frisbee events for
		# too long. But only if we are getting frisbee events
		# and only if we are still in the RELOADING state.
		#
		if (! $isstuck &&
		    $eventstate eq TBDB_NODESTATE_RELOADING()) {
		    my $frisbeestatus =
			$self->nodeinfo($nodeobject, "frisbeestatus");
		    if (defined($frisbeestatus)) {
			my $lastevent = $frisbeestatus->{'when'};
			my $diff = time() - $lastevent;
			if ($diff > 180) {
			    $isstuck = 1;
			    print STDERR "$self: $node: ".
				"Frisbee events have stopped coming in.\n"
				if ($self->debug());
			}
		    }
		}

1242
		if ($waittime > $maxwait ||
1243
1244
		    $eventstate eq TBDB_NODESTATE_TBFAILED() ||
		    $eventstate eq TBDB_NODESTATE_PXEFAILED() ||
1245
		    $eventstate eq TBDB_NODESTATE_RELOADFAILED() ||
1246
		    $isstuck) {
1247

1248
		    my $t = (int ($waittime / 60));
Leigh B Stoller's avatar
Leigh B Stoller committed
1249
1250
		    my $msg = "$self: $node appears wedged; ".
			"it has been $t minutes since it was rebooted.\n";
1251

1252
		    if ($eventstate eq TBDB_NODESTATE_TBFAILED() ||
1253
			$eventstate eq TBDB_NODESTATE_RELOADFAILED() ||
1254
			$eventstate eq TBDB_NODESTATE_PXEFAILED()) {
Leigh B Stoller's avatar
Leigh B Stoller committed
1255
			$msg .= "$self: $node is stuck in $eventstate.";
1256
		    }
1257
		    elsif ($isstuck) {
Leigh B Stoller's avatar
Leigh B Stoller committed
1258
1259
1260
1261
1262
1263
1264
1265
1266
			if ($eventstate eq TBDB_NODESTATE_RELOADING()) {
			    $msg .= "$self: $node has not made any ".
				"frisbee progress in a long time.";
			}
			else {
			    $msg .= "$self: $node failed to make a state ".
				"transition after $REBOOTWAIT minutes; ".
				"stuck in $eventstate.";
			}
1267
		    }
Leigh B Stoller's avatar
Leigh B Stoller committed
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
		    else {
			#
			# We have waited longer then maxwait. If we are
			# getting frisbee events then we ignore that limit
			# since that is soooo old school. Now frisbee tells
			# us it is making progress, so we wait until there
			# have been no frisbee events (no progress) for too
			# long, and then call it stuck.
			#
			my $frisbeestatus =
			    $self->nodeinfo($nodeobject, "frisbeestatus");
			if (defined($frisbeestatus)) {
			    my $lastevent = $frisbeestatus->{'when'};
			    my $diff = time() - $lastevent;
			    if ($diff < 120) {
				print STDERR "$self: $node: ".
				    "waiting for another frisbee event.\n"
				    if ($self->debug());
				goto okay;
			    }
			    print STDERR "$self: $node: ".
				"Frisbee events have stopped coming in.\n"
				if ($self->debug());
			}
			$msg .= "$self: $node did not finish reloading.";
		    }
		    tbnotice($msg);
1295
1296
1297
1298
1299
1300
1301
		    TBNodeConsoleTail($node, *STDERR);

		    $count--;
		    $done{$node} = $waitmode;
		    push(@failed, $node);
		    next;
		}
1302
	      okay:
1303
1304
		if (int($waittime / 60) > $minutes) {
		    $minutes = int($waittime / 60);
Leigh B Stoller's avatar
Leigh B Stoller committed
1305
1306
		    print STDERR "$self ($node): still waiting in ".
			$eventstate . "; " .
Leigh B Stoller's avatar
Leigh B Stoller committed
1307
1308
1309
1310
1311
1312
			"it has been $minutes minute(s). ";

		    my $frisbeestatus =
			$self->nodeinfo($nodeobject, "frisbeestatus");
		    if (defined($frisbeestatus)) {
			my $wbytes = $frisbeestatus->{"wbytes"};
1313
			print STDERR "${wbytes}MB written.";
Leigh B Stoller's avatar
Leigh B Stoller committed
1314
1315
		    }
		    print STDERR "\n";
1316
1317
1318
1319
1320
1321
		}
	    }
	}
    }

    if ($waitmode > 1) {
1322
	$startwait = time;
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
	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,
1334
				      TBDB_NODESTATE_RELOADFAILED,
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
				      TBDB_NODESTATE_PXEFAILED,
				      TBDB_NODESTATE_ISUP))) {
		    $done{$node} = $waitmode;
		} else {
		    push(@failed, $node);
		}
	    }
	}
    }

1345
    $self->dprintts("WaitTillReloadDone(" . join(',',@nodes) . "): finished");
1346
1347
1348
1349

    return @failed;
}

1350
1351
1352
1353
1354
1355
1356
1357
#
# Grab the size and update the database.
#
sub GetImageSize($$$)
{
    my ($self, $image, $node) = @_;
    my $imagesize = 0;
    my $imagepath = $image->FullImageFile();
1358

1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
    #
    # 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;
}
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

#
# 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) = @_;

1437
    $self->dprintts("osload_wait($childpid): starting");
1438
1439
1440
1441
1442
1443
1444
1445
1446

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

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

	if ($line =~ /^([-\w]+),([-\d])+$/) {
	    $result->{$1} = $2;
1447
	    print STDERR "$self osload_wait($1): child returned $2 status.\n";
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
	}
	else {
	    tberror "$self osload_wait: improper response from child: $_"; # INTERNAL
	}
    }

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

    return $retval;
}

Leigh B Stoller's avatar
Leigh B Stoller committed
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
sub osload_kill($$)
{
    my ($self,$childpid) = @_;

    $self->dprintts("osload_kill($childpid): starting");
    kill('TERM', $childpid);
    waitpid($childpid, 0);
    $self->dprintts("osload_kill($childpid) finished");
    return 0;
}

1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
#
# 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(
1506
	"select r.node_id,r.vname,r.pid,r.eid,r.erole,n.osid,p.`partition`,".
1507
1508
	"       p.imageid,p.imageid_version,p.imagepid,i.imagename,".
	"       iv.loadpart,e.savedisk ".
1509
1510
1511
	"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 ".
1512
	"left join `partitions` as p on p.node_id=n.node_id and ".
1513
1514
1515
1516
1517
	"          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 ".
1518
1519
1520
1521
1522
1523
1524
        "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,
1525
	       $imageid_version, $imagepid, $imagename, $lpart, $savedisk) =
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
	   $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;
	}
1546
	my $image = OSImage->Lookup($imageid, $imageid_version);
1547
1548
1549
1550
1551
1552
	if (!defined($image)) {
	    print "*** swapinfo: Image $imageid,$imageid_version not found!\n";
	    next
		if (!$allnodes);
	    return 1;
	}
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
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653

	#
	# 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})) {
1654
1655
	    my $fromtime = stat("$sigdir/$signame")->mtime;
	    my $totime = stat($basesig)->mtime;
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
	    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;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
1751
1752
1753
1754
1755
1756
    
    $tuple = address_tuple_alloc();
    if (!$tuple) {
	print STDERR "*** event: Could not allocate an address tuple\n";
	return undef;
    }
1757
    %$tuple = (objtype   => TBDB_TBEVENT_FRISBEESTATUS());
Leigh B Stoller's avatar
Leigh B Stoller committed
1758
1759
1760
1761
    if (!event_subscribe($EVhandle, $handler, $tuple)) {
	print STDERR "*** event: Could not subscribe to events\n";
	return undef;
    }
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
    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;
1783
use OSImage;
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
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();

1821
    $self->dprint(3,"loading default images for $node_id");
1822
1823
1824

    my $default_imageid = $nodeobject->default_imageid();
    if (!defined($default_imageid)) {
1825
	tberror("$node_id: No default imageid defined!");
1826
1827
1828
1829
1830
	return -1;
    }
    my @default_imageids = split(/,/, $default_imageid);
    my @default_images;
    foreach my $default_imageid (@default_imageids) {
1831
	my $default_image = OSImage->Lookup($default_imageid);
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
	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();

1851
    $self->dprint(3,"loading current images for $node_id");
1852
1853

    my $def_boot_osid  = $nodeobject->def_boot_osid();
1854
    my $def_boot_vers  = $nodeobject->def_boot_osid_vers();
1855
    my $osimage = OSImage->Lookup($def_boot_osid, $def_boot_vers);
1856
    if (! defined($osimage)) {
1857
1858
1859
	tberror("Could not find OS $def_boot_osid in the DB!");
	return undef;
    }
1860
    my $best_image = $osimage->MapToImage($nodeobject->type());
1861
    if (!defined($best_image)) {
1862
	tberror("Could not map $osimage to an image for $node_id!");
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
	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 = {};
    }

1910
    $self->dprint(0,"AddNode($node_id)");
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921

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

1922
1923
    if ($self->nodeflag($nodeobject,'usedefault')) {
	if (defined($imagelistref) && scalar(@$imagelistref)) {
1924
	    tbwarn("$self AddNode($node_id): we were given $imagelist, but are " .
1925
1926
1927
		   " going to use the default OS instead!");
	}

1928
1929
1930
1931
	if ($self->_LoadDefaultImages($nodeobject)) {
	    return -1;
	}
    }
1932
    elsif ($self->nodeflag($nodeobject,'usecurrent')) {
1933
	if (defined($imagelistref) && scalar(@$imagelistref)) {
1934
	    tbwarn("$self AddNode($node_id): we were given $imagelist, but are " .
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
		   " 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();

1955
    $self->dprint(0,"_CheckImages($node_id)");
1956

1957
1958
1959
1960
1961
1962
1963
1964
1965
    my $imagelistref = $self->GetImages($nodeobject);
    if (!defined($imagelistref)) {
	#
	# Sometimes we can be called with no images to load, just so we
	# can reconfigure the node.  So catch that case.
	#
	return 0;
    }
    my @images = @$imagelistref;
1966
1967
1968
1969
1970
1971
1972
    my @imageids = map { $_->imageid() } @images;
    my @imageidxs = (0 .. $#imageids);

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

1973
	$self->dprint(1,"_CheckImages($node_id): using $image");
1974
1975

	#
Leigh B Stoller's avatar
Leigh B Stoller committed
1976
1977
1978
1979
	# 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())) {
1980
1981
1982
1983
1984
1985
	    #
	    # 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!";
1986
		return -1;
1987
	    }
1988
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
1989
1990
	if (! ($image->size() || $image->deltasize())) {
	    tberror "$image: no size info!";
1991
1992
	    return -1;
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
1993
	$self->dprint(2,"_CheckImages($node_id): imageinfo for $imageid:\n");
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
    }

    return 0;
}

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

2004
    $self->dprint(0,"SetBootOS($node_id): setting boot os");
2005
2006
2007

    my @images = @{$self->GetImages($nodeobject)};
    #
2008
    # When loading multiple images, use the osimage from the
2009
2010
2011
2012
2013
    # last image
    #
    my $image = $images[-1];
    my $imageid = $image->imageid();

Leigh B Stoller's avatar
Leigh B Stoller committed
2014
    my $defosid = $image->default_osid();
2015
2016
    my $osimage = OSImage->Lookup($defosid);
    if (!defined($osimage)) {
2017
	tberror("$self SetBootOS($node_id): could not map OSID $defosid to its object!");
2018
2019
2020
	return -1;
    }

2021
    print "$self SetBootOS($node_id): changing default OS to $osimage\n";
2022
    if (!$TESTMODE) {
2023
	if ($nodeobject->OSSelect($image,"def_boot_osid",$self->debug())) {
2024
	    tberror "$self SetBootOS($node_id): os_select $defosid failed!";
2025
2026
2027
2028
	    return -1;
	}
    }

2029
2030
2031
2032
2033
2034
2035
2036
2037
    #
    # 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));
2038
	$osimage->OSBootCmd("delay", \$ncmdline);
Mike Hibler's avatar