Image.pm.in 16.9 KB
Newer Older
1
2
3
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2007-2011 University of Utah and the Flux Group.
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
# All rights reserved.
#
package Image;

use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw ( );

# Must come after package declaration!
use libdb;
use libtestbed;
use English;
use Data::Dumper;
use overload ('""' => 'Stringify');

# Configure variables
my $TB		  = "@prefix@";
my $BOSSNODE      = "@BOSSNODE@";
my $CONTROL	  = "@USERNODE@";
my $TBOPS         = "@TBOPSEMAIL@";
my $TBAUDIT       = "@TBAUDITEMAIL@";
my $TBBASE        = "@TBBASE@";
my $TBWWW         = "@TBWWW@";

# Cache of instances to avoid regenerating them.
my %images    = ();
my $debug      = 0;

# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

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

#
# Lookup by idx or pid,osname, depending on the args.
#
sub Lookup($$;$)
{
    my ($class, $arg1, $arg2) = @_;
    my $imageid;

    #
    # A single arg is either an index or a "pid,osname" or "pid/osname" string.
    #
    if (!defined($arg2)) {
	if ($arg1 =~ /^(\d*)$/) {
	    $imageid = $1;
	}
	elsif ($arg1 =~ /^([-\w]*),([-\w\.\+]*)$/ ||
	       $arg1 =~ /^([-\w]*)\/([-\w\.\+]*)$/) {
	    $arg1 = $1;
	    $arg2 = $2;
	}
	else {
	    return undef;
	}
    }
    elsif (! (($arg1 =~ /^[-\w\.\+]*$/) && ($arg2 =~ /^[-\w\.\+]*$/))) {
	return undef;
    }

    #
    # Two args means pid/imagename lookup instead of gid_idx.
    #
    if (defined($arg2)) {
	my $images_result =
	    DBQueryWarn("select imageid from images ".
			"where pid='$arg1' and imagename='$arg2'");

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

	($imageid) = $images_result->fetchrow_array();
    }

    # Look in cache first
    return $images{"$imageid"}
        if (exists($images{"$imageid"}));
    
    my $query_result =
	DBQueryWarn("select * from images where imageid='$imageid'");

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

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

    bless($self, $class);
    
    # Add to cache. 
    $images{"$imageid"} = $self;
    
    return $self;
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'IMAGE'}->{$_[1]}); }
sub imagename($)        { return field($_[0], "imagename"); }
sub imageid($)          { return field($_[0], "imageid"); }
sub old_imageid($)      { return field($_[0], "old_imageid"); }
sub pid($)	        { return field($_[0], "pid"); }
sub gid($)	        { return field($_[0], "gid"); }
sub pid_idx($)          { return field($_[0], "pid_idx"); }
sub gid_idx($)          { return field($_[0], "gid_idx"); }
sub creator($)          { return field($_[0], "creator"); }
sub creator_idx($)      { return field($_[0], "creator_idx"); }
sub created($)          { return field($_[0], "created"); }
sub description($)      { return field($_[0], "description"); }
sub loadpart($)         { return field($_[0], "loadpart"); }
sub loadlength($)       { return field($_[0], "loadlength"); }
sub part1_osid($)       { return field($_[0], "part1_osid"); }
sub part2_osid($)       { return field($_[0], "part2_osid"); }
sub part3_osid($)       { return field($_[0], "part3_osid"); }
sub part4_osid($)       { return field($_[0], "part4_osid"); }
sub default_osid($)     { return field($_[0], "default_osid"); }
sub path($)             { return field($_[0], "path"); }
sub magic($)            { return field($_[0], "magic"); }
sub ezid($)             { return field($_[0], "ezid"); }
sub shared($)           { return field($_[0], "shared"); }
sub global($)           { return field($_[0], "global"); }
sub updated($)          { return field($_[0], "updated"); }
Leigh B Stoller's avatar
Leigh B Stoller committed
134
sub mbr_version($)      { return field($_[0], "mbr_version"); }
135
sub access_key($)       { return field($_[0], "access_key"); }
136

137
138
#
# Get a list of all running frisbee images.
139
140
# XXX if this is actually used, it will have to be fixed; DB no longer
# tracks running frisbee daemons.
141
142
143
144
145
146
147
#
sub ActiveImages($)
{
    my ($class) = @_;
    my @result  = ();

    my $query_result =
148
	DBQueryWarn("select imageid from frisbee_blobs where frisbee_pid!=0");
149
150
151
152
153
154
155
156
157
158
159
160
161
162
    return undef
	if (!defined($query_result));

    while (my ($imageid) = $query_result->fetchrow_array()) {
	my $image = Image->Lookup($imageid);
	if (!defined($image)) {
	    print STDERR "*** Could not find DB object for image $imageid\n";
	    return undef;
	}
	push(@result, $image);
    }
    return \@result;
}

163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

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

    my $imageid = $self->imageid();
    
    my $query_result =
	DBQueryWarn("select * from images where imageid=$imageid");

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

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

    return 0;
}

186
187
188
189
#
# Create a new os_info. This installs the new record in the DB,
# and returns an instance. There is some bookkeeping along the way.
#
190
sub Create($$$$$$$$)
191
{
192
193
    my ($class, $project, $group, $creator,
	$imagename, $imageid, $argref, $usrerr_ref) = @_;
194
    require OSinfo;
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213

    return undef
	if (ref($class) || !ref($project));

    my $isadmin = $creator->IsAdmin();

    # We may ignore particular partN_osid's by deleting them.
    my @arg_slots = grep(/^part[1-4]_osid$/, keys(%{$argref}));

    # Pass-through a bunch of required slots, ignoring any extras
    # and stuff we handle explicitly.
    foreach my $key ("loadpart", "loadlength", "default_osid") {
	if (!exists($argref->{$key})) {
	    $$usrerr_ref = "Error: $key missing in Image->Create!";
	    return undef;
	}
	push(@arg_slots, $key);
    }
    # Pass-through optional slots, otherwise the DB default is used.
214
    foreach my $key ("path", "shared", "global", "ezid", "mbr_version") {
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
	if (exists($argref->{$key})) {
	    push(@arg_slots, $key);
	}
    }

    my $pid     = $project->pid();
    my $pid_idx = $project->pid_idx();
    my $gid     = $group->gid();
    my $gid_idx = $group->gid_idx();
    my $uid     = $creator->uid();
    my $uid_idx = $creator->uid_idx();

    #
    # The pid/imageid has to be unique, so lock the table for the check/insert.
    #
    DBQueryWarn("lock tables images write, emulab_indicies write")
	or return undef;

    my $query_result =
	DBQueryWarn("select imagename from images ".
		    "where pid_idx='$pid_idx' and imagename='$imagename'");

    if ($query_result->numrows) {
	DBQueryWarn("unlock tables");
	$$usrerr_ref = "Error: IMAGE $imagename in project $pid already exists!";
	return undef;
    }

243
244
245
246
247
248
249
250
251
252
253
254
255
    # We allow providing an image descriptor index, so newimageid_ez can use
    # the same name, description, and index for both the OS and Image it makes.
    if ($imageid > 0 ) {
	# Make sure the OS descriptor for it already exists.
	if (!OSinfo->Lookup($imageid)) {
	    DBQueryWarn("unlock tables");
	    $$usrerr_ref = "Error: Missing OSinfo $imagename/$imageid in $pid!";
	    return undef;
	}
    } else {
	#
	# Grab unique ID. Table already locked.
	# 
256
	$imageid  = TBGetUniqueIndex("next_osid", undef, 1);
257
    }
258
259
260
261
    my $uuid  = NewUUID();

    # Some fields special cause of quoting.
    #
262
    my $desc  = "''";
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
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
350
351
352
353
    if (exists($argref->{'description'})) {
	$desc = DBQuoteSpecial($argref->{'description'});
    }
    
    my $query = "insert into images set ".
	join(",", map("$_='" . $argref->{$_} . "'", @arg_slots));

    # Append the rest
    $query .= ",imagename='$imagename'";
    $query .= ",imageid='$imageid'";
    $query .= ",uuid='$uuid'";
    $query .= ",pid='$pid',pid_idx='$pid_idx'";
    $query .= ",gid='$gid',gid_idx='$gid_idx'";
    $query .= ",creator='$uid',creator_idx='$uid_idx'";
    $query .= ",created=now()";
    $query .= ",description=$desc";    
    
    if (! DBQueryWarn($query)) {
	DBQueryWarn("unlock tables");
	tberror("Error inserting new images record for $pid/$imagename!");
	return undef;
    }

    my $image = Image->Lookup($imageid);
    # Create the osidtoimageid mapping.  Admins have an option to do it or not.
    my $makedefault = exists($argref->{"makedefault"}) && 
	$argref->{"makedefault"} eq "1";
    if (!$isadmin || $makedefault) {

	# Lock tables unlocks previous locks as a side-effect.
	DBQueryWarn("lock tables osidtoimageid write, images write, ".
		    "nodes as n write, node_type_attributes as a write");
	#
	# Need a list of node types. We join this over the nodes table so that
	# we get a list of just the nodes that are currently in the testbed, not
	# just in the node_types table.
	#
	my $types_result =
	    DBQueryWarn("select distinct n.type from nodes as n ".
			 "left join node_type_attributes as a on a.type=n.type ".
			 "where a.attrkey='imageable' and ".
			 "      a.attrvalue!='0'");
	my @mtypes_array;
	my @map_updates;
	while (my ($type) = $types_result->fetchrow_array()) {
	    push(@mtypes_array, $type);

	    # Remember when we get one of the mtype_$type args.  These aren't DB
	    # columns to update, but instead control re-creating the rows in the
	    # osidtoimageid table for this imageid, below.
	    my $mtype = "mtype_$type";
	    if (exists($argref->{$mtype})) {
		my $value = $argref->{$mtype};
		##printf "argref->{$mtype} %s\n", $value;
		if ($value eq "1") {
		    push(@map_updates, $type);
		}
	    }
	}

	my @osid_array;
	for (my $i = 1; $i <= 4; $i++) {
	    my $foo = $image->field("part${i}_osid");
	    if (defined($foo)) {
		push(@osid_array, $foo);
	    }
	}

	for (my $i = 0; $i <= $#map_updates; $i++) {
	    for (my $j = 0; $j <= $#osid_array; $j++) {
		 my $query = "INSERT INTO osidtoimageid ".
			     "       (osid, type, imageid) ".
			     "VALUES ('$osid_array[$j]', ".
			     "        '$map_updates[$i]', ".
			     "        '$imageid')";
		 ##print "$query\n";
		 if (! DBQueryWarn($query)) {
		     DBQueryWarn("unlock tables");
		     tberror("Error inserting new ostoimageid mapping for ".
			     "$pid/$imagename!");
		     return undef;
		 }
	    }
	}
    }

    DBQueryWarn("unlock tables");

    return $image;
}

354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#
# Worker class method to edit image descriptor.
# Assumes most argument checking was done elsewhere.
#
sub EditImageid($$$$)
{
    my ($class, $image, $argref, $usrerr_ref) = @_;

    my %mods;
    my $noreport;

    my $imageid = $image->imageid();

    #
    # Now update the rest of the information in the DB.
    # (Others above already did their own updates.)
    #
    my %updates;
372
    foreach my $col ("description", "path") {
373
374
375
376
377
378
379
380
381
382
383
384
385
	# Copy args we want so that others can't get through.
	if (exists($argref->{$col})) {
	    $updates{$col} = $mods{$col} = $argref->{$col};
	}
    }
    # See mtype_$type args below.

    #
    # Need a list of node types. We join this over the nodes table so that
    # we get a list of just the nodes that are currently in the testbed, not
    # just in the node_types table.
    #
    my $types_result =
386
	DBQueryWarn("select distinct n.type from nodes as n ".
387
388
389
390
391
392
393
394
		     "left join node_type_attributes as a on a.type=n.type ".
		     "where a.attrkey='imageable' and ".
		     "      a.attrvalue!='0'");
    my @mtypes_array;
    my @map_updates;
    my $redo_map = 0;
    while (my ($type) = $types_result->fetchrow_array()) {
	push(@mtypes_array, $type);
395
396
397
398
399
    }
    #
    # Special hack to allow pcvm type -- see SetupReload in os_setup
    #
    push @mtypes_array, "pcvm";
400

401
    foreach my $type (@mtypes_array) {
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
	# Remember when we get one of the mtype_$type args.  These aren't DB
	# columns to update, but instead control re-creating the rows in the
	# osidtoimageid table for this imageid, below.
	my $mtype = "mtype_$type";
	if (exists($argref->{$mtype})) {
	    my $value = $argref->{$mtype};
	    ##printf "argref->{$mtype} %s\n", $value;
	    $mods{$mtype} = $value;
	    if ($value eq "1") {
		push(@map_updates, $type);
		$redo_map = 1;
	    }
	}
    }

    if (!keys %mods) {
	if (!$noreport) {
	    # Warn the user that the submit button was pressed with no effect.
	    $$usrerr_ref = "Submit: Nothing changed";
	    return undef;
	}
    }

    if (keys %updates || $redo_map) {
426
	DBQueryWarn("lock tables images write, os_info write, ".
427
428
429
430
431
		     "osidtoimageid write");
    }
    if (keys %updates) {
	if ($image->Update(\%updates)) {
	    $$usrerr_ref = "DB: Error updating the images table";
432
	    DBQueryWarn("unlock tables");
433
434
435
436
437
438
439
440
	    return undef;
	}
    }
    if ($redo_map) {
	#
	# Update the osidtoimageid table too.
	# 
	# Must delete old entries first.
441
	DBQueryWarn("delete from osidtoimageid ".
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
		     "where imageid='$imageid'");

	my @osid_array;
	for (my $i = 1; $i <= 4; $i++) {
	    my $foo = $image->field("part${i}_osid");
	    if (defined($foo)) {
		push(@osid_array, $foo);
	    }
	}
	for (my $i = 0; $i <= $#map_updates; $i++) {
	    for (my $j = 0; $j <= $#osid_array; $j++) {
		 my $query = "REPLACE INTO osidtoimageid ".
			     "       (osid, type, imageid) ".
			     "VALUES ('$osid_array[$j]', ".
			     "        '$map_updates[$i]', ".
			     "        '$imageid')";
		 ##print "$query\n";
459
		 DBQueryWarn($query);
460
461
462
463
	    }
	}
    }
    if (keys %updates || $redo_map) {
464
	DBQueryWarn("unlock tables");
465
466
467
468
469
    }

    return 1;
}

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
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $pid       = $self->pid();
    my $imageid   = $self->imageid();
    my $imagename = $self->imagename();

    return "[Image $imageid: $pid,$imagename]";
}

#
# Return the internal DB rowref. Used for code that has not been converted.
#
sub DBData($)
{
    my ($self) = @_;

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

    return $self->{'IMAGE'}
}

#
# Perform some updates ...
#
sub Update($$)
{
    my ($self, $argref) = @_;

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

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

    my $query = "update images set ".
	join(",", map("$_='" . $argref->{$_} . "'", keys(%{$argref})));

    $query .= " where imageid='$imageid'";

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

    return Refresh($self);
}

#
522
523
524
525
526
# Load the project object for an image
#
sub GetProject($)
{
    my ($self) = @_;
527
    require Project;
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547

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

    my $project = Project->Lookup($self->pid_idx());
    
    if (! defined($project)) {
	print("*** WARNING: Could not lookup project object for $self!", 1);
	return undef;
    }
    return $project;
}

#
# Load the group object for an image
#
sub GetGroup($)
{
    my ($self) = @_;
548
    require Group;
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565

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

    my $group = Group->Lookup($self->gid_idx());
    
    if (! defined($group)) {
	print("*** WARNING: Could not lookup group object for $self!", 1);
	return undef;
    }
    return $group;
}

#
# Check permissions. Note that root may ask permission, which comes in
# as an undef user.
566
567
568
569
570
571
#
sub AccessCheck($$$)
{
    my ($self, $user, $access_type) = @_;

    # Must be a real reference. 
572
    return 0
573
574
	if (! ref($self));

575
576
577
578
579
580
581
582
    if ($access_type < TB_IMAGEID_MIN || $access_type > TB_IMAGEID_MAX) {
	print "*** Invalid access type $access_type!\n";
	return 0;
    }
    # Admins and root do whatever they want.
    return 1
	if ((defined($user) && $user->IsAdmin()) ||
	    ($UID == 0 || $UID eq "root"));
583

584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
    my $mintrust;
    
    #
    # Global ImageIDs can be read by anyone.
    #
    if ($self->global()) {
	if ($access_type == TB_IMAGEID_READINFO) {
	    return 1;
	}
	return 0;
    }

    my $project = $self->GetProject();
    return 0
	if (!defined($project));
    my $group = $self->GetGroup();
    return 0
	if (!defined($group));

    #
    # Otherwise must have proper trust in the group
    #
    if ($access_type == TB_IMAGEID_READINFO) {
	$mintrust = PROJMEMBERTRUST_USER;
        #
        # Shared imageids are readable by anyone in the project.
        #
	if ($self->shared()) {
	    $group = $project->GetProjectGroup();
	}
    }
    else {
	$mintrust = PROJMEMBERTRUST_LOCALROOT;
    }

    #
    # Either proper permission in the group, or group_root in the project.
    # This lets group_roots muck with other people's experiments, including
    # those in groups they do not belong to.
    #
    return TBMinTrust($group->Trust($user), $mintrust) ||
	TBMinTrust($project->Trust($user), PROJMEMBERTRUST_GROUPROOT);
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
652
653
654
655
656
657
658
659
660
#
# LockTables simply locks the given tables, and then refreshes the
# instance (thereby getting the data from the DB after the tables are locked).
#
sub LockTables($;$)
{
    my ($self, $spec) = @_;

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

    $spec = "images write"
	if (!defined($spec));
    
    DBQueryWarn("lock tables $spec")
	or return -1;
	
    return $self->Refresh();
}
sub UnLockTables($)
{
    my ($self) = @_;

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

    DBQueryWarn("unlock tables")
	or return -1;
    return 0;
}

661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
#
# Mark the update time in the record,
#
sub MarkUpdateTime($)
{
    my ($self) = @_;

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

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

    return -1
	if (! DBQueryWarn("update images set updated=now() " .
			  "where imageid='$imageid'"));

    return 0;
}

681

682
683
# _Always_ make sure that this 1 is at the end of the file...
1;