manageremote.in 16.9 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
Leigh Stoller's avatar
Leigh Stoller committed
3
# Copyright (c) 2010-2016 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 23 24 25 26 27 28
# 
# {{{GENIPUBLIC-LICENSE
# 
# GENI Public License
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
# 
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
# 
# }}}
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#
use strict;
use English;
use Getopt::Std;
use Data::Dumper;
use CGI;

#
#
#
sub usage()
{
    print "Usage: manageremote version <remote>\n";
    print "       manageremote addpeer <remote> <urn> <url> [is_primary]\n";
    print "       manageremote adduser <remote> <uid>\n";
    print "       manageremote deluser <remote> <uid>\n";
    print "       manageremote moduser <remote> <uid>\n";
    print "       manageremote setgroups <remote> <uid>\n";
    print "       manageremote xlogin <remote> <uid>\n";
    print "       manageremote addproject <remote> <pid>\n";
    print "       manageremote addgroup <remote> <gid>\n";
    exit(1);
}
52
my $optlist    = "dnfp";
53 54 55
my $debug      = 0;
my $force      = 0;
my $impotent   = 0;
56 57
my $locked     = 0;
my $fromdaemon = 0;
58 59 60 61 62 63 64 65 66

#
# Function prototypes
#
sub Version();
sub AddUser(;$);
sub AddPeer();
sub DeleteUser();
sub ModifyUser();
Leigh Stoller's avatar
Leigh Stoller committed
67
sub SetGroups(;$);
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
sub CrossLogin();
sub AddProject();
sub AddGroup();
sub fatal($);
sub do_method($$;$);

#
# Configure variables
#
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
my $TBLOGS        = "@TBLOGSEMAIL@";
my $PGENISUPPORT  = @PROTOGENI_SUPPORT@;
my $PORTAL_ENABLE = @PORTAL_ENABLE@;
my $PORTAL_PRIMARY= @PORTAL_ISPRIMARY@;
my $OURDOMAIN     = "@OURDOMAIN@";
my $DUMPUSER	  = "$TB/sbin/dumpuser";
my $DUMPPROJ	  = "$TB/sbin/dumpproject";
my $SACERT	  = "$TB/etc/genisa.pem";

# un-taint path
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/usr/site/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Turn off line buffering on output
#
$| = 1;

use lib '@prefix@/lib';
use emdb;
use libtestbed;
use User;
use Project;
use Group;
use emutil;
use GeniHRN;
use Genixmlrpc;
use GeniResponse;
use GeniCredential;
use GeniAuthority;

#
# Check args.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"f"})) {
    $force = 1;
}
if (defined($options{"n"})) {
    $impotent = 1;
}
126 127 128
if (defined($options{"p"})) {
    $fromdaemon = 1;
}
129
usage()
130
    if (@ARGV < 2 || @ARGV > 5);
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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177

my $cmd      = shift(@ARGV);
my $peername = shift(@ARGV);
my $peerurn;

if (! $PORTAL_ENABLE) {
    fatal("Portal mode is not enabled");
}
if (! ($PORTAL_PRIMARY || $cmd eq "addpeer")) {
    fatal("You can only run addpeer on this boss");
}

#
# Map invoking user to object. 
#
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    fatal("You ($UID) do not exist!");
}
#
# Mere users can call only one function.
#
if (!$this_user->IsAdmin() && $cmd ne "xlogin") {
    fatal("You must be a TB administrator to run this script!");
}

#
# Load the SA cert to act as caller context.
#
my $certificate = GeniCertificate->LoadFromFile($SACERT);
if (!defined($certificate)) {
    fatal("Could not load certificate from $SACERT\n");
}
my $context = Genixmlrpc->Context($certificate);
if (!defined($context)) {
    fatal("Could not create context to talk to clearinghouse");
}
Genixmlrpc->SetContext($context);

my $me      = GeniAuthority->Lookup($certificate->uuid());
if (!defined($me)) {
    fatal("Could not find my own authority object");
}
my $credential = GeniCredential->GetSelfCredential($me);
if (!defined($credential)) {
    fatal("Could not create self credential for $me");
}
178
my $authority;
179 180 181 182 183

#
# All operations other then AddPeer require that the peer be
# in the DB.
#
184
if ($cmd ne "addpeer") {
185 186 187 188 189 190
    my $query_result =
	DBQueryFatal("select name,urn from emulab_peers ".
		     "where name='$peername' or urn='$peername'");
    fatal("Unknown peer")
	if (!$query_result->numrows);
    ($peername,$peerurn) = $query_result->fetchrow_array();
191 192 193 194 195

    $authority = GeniAuthority->CreateFromRegistry("sa", $peerurn);
    if (!defined($authority)) {
	fatal("Could not locate authority for $peername");
    }
196
}
197 198 199 200 201 202 203 204 205 206 207

#
# All operations other then xlogin require locking to avoid a
# race with the portal_daemon. 
#
if ($cmd ne "xlogin" && !$fromdaemon) {
    while (TBScriptLock("portal_op", 0, 5) != TBSCRIPTLOCK_OKAY()) {
	print "Could not get the lock; trying again ... ^C to stop trying.\n";
	next;
    }
    $locked = 1;
208 209 210 211 212 213 214 215 216 217 218 219 220 221
}

#
# Now dispatch operation.
#
SWITCH: for ($cmd) {
    /^version$/ && do {
	Version();
	last SWITCH;
    };
    /^adduser$/ && do {
	AddUser();
	last SWITCH;
    };
222 223 224 225
    /^addpeer$/ && do {
	AddPeer();
	last SWITCH;
    };
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
    /^deluser$/ && do {
	DeleteUser();
	last SWITCH;
    };
    /^moduser$/ && do {
	ModifyUser();
	last SWITCH;
    };
    /^setgroups$/ && do {
	SetGroups();
	last SWITCH;
    };
    /^xlogin$/ && do {
	CrossLogin();
	last SWITCH;
    };
    /^addproject$/ && do {
	AddProject();
	last SWITCH;
    };
    /^addgroup$/ && do {
	AddGroup();
	last SWITCH;
    };
    
    # Default
252 253
    TBScriptUnlock()
	if ($locked);
254 255
    usage();
}
256 257
TBScriptUnlock()
    if ($locked);
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
exit(0);

#
# Get the version. 
#
sub Version()
{
    my $response = do_method($authority, "GetVersion");
    fatal("Could not get version from $authority")
	if (! (defined($response) &&
	       $response->code() == GENIRESPONSE_SUCCESS));

    my $version = $response->value();
    print "Version: $version\n";
    return 0;
}

#
# Add a peer to the list
#
sub AddPeer()
{
    usage()
	if (@ARGV < 2);
    
    my $urn  = shift(@ARGV);
    my $url  = shift(@ARGV);
    my $primary  = (@ARGV ? shift(@ARGV) : 0);
    my $safe_url = DBQuoteSpecial($url);
    $primary = ($primary ? 1 : 0);

    fatal("Invalid URN")
	if (!GeniHRN::IsValid($urn));
    fatal("Invalid peer name")
	if (! ($peername =~ /^[-\w]*$/));

    my $authority = GeniAuthority->CreateFromRegistry("sa", $urn);
    if (!defined($authority)) {
	fatal("Could not locate authority for $peername");
    }
    
    my $query_result =
	DBQueryFatal("select * from emulab_peers ".
		     "where name='$peername' or urn='$urn' or ".
		     "      weburl=$safe_url");
    fatal("Peer already exists. Please delete first")
	if ($query_result->numrows);

    fatal("Could not add new peer")
	if (!DBQueryWarn("insert into emulab_peers set ".
			 "  name='$peername', urn='$urn', weburl=$safe_url, ".
			 "  is_primary='$primary'"));
    return 0;
}

#
# Add a user.
#
sub AddUser(;$)
{
    my ($token) = @_;

    if (! defined($token)) {
	usage()
	    if (! @ARGV);
	$token = $ARGV[0];
    }
    my $user = User->Lookup($token);
    if (!defined($user)) {
	fatal("No such user");
    }
    my $uid_idx = $user->uid_idx();
    my $uid     = $user->uid();

    # Check for existing export.
    my $query_result =
	DBQueryFatal("select * from user_exports ".
		     "where uid_idx='$uid_idx' and peer='$peername'");
    if ($query_result->numrows && !$force) {
	fatal("User already exported to peer. Use -f option");
    }
    my $urn = GeniHRN::Generate($OURDOMAIN, "user", $user->uid());
    
341
    my $xmlgoo = emutil::ExecQuiet("$DUMPUSER $uid");
342
    if ($?) {
Leigh Stoller's avatar
Leigh Stoller committed
343
	print STDERR "$xmlgoo";
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 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
	fatal("$DUMPUSER failed");
    }
    my $args = {"xmlstring" => $xmlgoo,
		"urn"       => $urn};
    
    my $response = do_method($authority, "AddUser", $args);
    fatal("Could not add user to $authority")
	if (! (defined($response) &&
	       ($response->code() == GENIRESPONSE_SUCCESS ||
		$response->code() == GENIRESPONSE_ALREADYEXISTS)));

    DBQueryFatal("replace into user_exports set ".
		 "  uid='$uid', uid_idx='$uid_idx', peer='$peername', ".
		 "  exported=now()");
    
    return 0;
}

#
# Delete a user.
#
sub DeleteUser()
{
    usage()
	if (! @ARGV);
    
    my $user = User->Lookup($ARGV[0]);
    if (!defined($user)) {
	fatal("No such user");
    }
    my $uid     = $user->uid(); 
    my $uid_idx = $user->uid_idx();
    
    my $query_result =
	DBQueryFatal("select * from user_exports ".
		     "where uid_idx='$uid_idx' and peer='$peername'");
    if (!$query_result->numrows && !$force) {
	fatal("User has not been exported to peer. Use -f option");
    }
    my $urn = GeniHRN::Generate($OURDOMAIN, "user", $user->uid());
    my $args = {"urn" => $urn};
    
    my $response = do_method($authority, "DeleteUser", $args);
    fatal("Could not delete user from $authority")
	if (! (defined($response) &&
	       ($response->code() == GENIRESPONSE_SUCCESS ||
		$response->code() == GENIRESPONSE_SEARCHFAILED)));

    DBQueryFatal("delete from user_exports ".
		 "where uid_idx='$uid_idx' and peer='$peername'");
    return 0;
}

#
# Modify a user.
#
sub ModifyUser()
{
    usage()
	if (! @ARGV);
    
    my $user = User->Lookup($ARGV[0]);
    if (!defined($user)) {
	fatal("No such user");
    }
    my $uid     = $user->uid();
    my $uid_idx = $user->uid_idx();
    
    my $query_result =
	DBQueryFatal("select * from user_exports ".
		     "where uid_idx='$uid_idx' and peer='$peername'");
    if (!$query_result->numrows && !$force) {
	fatal("User has not been exported to peer. Use -f option");
    }
    my $urn = GeniHRN::Generate($OURDOMAIN, "user", $user->uid());
    
420
    my $xmlgoo = emutil::ExecQuiet("$DUMPUSER $uid");
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 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 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 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 581 582 583 584 585 586 587 588 589 590 591 592 593 594
    if ($?) {
	fatal("$DUMPUSER failed");
    }
    my $args = {"xmlstring" => $xmlgoo,
		"urn"       => $urn};
    
    my $response = do_method($authority, "ModifyUser", $args);
    fatal("Could not modify user at $authority")
	if (! (defined($response) &&
	       $response->code() == GENIRESPONSE_SUCCESS));
    return 0;
}

#
# Set the groups for a user.
#
sub SetGroups(;$)
{
    my ($token) = @_;

    if (! defined($token)) {
	usage()
	    if (! @ARGV);
	$token = $ARGV[0];
    }
    my $user = User->Lookup($token);
    if (!defined($user)) {
	fatal("No such user");
    }
    my $uid     = $user->uid();
    my $uid_idx = $user->uid_idx();
    
    my $query_result =
	DBQueryFatal("select * from user_exports ".
		     "where uid_idx='$uid_idx' and peer='$peername'");
    if (!$query_result->numrows && !$force) {
	fatal("User has not been exported to peer. Use -f option");
    }
    my $urn = GeniHRN::Generate($OURDOMAIN, "user", $user->uid());

    my @grouplist = ();
    if ($user->GroupMembershipList(\@grouplist)) {
	fatal("Could not get group list for user");
    }
    if (! @grouplist) {
	print STDERR "$user is not a member of any groups";
	return 0;
    }
    my %grouparray = ();
    foreach my $group (@grouplist) {
	my $pid_idx = $group->pid_idx();
	my $gid_idx = $group->gid_idx();
	#
	# See if this group has been exported. Skip if not.
	#
	$query_result =
	    DBQueryFatal("select pid_idx,gid_idx from group_exports ".
			 "where  pid_idx='$pid_idx' and gid_idx='$gid_idx' and ".
			 "       peer='$peername'");
	next
	    if (!$query_result->numrows);
	
	my $membership = $group->LookupUser($user);
	if (!defined($membership)) {
	    fatal("Could not get membership for $user in $group");
	}
	my $pid   = $group->pid();
	my $gid   = $group->gid();
	my $trust = $membership->trust();
	$grouparray{"$pid,$gid"} = $trust;
    }
    print STDERR Dumper(\%grouparray) if ($debug);
    
    my $args = {"groups" => \%grouparray,
		"urn"    => $urn};

    my $response = do_method($authority, "SetGroups", $args);
    fatal("Could not setgroups for user at $authority")
	if (! (defined($response) &&
	       $response->code() == GENIRESPONSE_SUCCESS));
    return 0;
}

#
# Cross Login
#
sub CrossLogin()
{
    usage()
	if (! @ARGV);
    
    my $user = User->Lookup($ARGV[0]);
    if (!defined($user)) {
	fatal("No such user");
    }
    my $uid     = $user->uid();
    my $uid_idx = $user->uid_idx();
    
    my $query_result =
	DBQueryFatal("select * from user_exports ".
		     "where uid_idx='$uid_idx' and peer='$peername'");
    if (!$query_result->numrows && !$force) {
	fatal("User has not been exported to peer. Use -f option");
    }
    my $urn  = GeniHRN::Generate($OURDOMAIN, "user", $user->uid());
    my $args = {"urn" => $urn};

    #
    # Since this is coming from the web interface, want to limit
    # how long we wait, and return status if timed out.
    #
    Genixmlrpc->SetTimeout(20);
    
    my $response = do_method($authority, "CrossLogin", $args);
    fatal("Could not xlogin user at $authority")
	if (! (defined($response) &&
	       $response->code() == GENIRESPONSE_SUCCESS));
    my $key = $response->value();
    print "$key\n";
    return 0;
}

#
# Add a Project
#
sub AddProject()
{
    usage()
	if (! @ARGV);
    
    my $project = Project->Lookup($ARGV[0]);
    if (!defined($project)) {
	fatal("No such project");
    }
    my $pid     = $project->pid();
    my $pid_idx = $project->pid_idx();
    my $leader_uid = $project->head_uid();
    my $leader_idx = $project->head_idx();
    
    my $query_result =
	DBQueryFatal("select * from group_exports ".
		     "where pid_idx='$pid_idx' and gid_idx='$pid_idx' and ".
		     "      peer='$peername'");
    if ($query_result->numrows && !$force) {
	fatal("Project has already been exported to peer. Use -f option");
    }
    #
    # Check that the leader has been exported, and if not do that first.
    #
    my $leader_result =
	DBQueryFatal("select * from user_exports ".
		     "where uid_idx='$leader_idx' and peer='$peername'");
    if (!$leader_result->numrows) {
	AddUser($leader_idx);
    }
    
    my $xmlgoo = emutil::ExecQuiet("$DUMPPROJ $pid");
    if ($?) {
	fatal("$DUMPPROJ failed");
    }
    my $args = {"xmlstring" => $xmlgoo};
    
    my $response = do_method($authority, "AddProject", $args);
    fatal("Could not add project to $authority")
	if (! (defined($response) &&
	       ($response->code() == GENIRESPONSE_SUCCESS ||
		$response->code() == GENIRESPONSE_ALREADYEXISTS)));

    DBQueryFatal("replace into group_exports set ".
		 "  pid='$pid', pid_idx='$pid_idx', ".
		 "  gid='$pid', gid_idx='$pid_idx', ".
		 "  exported=now(), updated=now(), ".
		 "  peer='$peername'");
    
595
    SetGroups($leader_idx);
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 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
    return 0;
}

#
# Add a Group
#
sub AddGroup()
{
    usage()
	if (! @ARGV);
    
    my $group = Group->Lookup($ARGV[0]);
    if (!defined($group)) {
	fatal("No such group");
    }
    if ($group->IsProjectGroup()) {
	fatal("Please use addproject instead.");
    }
    my $pid_idx = $group->pid_idx();
    my $gid_idx = $group->gid_idx();
    my $pid     = $group->pid();
    my $gid     = $group->gid();
    
    my $query_result =
	DBQueryFatal("select * from group_exports ".
		     "where pid_idx='$pid_idx' and gid_idx='$pid_idx' and ".
		     "      peer='$peername'");
    if (!$query_result->numrows) {
	fatal("Project has not been exported to peer.\n");
    }
    $query_result =
	DBQueryFatal("select * from group_exports ".
		     "where pid_idx='$pid_idx' and gid_idx='$gid_idx' and ".
		     "      peer='$peername'");
    if ($query_result->numrows && !$force) {
	fatal("Group has already been exported to peer. Use -f option");
    }
    
    my %tags = (
	"project"	=> $group->pid(),
	"group_id"	=> $group->gid(),
	"group_leader"	=> $group->leader(),
	"group_description" => $group->description() || "",
    );

    my $args = {"tags" => \%tags};
    
    my $response = do_method($authority, "AddGroup", $args);
    fatal("Could not add group to $authority")
	if (! (defined($response) &&
	       ($response->code() == GENIRESPONSE_SUCCESS ||
		$response->code() == GENIRESPONSE_ALREADYEXISTS)));

    DBQueryFatal("replace into group_exports set ".
		 "  pid='$pid', pid_idx='$pid_idx', ".
		 "  gid='$gid', gid_idx='$gid_idx', ".
		 "  exported=now(), updated=now(), ".
		 "  peer='$peername'");
    
    return 0;
}

#
# Make an rpc call to the Emulab interface on the remote authority.
#
sub do_method($$;$)
{
    my ($authority, $method, $args) = @_;
    $args = {} if (!defined($args));

    #
    # The URL refers to the sa, but we want the emulab interface.
    #
    my $url = $authority->url();
    $url =~ s/\/sa$/\/emulab/;

    $args->{'credentials'} = [$credential->asString()];
    
    my $response =
	Genixmlrpc::CallMethod($url, undef, $method, $args);
    
    if (!defined($response)) {
	print STDERR "*** Internal error at $authority\n";
	return undef;
    }
    if ($response->code() != GENIRESPONSE_SUCCESS) {
	print STDERR "Error at $authority:";
	print STDERR " " . $response->output() . "\n";
    }
    return $response;
}

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

    print STDERR "$msg\n";
    exit(-1);
}