editnodetype.in 17.8 KB
Newer Older
1 2 3
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2012 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 134 135 136 137 138 139 140 141 142
# All rights reserved.
#
use English;
use strict;
use Getopt::Std;
use XML::Simple;
use Data::Dumper;

#
# Back-end script to create or edit a nodetype.
#
sub usage()
{
    print("Usage: editnodetype [-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@";

#
# 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;
use OSinfo;

# 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!");
    }
    fatal("You must have admin privledges to ...")
	if (!$this_user->IsAdmin());
}
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.
    my $translated = `realpath $xmlfile`;
    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!");
    }
}

#
# 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
    ("node_type"	=> ["node_type",	$SLOT_REQUIRED],

     # Presence of new_type commands creation of a new nodetype.
     "new_type"		=> ["attr_boolean",	$SLOT_OPTIONAL],

     # Class may only be changed while making a new class. 
     "class"		=> ["class",		$SLOT_OPTIONAL],

     # Fixed attributes.
143 144 145 146 147 148 149
     "isvirtnode"	=> ["isvirtnode",	$SLOT_OPTIONAL],
     "isjailed"		=> ["isjailed",		$SLOT_OPTIONAL],
     "isdynamic"	=> ["isdynamic",	$SLOT_OPTIONAL],
     "isremotenode"	=> ["isremotenode",	$SLOT_OPTIONAL],
     "issubnode"	=> ["issubnode",	$SLOT_OPTIONAL],
     "isplabdslice"	=> ["isplabdslice",	$SLOT_OPTIONAL],
     "issimnode"	=> ["issimnode",	$SLOT_OPTIONAL],
150 151
     "isgeninode"	=> ["isgeninode",	$SLOT_OPTIONAL],
     "isfednode"	=> ["isfednode",	$SLOT_OPTIONAL],
152
     "isswitch"		=> ["isswitch",		$SLOT_OPTIONAL],
153 154 155

     # Dynamic attributes with wildcards.
     "attr_boolean_*"	=> ["attr_boolean",	$SLOT_OPTIONAL],
156
     "attr_integer_*"	=> ["attr_integer",	$SLOT_OPTIONAL],
157 158 159
     "attr_float_*"	=> ["attr_float",	$SLOT_OPTIONAL],
     "attr_string_*"	=> ["attr_string",	$SLOT_OPTIONAL],

160 161 162
     # OS and Image ID's, referenced by their integer index.
     "attr_integer_*_osid"   => ["attr_osid",	$SLOT_OPTIONAL],
     "attr_integer_*_imageid"=> ["attr_imageid",$SLOT_OPTIONAL],
163

164 165 166 167
     # OS and Image ID's, referenced by their pid,name 
     "attr_string_*_osid"   => ["attr_string",	$SLOT_OPTIONAL],
     "attr_string_*_imageid"=> ["attr_string", $SLOT_OPTIONAL],

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
     # The name of a single attribute to add to the list.
     "new_attr"		=> ["attr_name",	$SLOT_OPTIONAL],
     # Multiple attributes can be deleted from the list.
     "delete_*"		=> ["attr_boolean",	$SLOT_OPTIONAL]);

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

#
Russ Fish's avatar
Russ Fish committed
205
# We build up an array of arguments to reference as we check
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
# the attributes.
#
my %editnodetype_args = ();

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

foreach $key (keys(%{ $xmlparse->{'attribute'} })) {
    my $value = $xmlparse->{'attribute'}->{"$key"}->{'value'};
236 237 238
    if (!defined($value)) {	# Empty string comes from XML as an undef value.
	$xmlparse->{'attribute'}->{"$key"}->{'value'} = $value = "";
    }
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

    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) {
	    $errors{$key} = "Unknown attribute";
	    next; # foreach $key
	}
    }

    my ($dbslot, $required, $default) = @{$xmlfields{$field}};

    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.
288 289
    if (! TBcheck_dbslot($value, "node_types",
			 $dbslot, TBDB_CHECKDBSLOT_ERROR)) {
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 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
	$errors{$key} = TBFieldErrorString();
	next;
    }

    $editnodetype_args{$key} = $value;
}
UserError()
    if (keys(%errors));

#
# Now do special checks.
#
my $query_result;
my $node_type = $editnodetype_args{'node_type'};
my $new_type = exists($editnodetype_args{"new_type"});

#
# Check whether the node type already exists.
#
$query_result =
    DBQueryFatal("select * from node_types where type='$node_type'");
my $node_type_exists = $query_result->numrows;
my $prev_nodetype_data;
if ($new_type) {

    # Found.  But it's supposed to be new.
    UserError("New NodeType: $node_type is already used!")
	if ($node_type_exists);
}
else {
    # Not found, but it was supposed to be old.
    UserError("NodeType: $node_type is not a valid nodetype!")
	if (!$node_type_exists);

    # Found an existing one, grab its data.
    $prev_nodetype_data = $query_result->fetchrow_hashref();
}

#
# Check attributes of the node type, building an insert list as we go.
#
my @nodetype_data;

# First check fixed (non-attr*) attributes that are in the node_types table.
# Class may only be set while making a new nodetype.
my $class;
if (exists($editnodetype_args{"class"})) {
    my $newclass = $editnodetype_args{"class"};
    if ($new_type) {
	$class = $newclass;
	if ($class eq "") {
	    $class = "pc";	# Default to pc class.
	}
	push(@nodetype_data, "class='$class'");
    }
    else {
	$class = $prev_nodetype_data->{"class"};

	# It's okay to specify it to be the same as it was before.
	UserError("NodeType: Can't change class ($class) of existing node.")
	    if ($class ne $newclass);
    }
}

# The rest of them all have names starting with "is" at present.
my @fixed_args   = grep(/^is/, keys(%editnodetype_args));
foreach my $name (@fixed_args) {
    if (exists($editnodetype_args{$name})) {
	my $value = $editnodetype_args{$name};
	push(@nodetype_data, "$name='$value'");
    }
}
# Needed below.
my $isremotenode = exists($editnodetype_args{"isremotenode"}) ?
    $editnodetype_args{"isremotenode"} : 
    $prev_nodetype_data->{"isremotenode"};

# Get previous dynamic attrs from the node_type_attributes table.
$query_result =
    DBQueryFatal("select * from node_type_attributes ".
		 "where type='$node_type'");
my $prev_attrs = $query_result->fetchall_hashref("attrkey");

# Dynamic attributes to be changed or deleted.  Possibly one new one added.
my $new_attr_name = "";
if (my $new_attr = exists($editnodetype_args{'new_attr'})) {
    $new_attr_name = $editnodetype_args{'new_attr'};

    # The new attr must not already exist.
    UserError("New NodeType Attr: $new_attr_name is already used!")
	if (exists($prev_attrs->{$new_attr_name}));
}

383 384 385 386 387 388
my %osids     = ();
my %mfsosids  = ();
my %osidmap   = ();
my %imageids  = ();
my %imagemap  = ();

389 390 391 392 393
# Get lists of ids for checking the special "attr_*_*id" attributes.
$query_result =
    DBQueryFatal("select osid,osname,pid from os_info ".
		 "where (path='' or path is NULL) ".
		 "order by pid,osname");
394 395 396 397 398
while (my ($osid,$osname,$pid) = $query_result->fetchrow_array()) {
    $osids{$osid} = "$pid,$osname";
    $osidmap{"$pid,$osname"} = $osid;
}
    
399 400 401 402
$query_result =
    DBQueryFatal("select osid,osname,pid from os_info ".
		 "where (path is not NULL and path!='') ".
		 "order by pid,osname");
403 404 405 406 407
while (my ($osid,$osname,$pid) = $query_result->fetchrow_array()) {
    $mfsosids{$osid} = "$pid,$osname";
    $osidmap{"$pid,$osname"} = $osid;
}

408 409 410
$query_result =
    DBQueryFatal("select imageid,imagename,pid from images ".
		 "order by pid,imagename");
411 412 413 414
while (my ($imageid,$imagename,$pid) = $query_result->fetchrow_array()) {
    $imageids{$imageid} = "$pid,$imagename";
    $imagemap{"$pid,$imagename"} = $imageid;
}
415 416 417 418 419 420 421 422 423 424

# Separate out the attr types and names from the other argument keys.
my ($attr_name, $attr_type, $attr_value);
my (@attr_names, %attr_types, %attr_values, %attr_dels);
foreach my $argkey (keys(%editnodetype_args)) {
    next
	if (!($argkey =~ /^attr_/));

    $attr_name = $attr_type = $argkey;
    $attr_name =~ s/^attr_${wordpat}_(.*)$/$1/;
425 426 427 428 429
    if ($argkey =~ /_default_imageid$/) {
	# hack, now a comma seperated list, assume valid
	$attr_type = "imageids";
    } 
    elsif ($argkey =~ /_(osid|imageid)$/) {
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
	# Special case: the type is the LAST part of the name for ID attrs.
	$attr_type = $1;
    }
    else {
	# Normal ones are like "attr_type_name".
	$attr_type =~ s/^attr_($wordpat)_.*$/$1/;
    }
    $attr_value = $editnodetype_args{$argkey};

    if ($debug) {
	print STDERR "Dynamic attr: $attr_name($attr_type) = '$attr_value'\n";
    }

    push(@attr_names, $attr_name);
    $attr_types{$attr_name} = $attr_type;
    $attr_values{$attr_name} = $attr_value;
}

# Check all of the dynamic attrs that are to be set.
foreach $attr_name (@attr_names) {
    
    # Skip checks on attrs that are scheduled for deletion anyway.
    my $del = $attr_dels{$attr_name} = 
	exists($editnodetype_args{"delete_${attr_name}"}) &&
	    $editnodetype_args{"delete_${attr_name}"} eq "1";
    next
	if $del;

458 459
    # An attr to be set must pre-exist, unless it's the one new attr.
    # (And of course, the attrs of a new_type are *all* new attrs.)
460
    UserError("NodeType Attr: $attr_name is not set in nodetype $node_type!")
461 462
	if (!$new_type && 
	    !exists($prev_attrs->{$attr_name}) && 
463 464 465 466 467 468 469 470
	    $attr_name ne $new_attr_name);

    $attr_type = $attr_types{$attr_name};
    $attr_value = $attr_values{$attr_name};

    # Check the osid and imageid attribute values against the id lists.
    # Under the web page interface, these come to us from selectors.
    if ($attr_type eq "osid") {
471 472 473 474 475 476 477 478 479 480 481 482 483 484
	if ($attr_value =~ /^([^,]+),([^,]+)$/) {
	    if (!exists($osidmap{"$1,$2"})) {
		UserError("NodeType OSID Attr: $attr_name is not an osid.")
	    }
	    my $new_attr_value = $osidmap{"$1,$2"};
	    print STDERR "Mapping $attr_name: $attr_value -> $new_attr_value\n"
		if ($debug);
	    
	    $attr_value = $new_attr_value;
	    $attr_values{$attr_name} = $attr_value;
	}
	elsif (! ($attr_value =~ /^(\d*)$/)) {
	    UserError("Invalid osid value for $attr_name");
	}
485
	if ($attr_name =~ /mfs/) {
486
	    UserError("NodeType MFS OSID Attr: $attr_name is not an mfs_osid.")
487
		if (!exists($mfsosids{$attr_value}));
488 489 490
	}
	else {
	    UserError("NodeType OSID Attr: $attr_name is not an osid.")
491
		if (!exists($osids{$attr_value}));
492
	}
493
	$attr_types{$attr_name} = "integer"; # An idx is an integer attr.
494 495
    }
    elsif ($attr_type eq "imageid") {
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
	if ($attr_value =~ /^([^,]+),([^,]+)$/) {
	    if (!exists($imagemap{"$1,$2"})) {
		UserError("NodeType Image ID Attr: $attr_name is not an imageid.")
	    }
	    my $new_attr_value = $imagemap{"$1,$2"};
	    print STDERR "Mapping $attr_name: $attr_value -> $new_attr_value\n"
		if ($debug);

	    $attr_value = $new_attr_value;
	    $attr_values{$attr_name} = $attr_value;
	}
	elsif (! ($attr_value =~ /^(\d*)$/)) {
	    UserError("Invalid image id value for $attr_name");
	}
	
511
	UserError("NodeType Image ID Attr: $attr_name is not an imageid.")
512
	    if (!exists($imageids{$attr_value}));
513
	$attr_types{$attr_name} = "integer"; # An idx is an integer attr.
514
    }
515
    elsif ($attr_type eq "imageids") {
516 517
	my @newvals = ();
	    
518
	foreach my $k (split /,/, $attr_value) {
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
	    if ($k =~ /^([^:]+):([^:]+)$/) {
		if (!exists($imagemap{"$1,$2"})) {
		    UserError("NodeType Image ID Attr: $attr_name is not an imageid.")
		}
		my $new_k = $imagemap{"$1,$2"};
		print STDERR "Mapping $attr_name: $attr_value -> $new_k\n"
		    if ($debug);
		$k = $new_k;
	    }
	    elsif (! ($k =~ /^(\d*)$/)) {
		UserError("Invalid image id value for $attr_name");
	    }
	    push(@newvals, $k);
	    
	    UserError("NodeType Image ID Attr: ".
		      "$attr_name contains an invalid imageid.")
		if (!exists($imageids{$k}));
536
	}
537
	$attr_values{$attr_name} = join(",", @newvals);
538 539
	$attr_types{$attr_name} = "string"; # really a comma seperated list
    }
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 570 571 572 573 574 575 576 577 578
}

exit(0)
    if ($verify);

#
# Now safe to put the nodetype info into the DB.
#
my ($type, $value);
if ($new_type) {
    DBQueryFatal("insert into node_types set type='$node_type', ".
		 join(",", @nodetype_data));

    if ($class eq "pc" || $isremotenode eq "1") {
	my $vnode_type = $node_type;
	$vnode_type =~ s/pc/pcvm/;
	if ($vnode_type eq $node_type) {
	    $vnode_type = "$vnode_type-vm";
	}
	my $pcvmtype = ($isremotenode eq "1" ? "pcvwa" : "pcvm");

	DBQueryFatal("insert into node_types_auxtypes set " .
		     "  auxtype='$vnode_type', type='$pcvmtype'");
    }

    foreach $attr_name (@attr_names) {
	# Skip adding an attr if it is also scheduled for deletion.
	next
	    if ($attr_dels{$attr_name});

	$key   = escapeshellarg($attr_name);
	$type  = escapeshellarg($attr_types{$attr_name});
	$value = escapeshellarg($attr_values{$attr_name});

	DBQueryFatal("insert into node_type_attributes set ".
		     "   type='$node_type', ".
		     "   attrkey='$key', attrtype='$type', ".
		     "   attrvalue='$value' ");
    }
Leigh Stoller's avatar
Leigh Stoller committed
579 580 581 582 583

    # And a group policy that prevents new type from being used.
    DBQueryFatal("replace into group_policies ".
		 "(pid_idx, gid_idx, pid, gid, policy, auxdata, count) ".
		 "values (0, 0, '-', '-', 'type', '$type', 0)");
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 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
}
else {
    DBQueryFatal("update node_types set ".
		 join(",", @nodetype_data) . " ".
		 "where type='$node_type'");

    foreach $attr_name (@attr_names) {
	$key   = escapeshellarg($attr_name);
	$type  = escapeshellarg($attr_types{$attr_name});
	$value = escapeshellarg($attr_values{$attr_name});

	# Remove an attr from the DB if scheduled for deletion.
	if ($attr_dels{$attr_name}) {
	    DBQueryFatal("delete from node_type_attributes ".
			 "where type='$node_type' and attrkey='$key'");
	}
	else {
	    DBQueryFatal("replace into node_type_attributes set ".
			 "   type='$node_type', ".
			 "   attrkey='$key', attrtype='$type', ".
			 "   attrvalue='$value' ");
	}
    }
}

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