editimageid.in 13.5 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
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
#
use English;
use strict;
use Getopt::Std;
use XML::Simple;
use Data::Dumper;
29
use Cwd qw(realpath);
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

#
# Back-end script to edit image descriptor.
#
sub usage()
{
    print("Usage: editimageid [-v] <xmlfile>\n");
    exit(-1);
}
my $optlist = "dv";
my $debug   = 0;
my $verify  = 0;	# Check data and return status only. 

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $TBAUDIT	= "@TBAUDITEMAIL@";
my $TBGROUP_DIR	= "@GROUPSROOT_DIR@";
my $TBPROJ_DIR	= "@PROJROOT_DIR@";

#
# Untaint the path
#
$ENV{'PATH'} = "$TB/bin:$TB/sbin:/bin:/usr/bin:/usr/bin:/usr/sbin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
#
# Turn off line buffering on output
#
$| = 1;

#
# Load the Testbed support stuff.
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use User;
use Project;
70
use OSImage;
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

# Protos
sub fatal($);
sub UserError(;$);
sub escapeshellarg($);

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"v"})) {
    $verify = 1;
}
if (@ARGV != 1) {
    usage();
}
my $xmlfile  = shift(@ARGV);

#
# Map invoking user to object. 
# If invoked as "nobody" we are coming from the web interface and the
# current user context is "implied" (see tbauth.php3).
#
my $this_user;

if (getpwuid($UID) ne "nobody") {
    $this_user = User->ThisUser();

    if (! defined($this_user)) {
	fatal("You ($UID) do not exist!");
    }
    # You don't need admin privileges to edit image descriptor.
}
else {
    #
    # Check the filename when invoked from the web interface; must be a
    # file in /tmp.
    #
    if ($xmlfile =~ /^([-\w\.\/]+)$/) {
	$xmlfile = $1;
    }
    else {
	fatal("Bad data in pathname: $xmlfile");
    }

    # Use realpath to resolve any symlinks.
124
    my $translated = realpath($xmlfile);
125 126 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
    if ($translated =~ /^(\/tmp\/[-\w\.\/]+)$/) {
	$xmlfile = $1;
    }
    else {
	fatal("Bad data in translated pathname: $xmlfile");
    }

    # The web interface (and in the future the xmlrpc interface) sets this.
    $this_user = User->ImpliedUser();

    if (! defined($this_user)) {
	fatal("Cannot determine implied user!");
    }
}

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

#
# These are the fields that we allow to come in from the XMLfile.
#
my $SLOT_OPTIONAL	= 0x1;	# The field is not required.
my $SLOT_REQUIRED	= 0x2;  # The field is required and must be non-null.
my $SLOT_ADMINONLY	= 0x4;  # Only admins can set this field.

# XXX We should encode all of this in the DB so that we can generate the
# forms on the fly, as well as this checking code.
#
my %xmlfields =
    # XML Field Name        DB slot name         Flags             Default
    ("imageid"		=> ["imageid",		$SLOT_REQUIRED],
155
     "version"		=> ["version",		$SLOT_REQUIRED],
156 157 158 159

     # The rest are optional, so we can skip passing ones that are not changing.
     "description"	=> ["description",	$SLOT_OPTIONAL],
     "path"		=> ["path",		$SLOT_OPTIONAL],
160
     "mbr_version",	=> ["mbr_version",	$SLOT_OPTIONAL],
161
     "mtype_*"		=> ["mtype",		$SLOT_OPTIONAL],
Leigh Stoller's avatar
Leigh Stoller committed
162
     "hash",		=> ["hash",		$SLOT_ADMINONLY],
163
     "notes",		=> ["notes",		$SLOT_ADMINONLY],
164
     "architecture"	=> ["architecture",	$SLOT_OPTIONAL],
165
    );
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
#
# 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 =
    DBQueryFatal("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'");
# Save the valid types in a new array for later.
my @mtypes_array;
while (my ($type) = $types_result->fetchrow_array()) {
    push(@mtypes_array, $type);
    $xmlfields{"mtype_$type"} = ["mtype", $SLOT_OPTIONAL];
}
182 183 184 185 186
#
# Special hack to allow pcvm type -- see SetupReload in os_setup
#
push(@mtypes_array, "pcvm");
$xmlfields{"mtype_pcvm"} = ["mtype", $SLOT_OPTIONAL];
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
## printf "%s mtypes\n", $#mtypes_array + 1;
## foreach my $x (@mtypes_array) { printf "%s\n", $x; }
## print "\n";

#
# Must wrap the parser in eval since it exits on error.
#
my $xmlparse = eval { XMLin($xmlfile,
			    VarAttr => 'name',
			    ContentKey => '-content',
			    SuppressEmpty => undef); };
fatal($@)
    if ($@);

#
# Process and dump the errors (formatted for the web interface).
# We should probably XML format the errors instead but not sure I want
# to go there yet.
#
my %errors = ();

#
# Make sure all the required arguments were provided.
#
my $key;
foreach $key (keys(%xmlfields)) {
    my (undef, $required, undef) = @{$xmlfields{$key}};

    $errors{$key} = "Required value not provided"
	if ($required & $SLOT_REQUIRED  &&
	    ! exists($xmlparse->{'attribute'}->{"$key"}));
}
UserError()
    if (keys(%errors));

#
# We build up an array of arguments to pass to Image->EditImageid() as we check
# the attributes.
#
my %editimageid_args = ();
my $foo;

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
#
# Wildcard keys have one or more *'s in them like simple glob patterns.
# This allows multiple key instances for categories of attributes, and
# putting a "type signature" in the key for arg checking, as well.
#
# Wildcards are made into regex's by anchoring the ends and changing each * to
# a "word" (group of alphahumeric.)  A tail * means "the rest", allowing
# multiple words separated by underscores or dashes.
#
my $wordpat = '[a-zA-Z0-9]+';
my $tailpat = '[-\w]+';
my %wildcards;
foreach $key (keys(%xmlfields)) {
    if (index($key, "*") >= 0) {
	my $regex = '^' . $key . '$';
	$regex =~ s/\*\$$/$tailpat/;
	$regex =~ s/\*/$wordpat/g;
	$wildcards{$key} = $regex;
    }
}
# Key ordering is lost in a hash.
# Put longer matching wildcard keys before their prefix.
my @wildkeys = reverse(sort(keys(%wildcards)));

253 254
foreach $key (keys(%{ $xmlparse->{'attribute'} })) {
    my $value = $xmlparse->{'attribute'}->{"$key"}->{'value'};
255 256 257
    if (!defined($value)) {	# Empty string comes from XML as an undef value.
	$xmlparse->{'attribute'}->{"$key"}->{'value'} = $value = "";
    }
258

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    print STDERR "User attribute: '$key' -> '$value'\n"
	if ($debug);

    my $field = $key;
    my $wild;
    if (!exists($xmlfields{$key})) {

	# Not a regular key; look for a wildcard regex match.
        foreach my $wildkey (@wildkeys) {
	    my $regex = $wildcards{$wildkey};
	    if ($wild = $key =~ /$regex/) {
		$field = $wildkey;
		print STDERR "Wildcard: '$key' matches '$wildkey'\n"
		    if ($debug);
		last; # foreach $wildkey
	    }
	}
	if (!$wild) {
Leigh Stoller's avatar
Leigh Stoller committed
277 278
	    # Silently ignore, and delete.
	    delete($xmlfields{$key});
279 280
	    next; # foreach $key
	}
281 282
    }

283
    my ($dbslot, $required, $default) = @{$xmlfields{$field}};
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307

    if ($required & $SLOT_REQUIRED) {
	# A slot that must be provided, so do not allow a null value.
	if (!defined($value)) {
	    $errors{$key} = "Must provide a non-null value";
	    next;
	}
    }
    if ($required & $SLOT_OPTIONAL) {
	# Optional slot. If value is null skip it. Might not be the correct
	# thing to do all the time?
	if (!defined($value)) {
	    next
		if (!defined($default));
	    $value = $default;
	}
    }
    if ($required & $SLOT_ADMINONLY) {
	# Admin implies optional, but thats probably not correct approach.
	$errors{$key} = "Administrators only"
	    if (! $this_user->IsAdmin());
    }
	
    # Now check that the value is legal.
308 309
    if (! TBcheck_dbslot($value, "images",
			 $dbslot, TBDB_CHECKDBSLOT_ERROR)) {
310 311 312 313
	$errors{$key} = TBFieldErrorString();
	next;
    }

314
    $editimageid_args{$key} = $value;
315 316 317 318 319 320 321 322
}
UserError()
    if (keys(%errors));

#
# Now do special checks.
#

323 324
my $image = OSImage->Lookup($editimageid_args{"imageid"},
			    $editimageid_args{"version"});
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 363 364 365 366 367 368
if (!defined($image)) {
    UserError("Image: No such image");
}
if (!$image->AccessCheck($this_user, TB_IMAGEID_MODIFYINFO())) {
    UserError("Image: Not enough permission");
}

#
# Description must not be blank.
#
if ((exists($editimageid_args{"description"}) ?
     $editimageid_args{"description"} eq "" :
     $image->description() eq "")) {
    UserError("Description: Missing Field");
}

#
# Path must not be blank.
#
if ((exists($editimageid_args{"path"}) ?
     $editimageid_args{"path"} eq "" :
     $image->path() eq "")) {
    UserError("Path: Missing Field");
}

# Admins can put an image wherever they want.
if (!$isadmin && exists($editimageid_args{"path"})) {
    my $pdef    = "";
    my $shared = $image->shared();
    my $pid    = $image->pid();
    my $gid    = $image->gid();
	
    if (!$shared && $gid ne $pid) {
	$pdef = "$TBGROUP_DIR/" . $pid . "/" . $gid . "/";
    }
    else {
	$pdef = "$TBPROJ_DIR/" . $pid . "/";
    }

    if (index($editimageid_args{"path"}, $pdef) < 0) {
	UserError("Path: Must reside in $pdef");
    }
}

369 370 371 372 373 374 375 376 377 378
if ($image->architecture() ||
    (exists($editimageid_args{"architecture"}) &&
     $editimageid_args{"architecture"} ne "")) {
    foreach my $arch (split(",", $editimageid_args{"architecture"})) {
	if (!exists($OSImage::IMAGE_ARCHITECTURES{$arch})) {
	    UserError("Architecture: Not a valid Architecture: $arch");
	}
    }
}
else {
379 380
#
# See what node types this image will work on. Must be at least one!
381 382 383
#
UserError("Node Types: Must have at least one node type")
    if ($#mtypes_array < 0);
384 385
my $typeclause = join(" or ", map("type='$_'", @mtypes_array));

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
# Check validity of mtype_* args, since the keys are dynamically generated.
my $node_types_selected = 0;
my @mtype_keys = grep(/^mtype_/, keys(%editimageid_args));
foreach $key (@mtype_keys) {
    my $value = $editimageid_args{$key};
    print STDERR "mtype: '$key' -> '$value'\n"
	if ($debug);

    my $type = $key;
    $type =~ s/^mtype_//;
    my $match = grep(/^${type}$/, @mtypes_array);
    if ($match == 0) {
	$errors{$key} = "Illegal node type."
    }
    elsif ($value eq "1") {
	$node_types_selected++;
    }
}
UserError("Node Types: Must select at least one node type")
    if ($node_types_selected == 0);

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
#
# Mereusers are not allowed to create more than one osid/imageid mapping
# for each machinetype. They cannot actually do that through the EZ form
# since the osid/imageid has to be unique, but it can happen by mixed
# use of the long form and the short form, or with multiple uses of the
# long form. 
#
my $osidclause;
for (my $i = 1; $i <= 4; $i++) {
    # Local variable dynamically created.    
    $foo = $image->field("part${i}_osid");

    if (defined($foo)) {
	$osidclause .= " or "
	    if (defined($osidclause));
	$osidclause .= "osid='$foo'";
    }
}
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
if (defined($osidclause)) {
    DBQueryFatal("lock tables images write, os_info write, osidtoimageid write");
    my $imageid = $image->imageid();
    my $query_result =
	DBQueryFatal("select osidtoimageid.*,images.pid,images.imagename ".
		     " from osidtoimageid ".
		     "left join images on ".
		     " images.imageid=osidtoimageid.imageid ".
		     "where ($osidclause) and ($typeclause) and ".
		     "      images.imageid!='$imageid'");
    DBQueryFatal("unlock tables");
    if ($query_result->numrows) {

	my $msg = 
	    "There are other image descriptors that specify the same OS".
	    "descriptors for the same node types.  There must be a unique".
	    "mapping of OS descriptor to Image descriptor for each node type!".
	    "Perhaps you need to delete one of the images below, or create a".
	    "new OS descriptor to use in this new Image descriptor.  \n\n";
	my $fmt = "%-10s %-15s %-15s %s\n";
	$msg .= sprintf($fmt, "Image", "OSID", "Type", "ImageID");
	$msg .= sprintf($fmt, "=====", "====", "====", "=======");
	while (my ($imageid, $osid, $type, $imagename) = 
	       $query_result->fetchrow_array()) {
	    $msg .= sprintf($fmt, $imageid, $osid, $type, $imagename);
	}
451

452 453
	UserError("Conflict: Please check the other Image descriptors".
		  " and make the necessary changes!\n $msg");
454 455
    }
}
456
}
457 458 459 460 461 462 463 464 465 466 467 468
exit(0)
    if ($verify);

#
# Now safe to edit image descriptor.
#
# We pass the imageid along as an argument to EditImageid(), so remove it from
# the argument array.
#
delete($editimageid_args{"imageid"});

my $usrerr;
469 470
my $editimageid_val = OSImage->EditImageid($image,
					   \%editimageid_args, \$usrerr);
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
UserError($usrerr)
    if (defined($usrerr));
fatal("Could not create new Image!")
    if (!defined($editimageid_val));

exit(0);

sub fatal($)
{
    my ($mesg) = @_;

    print STDERR "*** $0:\n".
	         "    $mesg\n";
    # Exit with negative status so web interface treats it as system error.
    exit(-1);
}

sub UserError(;$)
{
    my ($mesg) = @_;

    if (keys(%errors)) {
	foreach my $key (keys(%errors)) {
	    my $val = $errors{$key};
	    print "${key}: $val\n";
	}
    }
    print "$mesg\n"
	if (defined($mesg));

    # Exit with positive status so web interface treats it as user error.
    exit(1);
}

sub escapeshellarg($)
{
    my ($str) = @_;

    $str =~ s/[^[:alnum:]]/\\$&/g;
    return $str;
}