Image.pm.in 27.6 KB
Newer Older
1
2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2007-2013 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
#
package Image;

use strict;
27
use Carp;
28
use Exporter;
29
use vars qw(@ISA @EXPORT $AUTOLOAD);
30
31
32
33
34
35

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

# Must come after package declaration!
use libdb;
36
use EmulabConstants;
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
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;
}
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156

AUTOLOAD {
    my $self  = $_[0];
    my $type  = ref($self) or croak "$self is not an object";
    my $name  = $AUTOLOAD;
    $name =~ s/.*://;   # strip fully-qualified portion

    # A DB row proxy method call.
    if (exists($self->{'IMAGE'}->{$name})) {
	return $self->{'IMAGE'}->{$name};
    }
    carp("No such slot '$name' field in class $type");
    return undef;
}

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

    $self->{'IMAGE'} = undef;
}

#
# Lookup by URL.
#
sub LookupByURL($$)
{
    my ($class, $url) = @_;

    return undef
157
	if (! ($url =~ /^(ftp|http|https):/));
158
159
160
161
162
163
164
165
166
167
168
169

    my $safe_url = DBQuoteSpecial($url);
    
    my $query_result =
	DBQueryWarn("select imageid from images where metadata_url=$safe_url");
    return undef
	if (!$query_result || !$query_result->numrows);

    my ($imageid) = $query_result->fetchrow_array();

    return Image->Lookup($imageid);
}
170

171
172
#
# Get a list of all running frisbee images.
173
174
# XXX if this is actually used, it will have to be fixed; DB no longer
# tracks running frisbee daemons.
175
176
177
178
179
180
181
#
sub ActiveImages($)
{
    my ($class) = @_;
    my @result  = ();

    my $query_result =
182
	DBQueryWarn("select imageid from frisbee_blobs where frisbee_pid!=0");
183
184
185
186
187
188
189
190
191
192
193
194
195
196
    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;
}

197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#
# 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;
}

220
221
222
223
#
# Create a new os_info. This installs the new record in the DB,
# and returns an instance. There is some bookkeeping along the way.
#
224
sub Create($$$$$$$$)
225
{
226
227
    my ($class, $project, $group, $creator,
	$imagename, $imageid, $argref, $usrerr_ref) = @_;
228
    require OSinfo;
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247

    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.
248
249
    foreach my $key ("path", "shared", "global", "ezid", "mbr_version",
		     "metadata_url", "imagefile_url") {
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
	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;
    }
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
    # The metadata_url also has to be unique.
    if (exists($argref->{'metadata_url'})) {
	my $metadata_url = $argref->{'metadata_url'};
	my $safe_url = DBQuoteSpecial($metadata_url);
	
	my $query_result =
	    DBQueryWarn("select imagename from images ".
			"where metadata_url=$safe_url");

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

293
294
295
296
297
298
299
300
301
302
303
304
305
    # 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.
	# 
306
	$imageid  = TBGetUniqueIndex("next_osid", undef, 1);
307
    }
308
309
310
311
    my $uuid  = NewUUID();

    # Some fields special cause of quoting.
    #
312
    my $desc  = "''";
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
    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()";
Leigh B Stoller's avatar
Leigh B Stoller committed
328
329
330
    $query .= ",description=$desc";
    $query .= ",hash=" . DBQuoteSpecial($argref->{'hash'})
	if (exists($argref->{'hash'}));
331
332
333
334
335
336
337
338
339

    #
    # If this is set in the environment, we use it. This allows
    # us to track actual geni users, since all of that happens
    # as geniuser. We do not bother to set this for local users.
    #
    if (exists($ENV{'GENIURN'}) && $ENV{'GENIURN'} ne "") {
	$query .= ",creator_urn=". DBQuoteSpecial($ENV{'GENIURN'});
    }
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
    
    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");
356

357
	#
358
359
360
	# Dig out the mtypes we want to turn on. The caller has already
	# sanity checked them to make sure the types actually exist, and
	# that there are nodes matching that type.
361
	#
362
363
364
365
366
	my @map_updates = ();
	foreach my $key (grep(/^mtype_/, keys(%{$argref}))) {
	    if ($argref->{$key} eq "1") {
		$key =~ s/^mtype_//;
		push(@map_updates, $key);
367
368
369
	    }
	}

370
	my @osid_array = ();
371
	for (my $i = 1; $i <= 4; $i++) {
372
373
	    my $func = "part${i}_osid";
	    my $foo  = $image->$func();
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
	    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;
}

402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#
# 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;
Leigh B Stoller's avatar
Leigh B Stoller committed
420
    foreach my $col ("description", "path", "mbr_version", "hash") {
421
422
423
424
425
426
427
428
429
430
431
432
433
	# 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 =
434
	DBQueryWarn("select distinct n.type from nodes as n ".
435
436
437
438
439
440
441
442
		     "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);
443
444
445
446
447
    }
    #
    # Special hack to allow pcvm type -- see SetupReload in os_setup
    #
    push @mtypes_array, "pcvm";
448

449
    foreach my $type (@mtypes_array) {
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
	# 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) {
474
	DBQueryWarn("lock tables images write, os_info write, ".
475
476
477
478
479
		     "osidtoimageid write");
    }
    if (keys %updates) {
	if ($image->Update(\%updates)) {
	    $$usrerr_ref = "DB: Error updating the images table";
480
	    DBQueryWarn("unlock tables");
481
482
483
484
485
486
487
488
	    return undef;
	}
    }
    if ($redo_map) {
	#
	# Update the osidtoimageid table too.
	# 
	# Must delete old entries first.
489
	DBQueryWarn("delete from osidtoimageid ".
490
491
492
493
		     "where imageid='$imageid'");

	my @osid_array;
	for (my $i = 1; $i <= 4; $i++) {
494
495
	    my $func = "part${i}_osid";
	    my $foo  = $image->$func();
496
497
498
499
500
501
502
503
504
505
506
507
	    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";
508
		 DBQueryWarn($query);
509
510
511
512
	    }
	}
    }
    if (keys %updates || $redo_map) {
513
	DBQueryWarn("unlock tables");
514
515
516
517
518
    }

    return 1;
}

519
520
521
522
523
524
525
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
557
558
559
560
561
562
563
564
565
566
567
568
569
#
# 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);
}

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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
#
# Delete a descriptor. 
#
sub Delete($)
{
    my ($self) = @_;

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

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

    DBQueryWarn("lock tables images write, os_info write, ".
		"osidtoimageid write, os_submap write")
	or return -1;

    #
    # If this is an EZ imageid, then delete the corresponding OSID too.
    #
    DBQueryWarn("delete from osidtoimageid where imageid='$imageid'")
	or goto bad;
    DBQueryWarn("delete from images where imageid='$imageid'")
	or goto bad;
    if ($self->ezid()) {
	DBQueryWarn("delete from os_submap where osid='$imageid'")
	    or goto bad;
	DBQueryWarn("delete from os_info where osid='$imageid'")
	    or goto bad;
    }
    DBQueryWarn("unlock tables")
	or return -1;

    delete($images{"$imageid"});
    return 0;

  bad:
    DBQueryWarn("unlock tables");
    return -1;
}

611
#
612
613
614
615
616
# Load the project object for an image
#
sub GetProject($)
{
    my ($self) = @_;
617
    require Project;
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637

    # 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) = @_;
638
    require Group;
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655

    # 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.
656
657
658
659
#
sub AccessCheck($$$)
{
    my ($self, $user, $access_type) = @_;
660
    require Group;
661
662

    # Must be a real reference. 
663
    return 0
664
665
	if (! ref($self));

666
667
668
669
    if ($access_type < TB_IMAGEID_MIN || $access_type > TB_IMAGEID_MAX) {
	print "*** Invalid access type $access_type!\n";
	return 0;
    }
670
671
672
    my $isadmin = ((defined($user) && $user->IsAdmin()) ||
		   ($UID == 0 || $UID eq "root") ? 1 : 0);
	
673
674
    # Admins and root do whatever they want.
    return 1
675
	if ($isadmin);
676

677
678
679
680
681
682
683
684
685
    my $mintrust;
    
    #
    # Global ImageIDs can be read by anyone.
    #
    if ($self->global()) {
	if ($access_type == TB_IMAGEID_READINFO) {
	    return 1;
	}
686
687
688
	if ($access_type == TB_IMAGEID_EXPORT && $isadmin) {
	    return 1;
	}
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
    }

    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();
	}
    }
710
711
712
713
714
715
716
717
718
    elsif ($access_type == TB_IMAGEID_EXPORT) {
	#
	# Owner or root in the project.
	#
	return 1
	    if ($user->uid_idx() == $self->creator_idx());

	$mintrust = PROJMEMBERTRUST_GROUPROOT;
    }
719
720
721
722
723
724
725
726
727
    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.
    #
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
    return 1
	if (TBMinTrust($group->Trust($user), $mintrust) ||
	    TBMinTrust($project->Trust($user), PROJMEMBERTRUST_GROUPROOT));

    # No point in looking further; never allowed.
    return 0
	if ($access_type == TB_IMAGEID_EXPORT);

    #
    # Look in the image permissions. First look for a user permission,
    # then look for a group permission.
    #
    my $uid_idx = $user->uid_idx();
    my $imageid = $self->imageid();
    
    my $query_result = 
	DBQueryWarn("select allow_write from image_permissions ".
		    "where imageid='$imageid' and ".
		    "      permission_type='user' and ".
		    "      permission_idx='$uid_idx'");
    return 0
	if (!$query_result);
    
    if ($query_result->numrows) {
	# READINFO is read-only access to the image and its contents.
	return 1
	    if ($access_type == TB_IMAGEID_READINFO());
	
	if ($access_type == TB_IMAGEID_ACCESS()) {
	    my ($allow_write) = $query_result->fetchrow_array();

	    return 1
		if ($allow_write);
	}
    }
763
    my $trust_none = $Group::MemberShip::TRUSTSTRING_NONE;
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
    $query_result = 
	DBQueryFatal("select allow_write from group_membership as g ".
		     "left join image_permissions as p on ".
		     "     p.permission_type='group' and ".
		     "     p.permission_idx=g.gid_idx ".
		     "where g.uid_idx='$uid_idx' and ".
		     "      p.imageid='$imageid' and ".
		     "      trust!='$trust_none'");

    if ($query_result->numrows) {
	# READINFO is read-only access to the image and its contents.
	return 1
	    if ($access_type == TB_IMAGEID_READINFO());
	
	if ($access_type == TB_IMAGEID_ACCESS()) {
	    my ($allow_write) = $query_result->fetchrow_array();

	    return 1
		if ($allow_write);
	}
    }
    return 0;
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
#
# 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;
}

821
822
823
#
# Mark the update time in the record,
#
824
sub MarkUpdate($$;$)
825
{
826
    my ($self, $user, $stamp) = @_;
827
828
829
830
831

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

832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
    my $imageid     = $self->imageid();
    my $updater     = "";
    my $updater_idx = "";
    my $updater_urn = "";
    if (defined($user)) {
	$updater     = ", updater='" . $user->uid() . "'";
	$updater_idx = ", updater_idx='" . $user->uid_idx() . "'";
    }
    #
    # If this is set in the environment, we use it. This allows
    # us to track actual geni users, since all of that happens
    # as geniuser. We do not bother to set this for local users.
    #
    if (exists($ENV{'GENIURN'}) && $ENV{'GENIURN'} ne "") {
	$updater_urn = ", updater_urn=". DBQuoteSpecial($ENV{'GENIURN'});
    }
    
849
850
851
852
853
854
855
    if (defined($stamp)) {
	$stamp="FROM_UNIXTIME($stamp)";
    }
    else {
	$stamp="now()";
    }

856
    return -1
857
	if (! DBQueryWarn("update images set updated=$stamp " .
858
			  "  $updater $updater_idx $updater_urn ".
859
860
861
862
863
			  "where imageid='$imageid'"));

    return 0;
}

Leigh B Stoller's avatar
Leigh B Stoller committed
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
#
# Set the hash.
#
sub SetHash($$)
{
    my ($self, $hash) = @_;

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

    my $imageid   = $self->imageid();
    my $safe_hash = DBQuoteSpecial($hash);

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

    return 0;
}

885
#
886
# Lock and Unlock
887
#
888
889
890
891
892
893
894
895
896
897
898
899
900
sub Lock($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));
    return -1
	if (!DBQueryWarn("lock tables images write"));

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

    my $query_result =
901
	DBQueryWarn("update images set locked=now(),locker_pid=$PID " .
902
903
904
905
906
907
908
909
910
		    "where imageid='$imageid' and locked is null");

    if (! $query_result ||
	$query_result->numrows == 0) {
	DBQueryWarn("unlock tables");
	return -1;
    }
    DBQueryWarn("unlock tables");
    $self->{'IMAGE'}->{'locked'} = time();
911
    $self->{'IMAGE'}->{'locker_pid'} = $PID;
912
913
914
915
    return 0;
}

sub Unlock($)
916
917
{
    my ($self) = @_;
918
919
920
921
922
923
924
925

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

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

    return -1
926
	if (! DBQueryWarn("update images set locked=null,locker_pid=0 " .
927
928
929
			  "where imageid='$imageid'"));
    
    $self->{'IMAGE'}->{'locked'} = 0;
930
    $self->{'IMAGE'}->{'locker_pid'} = 0;
931
932
933
    return 0;
}

934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
sub GotLock($)
{
    my ($self) = @_;

    return 1
	if ($self->{'IMAGE'}->{'locked'} &&
	    $self->{'IMAGE'}->{'locker_pid'} == $PID);
    
    return 0;
}

#
# Wait to get lock.
#
sub WaitLock($$)
{
    my ($self, $seconds) = @_;

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

    while ($seconds > 0) {
	return 0
	    if ($self->Lock() == 0);

	# Sleep and try again.
	sleep(5);
	$seconds -= 5;
    }
    # One last try.
    return $self->Lock();
}

968
969
970
971
972
973
#
# Get the type list.
#
sub TypeList($;$)
{
    my ($self, $osinfo) = @_;
974
975
976
977
    require NodeType;

    my @result  = ();
    my $imageid = $self->imageid();
978
979
    my $clause  = (defined($osinfo) ?
		   "and osid='" . $osinfo->osid() . "'" : "");
980
981
982

    my $query_result =
	DBQueryWarn("select distinct type from osidtoimageid ".
983
		    "where imageid='$imageid' $clause");
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
    return undef
	if (!defined($query_result));

    while (my ($type) = $query_result->fetchrow_array()) {
	my $typeinfo = NodeType->Lookup($type);
	push(@result, $typeinfo)
	    if (defined($typeinfo));
    }
    return @result;
}

#
# Grant/Revoke permission to access an image.
#
sub GrantAccess($$$)
{
    my ($self, $target, $writable) = @_;
    $writable = ($writable ? 1 : 0);

    my $imageid   = $self->imageid();
    my $imagename = $self->imagename();
    my ($perm_idx, $perm_id, $perm_type);

    if (ref($target) eq "User") {
	$perm_idx  = $target->uid_idx();
	$perm_id   = $target->uid();
	$perm_type = "user";
    }
    if (ref($target) eq "Group") {
	$perm_idx  = $target->gid_idx();
	$perm_id   = $target->pid() . "/" . $target->gid();
	$perm_type = "group";
    }

    return -1
	if (!DBQueryWarn("replace into image_permissions set ".
			 "  imageid='$imageid', imagename='$imagename', ".
			 "  permission_type='$perm_type', ".
			 "  permission_id='$perm_id', ".
			 "  permission_idx='$perm_idx', ".
			 "  allow_write='$writable'"));
    return 0;
}

sub RevokeAccess($$)
{
    my ($self, $target) = @_;

    my $imageid   = $self->imageid();
    my ($perm_idx, $perm_type);

    if (ref($target) eq "User") {
	$perm_idx  = $target->uid_idx();
	$perm_type = "user";
    }
    if (ref($target) eq "Group") {
	$perm_idx  = $target->gid_idx();
	$perm_type = "group";
    }

    return -1
	if (!DBQueryWarn("delete from image_permissions ".
			 "where imageid='$imageid' and ".
			 "  permission_type='$perm_type' and ".
			 "  permission_idx='$perm_idx'"));
    return 0;
}
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
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
#
# Class method to record image history info. 
#
sub RecordImageHistory($$$$$$)
{
    my ($class, $experiment, $action, $log_session, $impotent, $noderef) = @_;
    require Node;
    
    # Flush info; we want most recent.
    $experiment->Refresh();
    
    my $exptidx   = $experiment->idx();
    my $pid       = $experiment->pid();
    my $eid       = $experiment->eid();
    my $state     = $experiment->state();
    my $rsrcidx   = $experiment->rsrcidx();
    my $lastrsrc  = $experiment->lastrsrc();
    $log_session  = 'NULL' if (!defined($log_session));

    my %prev_alloc;
    my $cant_find_prev_alloc = 0;
    if ($state eq 'modify_reswap') {
	if (!defined($lastrsrc)) {
	    print STDERR "lastrsrc not set during swapmod\n";
	    return -1;
	}
	my $db_result =
	    DBQueryWarn("select node_id from image_history ".
			"where rsrcidx=$lastrsrc");
	return -1
	    if (!$db_result);
	
	if ($db_result->numrows() < 1) {
	    print STDERR "could not find previous state (rsrcidx=$lastrsrc) ".
		"in image_history table, won't be able to determine ".
		"newly allocated nodes\n";
	    $cant_find_prev_alloc = 1;
	}
	while (my $n = $db_result->fetchrow) {
	    $prev_alloc{$n} = 1;
	}
    }

    foreach my $node_id (keys(%{$noderef})) {
	my $node = Node->Lookup($node_id);
	if (! defined($node)) {
	    print STDERR "No DB record for $node_id\n";
	    next;
	}
	# Need uptodate info below.
	$node->FlushReserved();
	
	my $ref  = $noderef->{$node_id};
	my ($osid, $imageid) = @{$ref};
	my $newly_alloc      = (exists($prev_alloc{$node_id}) ? 0 : 1);
	$newly_alloc = 'NULL'
	    if ($cant_find_prev_alloc);

	my $history_result =
	    DBQueryWarn("select max(history_id) ".
			"  from node_history where node_id = '$node_id'");
	return -1
	    if (! $history_result);

	if (! $history_result->numrows) {
	  nohistory:
	    print STDERR "No node_history for $node_id, ".
		"cannot log image usage for node.\n";
	    next;
	}
	my ($node_history_id) = $history_result->fetchrow_array();
	if (!defined($node_history_id)) {
	    goto nohistory;
	}
	my $vname      = $node->vname();
	my $erole      = $node->erole();
	my $phys_type  = $node->type();

	if (!defined($vname)) {
	    print STDERR "$node is no longer reserved!\n";
	    next;
	}

	# Ick. Should go into the Node object.
	my ($virt_result) =
	    DBQueryWarn("select osname,type from virt_nodes ".
			"where exptidx='$exptidx' and vname='$vname'");
	return -1
	    if (!$virt_result);
	if (!$virt_result->numrows) {
	    print STDERR "No virt info for node $node_id ($vname)\n";
	    next;
	}
	my ($osname, $req_type) = $virt_result->fetchrow_array();
	my $req_os = defined $osname ? ($osname ? 1 : 0) : 'NULL';
	$erole = 'delay' if $erole eq 'delaynode';
	$req_type = $erole unless defined $req_type;

	next
	    if ($impotent);
	
	DBQueryWarn("insert into image_history ".
		    "(stamp, node_history_id, node_id, ".
		    " action, newly_alloc, rsrcidx, log_session, ".
		    " req_type, phys_type, req_os, osid, imageid) ".
		    "values(UNIX_TIMESTAMP(now()), ".
		    "       $node_history_id, '$node_id', '$action', ".
		    "       $newly_alloc, $rsrcidx, ".
		    "       $log_session, '$req_type', '$phys_type', ".
		    "       $req_os, $osid, $imageid)")
	    or return -1;
    }
    return 0;
}

1167
1168
# _Always_ make sure that this 1 is at the end of the file...
1;