newscript.in 16.8 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2011-2017, 2019 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 30
use IO::Handle;
use URI::Escape;
31
use Cwd qw(realpath);
32 33 34 35 36 37

#
# Create a new node from a XML description. 
#
sub usage()
{
38
    print("Usage: newnode [-d] [-v] [-f] [xmlfile]\n\n");
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
    print("  -d  print debug information\n");
    print("  -v  verify permissions: do not execute commands\n");
    print("  -n  print out commands: do not execute commands\n");
    exit(-1);
}
my $optlist = "dvn";
my $debug   = 0;
my $verify  = 0;
my $fake    = 0;

#
# Configure variables
#
#my $TB		= "@prefix@";
my $TB = "/usr/testbed/";
54
my $GENIRACK    = @PROTOGENI_GENIRACK@;
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

#
# 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 "/usr/testbed/lib";
use libdb;
use libtestbed;
use User;
use Project;
75
use EmulabFeatures;
76
use Interface;
77 78 79 80 81

# Protos
sub fatal($);
sub UserError(;$);
sub PrintResult($);
Jonathon Duerig's avatar
Jonathon Duerig committed
82
sub ModifyRow($$);
83 84 85 86 87 88 89
sub RemoveRow($);
sub ResolveRow($);
sub CommitNode($);
sub CommitInterface($);
sub CommitWire;
sub CommitInterfaceType($);

90 91
my $useScriptFeature = $GENIRACK ||
    EmulabFeatures->FeatureEnabled("ScriptNewNodes", undef, undef, undef);
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

#
# 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 (defined($options{"n"})) {
    $fake = 1;
}
110
if (@ARGV > 1) {
111 112
    usage();
}
113 114 115 116
my $xmlfile;
if (scalar(@ARGV) >= 1) {
  $xmlfile = shift(@ARGV);
}
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

#
# 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 create new nodes")
	if (!$this_user->IsAdmin());
}
else {
    #
    # Check the filename when invoked from the web interface; must be a
    # file in /tmp.
    #
139 140 141 142 143 144 145
    if (defined($xmlfile)) {
	if ($xmlfile =~ /^([-\w\.\/]+)$/) {
	    $xmlfile = $1;
	}
	else {
	    fatal("Bad data in pathname: $xmlfile");
	}
146

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

    # 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 %nodefields =
    # XML Field Name        DB slot name         Flags             Default
    ("command"		=> ["command",		$SLOT_REQUIRED],
     "table"		=> ["table",		$SLOT_REQUIRED],
     "id"		=> ["new_node_id",	$SLOT_OPTIONAL,    undef],
     "node_id"		=> ["node_id",		$SLOT_OPTIONAL,    undef],
     "type"		=> ["type",		$SLOT_OPTIONAL,    undef],
     "IP"		=> ["IP",		$SLOT_OPTIONAL,    undef],
184
     "role"		=> ["role",		$SLOT_OPTIONAL,    undef],
185 186 187 188 189 190 191 192 193 194 195 196
     "identifier"      	=> ["identifier",      	$SLOT_OPTIONAL,	   undef]);

my %ifacefields =
    # XML Field Name        DB slot name         Flags             Default
    ("command"          => ["command",          $SLOT_REQUIRED],
     "table"		=> ["table",		$SLOT_REQUIRED],
     "id"		=> ["new_interface_id",	$SLOT_OPTIONAL,    undef],
     "node_id"          => ["new_node_id",      $SLOT_OPTIONAL,    undef],
     "card"             => ["card",             $SLOT_OPTIONAL,    undef],
     "port"             => ["port",             $SLOT_OPTIONAL,    undef],
     "mac"              => ["mac",              $SLOT_OPTIONAL,    undef],
     "type"             => ["interface_type",   $SLOT_OPTIONAL,    undef],
197
     "role"		=> ["role",		$SLOT_OPTIONAL,    undef],
198 199 200 201
     "IP"		=> ["IP",		$SLOT_OPTIONAL,    undef],
     "switch_id"	=> ["switch_id",	$SLOT_OPTIONAL,    undef],
     "switch_card"	=> ["switch_card",	$SLOT_OPTIONAL,    undef],
     "switch_port"	=> ["switch_port",	$SLOT_OPTIONAL,    undef]);
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 229 230 231 232 233 234

my %wirefields =
    # XML Field Name        DB slot name         Flags             Default
    ("command"          => ["command",          $SLOT_REQUIRED],
     "table"		=> ["table",		$SLOT_REQUIRED],
     "id"		=> ["new_wire_id",	$SLOT_OPTIONAL,    undef],
     "node_id1"        	=> ["node_id1",         $SLOT_OPTIONAL,    undef],
     "card1"      	=> ["card1",      	$SLOT_OPTIONAL,    undef],
     "port1"      	=> ["port1",      	$SLOT_OPTIONAL,    undef],
     "node_id2"        	=> ["node_id2",        	$SLOT_OPTIONAL,    undef],
     "card2"      	=> ["card2",      	$SLOT_OPTIONAL,    undef],
     "port2"      	=> ["port2",      	$SLOT_OPTIONAL,    undef],
     "cable"            => ["cable",            $SLOT_OPTIONAL,    undef],
     "len"              => ["len",              $SLOT_OPTIONAL,    undef],
     "type"             => ["type",             $SLOT_OPTIONAL,    undef]);

my %interfacetypefields =
    # XML Field Name        DB slot name         Flags             Default
    ("command"          => ["command",          $SLOT_REQUIRED],
     "table"		=> ["table",		$SLOT_REQUIRED],
     "id"		=> ["new_interface_type_id",	$SLOT_OPTIONAL,    ""],
     "type"		=> ["type",		$SLOT_OPTIONAL,    ""],
     "max_speed"       	=> ["max_speed",	$SLOT_OPTIONAL,    ""],
     "full_duplex"	=> ["full_duplex",	$SLOT_OPTIONAL,    ""],
     "manufacturer"	=> ["manufacturer",	$SLOT_OPTIONAL,    ""],
     "model"		=> ["model",		$SLOT_OPTIONAL,    ""],
     "ports"		=> ["ports",		$SLOT_OPTIONAL,    ""],
     "connector"	=> ["connector",	$SLOT_OPTIONAL,    ""],
    );

#
# Must wrap the parser in eval since it exits on error.
#
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
my $xmlparse;
if (defined($xmlfile)) {
  $xmlparse = eval { XMLin($xmlfile,
			   VarAttr => 'name',
			   ContentKey => '-content',
			   SuppressEmpty => undef); };
  fatal($@)
      if ($@);
} else {
    my $handle = new IO::Handle;
    $xmlparse = eval { XMLin($handle->fdopen(fileno(STDIN),"r"),
			     VarAttr => 'name',
			     ContentKey => '-content',
			     SuppressEmpty => undef); };
  fatal($@)
      if ($@);
}
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 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 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 383 384 385 386 387 388 389 390 391 392 393 394 395 396

#
# 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 = ();
my %xmlfields;
my $table;
my $tableid;
my $tabledb;

if (exists($xmlparse->{'attribute'}->{"table"}->{"value"})) {
    $table = $xmlparse->{'attribute'}->{"table"}->{"value"};
} else {
    $errors{"table"} = "Required value not provide";
}
UserError()
    if (keys(%errors));

my $commit;

if ($table eq "node") {
    %xmlfields = %nodefields;
    $commit = \&CommitNode;
    $tableid = "new_node_id";
    $tabledb = "new_nodes";
} elsif ($table eq "interface") {
    %xmlfields = %ifacefields;
    $commit = \&CommitInterface;
    $tableid = "new_interface_id";
    $tabledb = "new_interfaces";
} elsif ($table eq "wire") {
    %xmlfields = %wirefields;
    $commit = \&CommitWire;
    $tableid = "new_wire_id";
    $tabledb = "new_wires";
} elsif ($table eq "interface_type") {
    %xmlfields = %interfacetypefields;
    $commit = \&CommitInterfaceType;
    $tableid = "new_interface_type_id";
    $tabledb = "new_interface_types";
} else {
    $errors{"table"} = "Table value not valid";
}
UserError()
    if (keys(%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 the database as we check
# the attributes.
#
my %args = ();

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

    print STDERR "User attribute: '$key' -> '$value'\n"
	if ($debug);

    my $field = $key;
    if (!exists($xmlfields{$key})) {
	$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());
    }

    $args{$dbslot} = $value;

    # Now check that the value is legal.

# TODO: Exempt command and table
#    if (! TBcheck_dbslot($value, "new_nodes",
#			 $dbslot, TBDB_CHECKDBSLOT_ERROR)) {
#	$errors{$key} = TBFieldErrorString();
#	next;
#    }
}
UserError()
    if (keys(%errors));

my $id = $args{$tableid};
if (! defined($id) && $args{"command"} ne "list"
    && $args{"command"} ne "add") {
    $errors{"id"} = "Command " . $args{"command"} . " must have an id";
}
if ($args{"command"} eq "add") {
} elsif ($args{"command"} eq "update") {
} elsif ($args{"command"} eq "rollback") {
} elsif ($args{"command"} eq "commit") {
} elsif ($args{"command"} eq "resolve") {
} elsif ($args{"command"} eq "list") {
} else {
    $errors{"command"} = "Command must be add, update, rollback, commit, ".
	"resolve, or list";
}
UserError()
    if (keys(%errors));

exit(0)
    if ($verify);

my $rowlist;
if ($args{"command"} eq "add") {
Jonathon Duerig's avatar
Jonathon Duerig committed
397
    ModifyRow($id, 0);
398
} elsif ($args{"command"} eq "update") {
Jonathon Duerig's avatar
Jonathon Duerig committed
399
    ModifyRow($id, 1);
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 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 451
} elsif ($args{"command"} eq "rollback") {
    RemoveRow($id);
} elsif ($args{"command"} eq "commit") {
    &$commit($id);
} elsif ($args{"command"} eq "resolve") {
    $rowlist = ResolveRow($id);
    PrintResult($rowlist);
} elsif ($args{"command"} eq "list") {
    $rowlist = ResolveRow(undef);
    PrintResult($rowlist);
}
UserError()
    if (keys(%errors));

print "Completed ".$args{"command"}." on table $table\n";

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 PrintResult($)
{
    my ($result) = @_;
    my @current;
    while (@current = $result->fetchrow()) {
	for (my $i = 0; $i < scalar(@current); ++$i) {
	    if (! defined($current[$i])) {
452
		$current[$i] = "NULL";
453
	    }
454
	    $current[$i] = uri_escape($current[$i]);
455 456 457 458 459
	}
	print join(" ", @current)."\n";
    }
}

Jonathon Duerig's avatar
Jonathon Duerig committed
460
sub ModifyRow($$)
461
{
Jonathon Duerig's avatar
Jonathon Duerig committed
462
    my ($id, $isupdate) = @_;
463
    my $query;
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479

    # XXX
    if ($useScriptFeature && $tabledb eq "new_interfaces") {
	foreach my $key (keys(%args)) {
	    if ($key =~ /^switch/ && defined($args{$key})) {
		$errors{$tableid} =
		    "Should add to wires table to set switch info";
		return;
	    }
	}
    } elsif (!$useScriptFeature && $tabledb eq "new_wires") {
	$errors{$tableid} =
	    "Should add to interfaces table to set switch info";
	return;
    }

480
    my $none_changed = 1;
Jonathon Duerig's avatar
Jonathon Duerig committed
481
    if ($isupdate) {
482 483 484 485 486 487 488
	$query = "UPDATE";
    } else {
	$query = "INSERT";
    }
    $query .= " $tabledb SET";
    foreach $key (keys(%args)) {
	my $value = $args{$key};
Jonathon Duerig's avatar
Jonathon Duerig committed
489 490
	if ($key ne "table" && $key ne "command"
	    && (! $isupdate || $key ne $tableid)
491 492 493 494 495 496 497 498 499
	    && defined($value)) {
	    if ($query ne "UPDATE $tabledb SET"
		&& $query ne "INSERT $tabledb SET") {
		$query .= ",";
	    }
	    $query .= " $key='$value'";
	    $none_changed = 0;
	}
    }
Jonathon Duerig's avatar
Jonathon Duerig committed
500
    if ($isupdate) {
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 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 570 571 572 573 574 575 576 577 578 579 580
	$query .= " WHERE $tableid='$id'";
    }
    if ($none_changed == 1) {
	$errors{$tableid} = "At least one field must be specified to update ".
	    "or add";
    } else {
	if ($fake) {
	    print $query."\n";
	} else {
	    DBQueryFatal($query);
	}
    }
}

sub RemoveRow($)
{
    my ($id) = @_;
    my $query = "DELETE FROM $tabledb WHERE $tableid='$id'";
    if ($fake) {
	print $query."\n";
    } else {
	DBQueryFatal($query);
    }
}

sub ResolveRow($)
{
    my ($id) = @_;
    my $query = "SELECT ";
    if ($table eq "node") {
	$query .= 
	    "new_node_id, node_id, type, IP, " .
	    "DATE_FORMAT(created,'%M %e %H:%i:%s') as created, dmesg, " .
	    "identifier, building";
    } elsif ($table eq "interface") {
	$query .= "new_interface_id, new_node_id, card, port, mac, interface_type";
    } elsif ($table eq "wire") {
	$query .= "new_wire_id, cable, len, type, node_id1, card1, port1, " .
	    "node_id2, card2, port2";
    } elsif ($table eq "interface_type") {
	$query .= "new_interface_type_id, type, max_speed, full_duplex, " .
	    "manufacturer, model, ports, connector";
    } else {
	$query .= " *";
    }
    $query .= " FROM $tabledb";
    if (defined($id)) {
	$query .= " WHERE $tableid='$id'";
    } else {
	$query .= " ORDER BY $tableid";
    }
    if ($fake) {
	print $query."\n";
    }
    return DBQueryFatal($query);
}


sub CommitNode($)
{
    my ($id) = @_;
    my $result = ResolveRow($id);
    while (my ($skip, $nodeid) = $result->fetchrow()) {
	my $command = "$TB/sbin/newnode -f $nodeid";
	if ($fake) {
	    print $command."\n";
	} else {
	    system($command);
	}
    }
}

sub CommitInterface($)
{
    $errors{"command"} = "Interfaces cannot be committed individually. ".
	"Commit the node that they belong to.";
}

sub CommitWire
{
581 582 583 584 585
    if (!$useScriptFeature) {
	$errors{"command"} = "Wires cannot be committed individually. ".
	    "Commit the node that they belong to.";
	return;
    }
586 587 588 589
    my ($id) = @_;
    my $result = ResolveRow($id);
    while (my ($skip, $cable, $len, $type, $node_id1, $card1, $port1,
	       $node_id2, $card2, $port2) = $result->fetchrow()) {
590 591 592 593
	my $iface1 = "eth${card1}";
	my $iface2 = "${card2}/${port2}";
	    
	my $interface1 = Interface->LookupByIface($node_id1, $iface1);
594 595 596
	if (!defined($interface1)) {
	    $errors{"command"} = "Cannot lookup interface1";
	    return;
597
	}
598
	my $interface2 = Interface->LookupByIface($node_id2, $iface2);
599 600 601 602
	if (!defined($interface2)) {
	    $errors{"command"} = "Cannot lookup interface2";
	    return;
	}
603 604 605 606 607 608
	my $wireargs = {
	    "card1" => $card1,
	    "port1" => $port1,
	    "card2" => $card2,
	    "port2" => $port2,
	};
609 610
	$wireargs->{"cable"}  = $cable if (defined($cable));
	$wireargs->{"length"} = $len if (defined($len));
611
	if ($fake) {
612 613 614 615 616 617 618 619 620
	    print "wire: $interface1, $interface2\n";
	}
	else {
	    my $wire = Interface::Wire->Create($interface1, $interface2,
					       $type, $wireargs);
	    if (!defined($wire)) {
		$errors{"command"} = "Could not create wire.";
		return;
	    }
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
	}
    }
    RemoveRow($id);
}

sub CommitInterfaceType($)
{
    my ($id) = @_;
    my $result= ResolveRow($id);
    while (my ($skip, $type, $max_speed, $full_duplex, $manufacturer, $model,
	       $ports, $connector) = $result->fetchrow()) {
	my $query = "INSERT interface_types SET ".
	    "type='$type', max_speed='$max_speed', full_duplex='$full_duplex', ".
	    "manufacturer='$manufacturer', model='$model', ports='$ports', ".
	    "connector='$connector'";
	if ($fake) {
	    print $query."\n";
	} else {
	    DBQueryFatal($query);
	}
    }
    RemoveRow($id);
}