newimageid_ez.in 25.2 KB
Newer Older
1
#!/usr/bin/perl -w
2
#
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 URI::Escape;
30
use Cwd qw(realpath);
31 32 33 34 35 36

#
# Back-end script to create new Image descriptors (EZ Form.)
#
sub usage()
{
37
    print("Usage: newimageid [-v] [-a] [-s] [-t target] <xmlfile>\n");
38 39
    exit(-1);
}
40
my $optlist = "dvfast:";
41
my $debug   = 0;
42
my $force   = 0;
43
my $verify  = 0;	# Check data and return status only.
44 45
my $allpc   = 0;        # insert mappings for all pc types.
my $skipadmin = 0;      # Skip SLOT_ADMINONLY checks.
46
my $target;
47 48 49 50 51 52 53 54 55

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $TBAUDIT	= "@TBAUDITEMAIL@";
my $TBGROUP_DIR	= "@GROUPSROOT_DIR@";
my $TBPROJ_DIR	= "@PROJROOT_DIR@";
56 57
my $CREATEIMAGE = "$TB/bin/create_image";
my $CLONEIMAGE  = "$TB/sbin/clone_image";
58
my $RUNSONXEN   = "$TB/sbin/runsonxen";
59
my $DOIMAGEDIRS = @IMAGEDIRECTORIES@;
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

#
# 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;
80
use OSImage;
81
use Image;
82
use OSinfo;
83
use Node;
84
use EmulabFeatures;
85 86 87 88 89 90

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

91 92 93
# Set this is we need to instert an os_submap entry.
my $parentos;

94 95 96 97 98 99 100 101 102 103 104
#
# 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;
}
105 106 107
if (defined($options{"f"})) {
    $force = 1;
}
108 109 110
if (defined($options{"v"})) {
    $verify = 1;
}
111 112 113
if (defined($options{"s"})) {
    $skipadmin = 1;
}
114 115 116
if (defined($options{"a"})) {
    $allpc = 1;
}
117 118 119 120 121 122 123 124 125 126 127 128 129 130
if (defined($options{"t"})) {
    $target = $options{"t"};
    # Might be an EC2 target. Also need to untaint for below.
    if ($target =~ /^([-\w\@\.\+]+@[-\w\@\.\+]+)$/) {
	$target = $1;
    }
    else {
	my $node = Node->Lookup($target);
	if (!defined($node)) {
	    fatal("No such node!");
	}
	$target = $node->node_id();
    }
}
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
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 create new Image descriptors.
}
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.
164
    my $translated = realpath($xmlfile);
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    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.
186
my $SLOT_OSREQUIRED     = 0x8;  # Required on real OS's not datasets.
187 188 189 190 191 192 193 194 195 196 197 198
#
# 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
    ("imagename"	=> ["imagename",	$SLOT_REQUIRED],
     "nodetype"		=> ["nodetype",		$SLOT_OPTIONAL],
     "nodeclass"	=> ["nodeclass",	$SLOT_OPTIONAL],
     "pid"		=> ["pid",		$SLOT_REQUIRED],
     "gid"		=> ["gid",		$SLOT_OPTIONAL],
     "description"	=> ["description",	$SLOT_REQUIRED],
199 200
     "loadpart"		=> ["loadpart",		$SLOT_OSREQUIRED],
     "OS"		=> ["OS",		$SLOT_OSREQUIRED],
201 202 203 204
     "version"		=> ["version",		$SLOT_OPTIONAL,	   ""],
     "path"		=> ["path",		$SLOT_OPTIONAL,    ""],
     "node_id"		=> ["node_id",		$SLOT_OPTIONAL,    ""],
     "osfeatures",	=> ["osfeatures",	$SLOT_OPTIONAL,	   ""],
205
     "op_mode",		=> ["op_mode",		$SLOT_OSREQUIRED],
206 207 208 209
     "mtype_*"		=> ["mtype",		$SLOT_OPTIONAL],
     "wholedisk",	=> ["wholedisk",	$SLOT_OPTIONAL,    0],
     "max_concurrent",	=> ["max_concurrent",	$SLOT_OPTIONAL,    0],
     "shared",		=> ["shared",		$SLOT_OPTIONAL,    0],
210
     "global",		=> ["global",		$SLOT_OPTIONAL,    0],
Leigh Stoller's avatar
Leigh Stoller committed
211
     "noexport",	=> ["noexport",		$SLOT_OPTIONAL,    0],
212
     "mbr_version",	=> ["mbr_version",	$SLOT_OPTIONAL],
213
     "format",		=> ["format",		$SLOT_OPTIONAL],
214 215
     "metadata_url",	=> ["metadata_url",	$SLOT_ADMINONLY],
     "imagefile_url",	=> ["imagefile_url",	$SLOT_ADMINONLY],
216 217 218
     "origin_uuid",	=> ["origin_uuid",	$SLOT_ADMINONLY],
     "origin_name",	=> ["origin_name",	$SLOT_ADMINONLY],
     "origin_urn",	=> ["origin_urn",	$SLOT_ADMINONLY],
219
     "reboot_waittime",	=> ["reboot_waittime",	$SLOT_OPTIONAL],
Leigh Stoller's avatar
Leigh Stoller committed
220
     "hash",		=> ["hash",		$SLOT_ADMINONLY],
221
     "deltahash",	=> ["deltahash",	$SLOT_ADMINONLY],
222
     "nextosid",	=> ["nextosid",		$SLOT_ADMINONLY],
223
     "def_parentosid",	=> ["def_parentosid",	$SLOT_OPTIONAL],
224
     "isdataset",	=> ["isdataset",	$SLOT_OPTIONAL],
225 226 227
     "lba_low",    	=> ["lba_low",		$SLOT_OPTIONAL],
     "lba_high",	=> ["lba_high",		$SLOT_OPTIONAL],
     "lba_size",	=> ["lba_size",		$SLOT_OPTIONAL],
228
     "architecture",	=> ["architecture",	$SLOT_OPTIONAL],
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
);

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

248 249 250 251 252 253 254
# Image backed datasets are special.
my $isdataset = 0;
if (exists($xmlparse->{'attribute'}->{"isdataset"}) &&
    $xmlparse->{'attribute'}->{"isdataset"}->{'value'}) {
    $isdataset = 1;
}

255 256 257 258 259 260 261 262
#
# 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"
263 264
	if (($required & $SLOT_REQUIRED ||
	     ($required & $SLOT_OSREQUIRED && !$isdataset)) &&
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
	    ! exists($xmlparse->{'attribute'}->{"$key"}));
}
UserError()
    if (keys(%errors));

#
# We build up an array of arguments to pass to Image->Create() as we check
# the attributes.
#
my %newimageid_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'};
302 303 304
    if (!defined($value)) {	# Empty string comes from XML as an undef value.
	$xmlparse->{'attribute'}->{"$key"}->{'value'} = $value = "";
    }
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323

    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) {
324
	    # We now ignore unknown keys, to maintain compatability.
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
	    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;
	}
    }
347
    if ($required & $SLOT_ADMINONLY && !$skipadmin) {
348 349 350 351 352
	# Admin implies optional, but thats probably not correct approach.
	$errors{$key} = "Administrators only"
	    if (! $this_user->IsAdmin());
    }
	
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
    #
    # Special case nextosid so it can be in pid,osname format. 
    #
    if (($dbslot eq "nextosid" || $dbslot eq "def_parentosid") &&
	$value =~ /^.+,.+$/) {
	my ($pid,$osname) = ($value =~ /^(.*),(.*)$/);
	
	# Now check that the value is legal.
	if (! TBcheck_dbslot($pid, "projects",
			     "pid", TBDB_CHECKDBSLOT_ERROR)) {
	    $errors{$key} = TBFieldErrorString();
	    next;
	}
	if (! TBcheck_dbslot($osname, "os_info",
			     "osname", TBDB_CHECKDBSLOT_ERROR)) {
	    $errors{$key} = TBFieldErrorString();
	    next;
	}
    }
    else {
	# Now check that the value is legal.
	if (! TBcheck_dbslot($value, "images",
			     $dbslot, TBDB_CHECKDBSLOT_ERROR)) {
	    $errors{$key} = TBFieldErrorString();
	    next;
	}
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
    }
    $newimageid_args{$key} = $value;
}
UserError()
    if (keys(%errors));

#
# Options for using this page with different types of nodes.
# nodetype controls the view and trumps nodeclass.
# nodeclass determines what node types are visible from the DB.
#
my $nodeclass;
if (exists($newimageid_args{"nodetype"}) && 
    $newimageid_args{"nodetype"} == "mote") {
    $nodeclass = "mote";
} else {
    # Defaults to PC view.
    if (!exists($newimageid_args{nodeclass})) {
	$nodeclass = "pc";
    } else {
	$nodeclass = escapeshellarg($nodeclass);
    }
}

#
# 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.  Limit by class if given.
#
408 409 410 411
# If we are using architectures, and the image has an architecture, then
# we will switch back to the non-allpc path since we have enough info to
# make a better decision. 
#
412 413
my $types_querystring;
if ($allpc) {
414 415
    $types_querystring =
	"select nt.type,nt.class,nt.architecture from node_types as nt ".
416
	"left join node_type_attributes as a on a.type=nt.type ".
417 418 419 420 421 422
	"where a.attrkey='imageable' and a.attrvalue!='0' ";

    #
    # Restrict by sitevar, but still do query to avoid mistakes.
    #
    my $default_typelist = TBGetSiteVar("images/default_typelist");
Leigh Stoller's avatar
Leigh Stoller committed
423
    if (defined($default_typelist) && $default_typelist ne "") {
424 425 426 427 428
	$types_querystring .=
	    "and (".
	    join(" or ", map("nt.type='$_'", split(",", $default_typelist))) .
	    ") ";
    }
429 430
}
else {
431 432
    $types_querystring =
	"select distinct n.type,nt.class,nt.architecture from nodes as n ".
433 434 435 436 437
	"left join node_types as nt on n.type=nt.type ".
	"left join node_type_attributes as a on a.type=n.type ".
	"where a.attrkey='imageable' and ".
	"      a.attrvalue!='0' and n.role='testnode'";
}
438 439 440 441 442 443
if ($nodeclass) {
    $types_querystring .= " and nt.class='$nodeclass' ";
}
my $types_result = DBQueryFatal($types_querystring);

# Save the valid types in a new array for later.
444
my %mtypes_array;
445
my %mtypes_arch;
446 447

if ($types_result->numrows) {
448 449
    while (my ($type,$class,$arch) = $types_result->fetchrow_array()) {
	$mtypes_arch{$type}  = $arch if (defined($arch));
450
	$mtypes_array{$type} = $class;
451 452
	$xmlfields{"mtype_$type"} = ["mtype", $SLOT_OPTIONAL];
    }
453
}
454
else {
455
    $mtypes_array{"pc"} = "pc";
456 457 458
    $xmlfields{"mtype_pc"} = ["mtype", $SLOT_OPTIONAL];
}

459 460 461 462 463 464 465
#
# Now do special checks.
#

my $isadmin = $this_user->IsAdmin();
my $imagename = $newimageid_args{"imagename"};

466 467
# In this form, we make the images:imagename and the os_info:osname the
# same.
468 469 470 471 472 473 474 475 476 477 478
if ( length($imagename) > TB_OSID_OSNAMELEN()) {
    UserError("Descriptor Name: Too long! ".
    "Must be less than or equal to " . TB_OSID_OSNAMELEN());
}

my $project = Project->Lookup($newimageid_args{"pid"});
if (!defined($project)) {
    UserError("Project: No such project");
}

my $group;
Leigh Stoller's avatar
Leigh Stoller committed
479 480
if (exists($newimageid_args{"gid"})) {
    my $gid = $newimageid_args{"gid"};
481
    $group = Group->LookupByPidGid($project->pid(), $gid);
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
    if (!defined($group)) {
	UserError("Group: No such group $gid");
    }
}
else {
    $group = $project->GetProjectGroup();    
}

# Permission check if we managed to get a proper group above.
if ($group &&
    ! $group->AccessCheck($this_user, TB_PROJECT_MAKEIMAGEID())) {
    UserError("Project: Not enough permission");
}

#
# Only admin types can set the global bit for an image. Ignore silently.
#
my $global = 0;
500
if (($isadmin || $skipadmin) &&
501 502 503
    exists($newimageid_args{"global"}) &&
    $newimageid_args{"global"} eq "1") {
    $global = 1;
504 505
} else {
    delete $newimageid_args{"global"};
506 507 508 509 510 511 512 513 514 515 516 517
}

my $shared = 0;
if (exists($newimageid_args{"shared"}) &&
    $newimageid_args{"shared"} eq "1") {
    $shared = 1;
}
# Does not make sense to do this. 
if ($global && $shared) {
    UserError("Global: Image declared both shared and global");
}

518 519 520 521 522 523 524 525 526
if (exists($newimageid_args{"metadata_url"})) {
    $newimageid_args{"metadata_url"} =
	uri_unescape($newimageid_args{"metadata_url"})
}
if (exists($newimageid_args{"imagefile_url"})) {
    $newimageid_args{"imagefile_url"} =
	uri_unescape($newimageid_args{"imagefile_url"})
}

527 528 529 530 531 532 533 534 535 536 537 538
# Nextosid check. Must exist. admin check done above.
if (exists($newimageid_args{"nextosid"})) {
    my $nextos = OSinfo->Lookup($newimageid_args{"nextosid"});

    if (!defined($nextos)) {
	UserError("Nextosid: Does not exist");
    }
    # Might be in pid,osname format.
    $newimageid_args{"nextosid"} = $nextos->osid();
}
# Ditto def_parentosid
if (exists($newimageid_args{"def_parentosid"})) {
539
    $parentos = OSinfo->Lookup($newimageid_args{"def_parentosid"});
540

541
    if (!defined($parentos)) {
542 543 544
	UserError("def_parentosid: Does not exist");
    }
    # Might be in pid,osname format.
545
    $newimageid_args{"def_parentosid"} = $parentos->osid();
546 547
}

548
#
549 550 551 552 553 554 555 556 557 558 559 560 561
# We no longer allow users to set the path (via the web interface), so
# do not worry if it is not set, lets just set the path. In fact, we
# are going to ignore all he places that pass in a path, that code is
# duplicated in way too many places. The code below mirrors code in
# clone_image, but we can throw that away and all the other places.
#
# If its an admin, we allow the path to be set to /usr/testbed/images.
# We throw that away and set it the way we want it in /usr/testbed/images.
#
my $path;
my $spath = "/usr/testbed/images/";
my $ipid  = $newimageid_args{"pid"};
my $igid  = (exists($newimageid_args{"gid"}) &&
Leigh Stoller's avatar
Leigh Stoller committed
562
	     $newimageid_args{"gid"} ne "") ? $newimageid_args{"gid"} : $ipid;
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585

if ($ipid eq $igid || $global) {
    $path  = "$TBPROJ_DIR/$ipid/images/";
}
else {
    $path = "$TBGROUP_DIR/$ipid/$igid/images/";
}
if ($DOIMAGEDIRS) {
    $path  .= "${imagename}/";
    $spath .= "${imagename}/";
}
else {
    $path  .= "${imagename}.ndz";
    $spath .= "${imagename}.ndz";
}
if ($isadmin) {
    #
    # Admins can provide a path, but this is probably a bad idea too.
    # Ignore it unless /usr/testbed/images.
    #
    if (exists($newimageid_args{"path"}) &&
	$newimageid_args{"path"} =~ /^\/usr\/testbed\/images/) {
	$newimageid_args{"path"} = $spath;
586 587
    }
    else {
588
	$newimageid_args{"path"} = $path;
589 590
    }
}
591 592
else {
    $newimageid_args{"path"} = $path;
593
}
594 595 596 597 598
if ($newimageid_args{"path"} =~ /\/$/) {
    if (-e $newimageid_args{"path"} && ! -d $newimageid_args{"path"}) {
	UserError("Path: invalid path, it should be a directory");	
    }
}
599
elsif (-d $newimageid_args{"path"}) {
600 601
    UserError("Path: invalid path, its a directory");
}
602 603 604
if (1 || $debug) {
    print "Setting path to " . $newimageid_args{"path"} . "\n";
}
605

606 607 608 609 610 611 612 613 614 615 616 617 618
#
# We allow loadpart=0 for wholedisk images in the Long Form, and it
# uses the same table_regex checking patterns.  Here "wholedisk" is a
# separate checkbox. Note that for datasets we do not care about
# loadpart, it can be zero.
#
my $loadpart = 0;
if (!$isdataset) {
    $loadpart = $newimageid_args{"loadpart"};
    if ($loadpart < 1 || $loadpart > 4) {
	UserError("DOS Partion: Out of range.");
    }
}
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637

#
# Check sanity of node name and that user can create an image from it.
#
my ($node, $node_id);
if (exists($newimageid_args{"node_id"}) &&
    $newimageid_args{"node_id"} ne "") {

    if (!($node = Node->Lookup($newimageid_args{"node_id"}))) {
	UserError("Node: Invalid node name");
    }
    elsif (!$node->AccessCheck($this_user, TB_NODEACCESS_LOADIMAGE())) {
	UserError("Node: Not enough permission");
    }
    else {
	$node_id = $node->node_id();
    }
}

638 639 640 641 642
#
# If no MBR version was specified, and a snapshot node was given,
# try to deduce the default MBR version based on what is currently
# on the node we are snapshotting.
#
643 644
if (!$isdataset &&
    !exists($newimageid_args{"mbr_version"}) && defined($node_id)) {
645 646 647 648 649 650 651 652
    my $mbrvers = 1;

    #
    # If there is only one MBR version for all images on the disk,
    # use that.  Otherwise, if there is no or ambiguous info, default
    # to version 1.
    #
    my $query_result =
653
	DBQueryFatal("select mbr_version from ".
654
		     " `partitions` as p,image_versions as i ".
655 656 657
		     " where p.imageid=i.imageid ".
		     " and p.imageid_version=i.version ".
		     " and p.node_id='$node_id' group by mbr_version");
658 659 660 661 662 663
    if ($query_result && $query_result->numrows == 1) {
	($mbrvers) = $query_result->fetchrow_array();	
    }
    $newimageid_args{"mbr_version"} = $mbrvers;
}

664 665 666
#
# See what node types this image will work on. Must be at least one!
#
667
UserError("Node Types: Must have at least one node type defined")
668
    if (!$isdataset && !keys(%mtypes_array));
669

670
my $node_types_selected = 0;
671

672
#
673 674
# If we have architectures defined in the node_types table, and we got
# an architecture in the xml file for the image, we use those. Otherwise
675
# fall back to the old method. 
676
#
677 678 679
if (keys(%mtypes_arch) &&
    (exists($newimageid_args{"architecture"}) && 
     $newimageid_args{"architecture"} ne "")) {
680

681 682 683 684
    foreach my $arch (split(",", $newimageid_args{"architecture"})) {
	if (!exists($OSImage::IMAGE_ARCHITECTURES{$arch})) {
	    UserError("Architecture: Not a valid Architecture: $arch");
	}
685 686
    }
}
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
else {
    # Clear this since not using Architectures
    delete($newimageid_args{"architecture"})
	if (exists($newimageid_args{"architecture"}));
    
    # Check validity of mtype_* args, since the keys are dynamically generated.
    my @mtype_keys = grep(/^mtype_/, keys(%newimageid_args));
    foreach $key (@mtype_keys) {
	my $value = $newimageid_args{$key};
	print STDERR "mtype: '$key' -> '$value'\n"
	    if ($debug);

	my $type = $key;
	$type =~ s/^mtype_//;
    
	# Treat pcvm special for now.
	if ($type eq "pcvm" ||
	    grep(/^${type}$/, keys(%mtypes_array))) {
	    $node_types_selected++
		if ($value eq "1");
	}
	else {
	    $errors{$key} = "Illegal node type."
	}
    }
    #
    # When -a specified, add mappings for all pc types, does not matter if
    # there are nodes of that type. Skip the stub pc/pc entry though.
    #
    if ($allpc) {
	foreach my $type (keys(%mtypes_array)) {
	    my $class = $mtypes_array{$type};
	    next
		if ($class ne "pc" || $type eq $class);
721

722 723
	    $newimageid_args{"mtype_${type}"} = "1";
	    $node_types_selected++;
724
	}
725
    }
726 727
    UserError("Node Types: Must select at least one node type")
	if ($node_types_selected == 0 && !($force || $isdataset));
728 729 730 731 732 733 734 735 736 737 738 739 740 741
}

# XXX  Allowable OS types, OS features, and OpModes need to be
# XXX  converted from constants in osiddefs.php and put into the DB.
# XXX  Validity checks go here and in the similar place in newosid.in .
my %osid_reboot_waitlist = ("Linux", 120, "Fedora", 120, "FreeBSD", 120,
			    "NetBSD", 120, "Windows", 240, "TinyOS", 60,
			    "Oskit", 60, "Other", 60);

#
# Reboot waittime. Only admin users can set this. Grab default
# if not set.  If no default, complain (unless they failed to specify an OS
# in which case we will complain about that instead).
#
742 743 744 745 746 747 748 749 750 751 752 753
# XXX Do not think this code does anything useful.
#
if (!$isdataset) {
    my $OS = $newimageid_args{"OS"};
    my $reboot_waittime;
    if (!exists($osid_reboot_waitlist{$OS})) {
	UserError("OS: Invalid OS");
    } elsif (exists($newimageid_args{"reboot_waittime"})) {
	$reboot_waittime = $newimageid_args{"reboot_waittime"}
    } else {
	$reboot_waittime = $osid_reboot_waitlist{$OS};
    }
754 755 756 757 758 759 760 761 762 763 764 765 766
}

exit(0)
    if ($verify);

#
# Now safe to create new OS and image descriptors.
#
# We pass the imagename along as an argument to Create(), so remove it from
# the argument array.  (Same name is used for both Creates.)
#
delete($newimageid_args{"imagename"});

767
#
768
# No need for an osid when creating a dataset.
769
#
770 771
my $osid = undef;
my $new_osinfo = undef;
772 773
my $usrerr;

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
if (!$isdataset) {
    #
    # XXX note that osid "path" is not the same as imageid "path".  The former
    # is for multiboot (aka OSKit) kernels.  So we remove the path arg
    # temporary.
    #
    my $ipath = $newimageid_args{"path"};
    delete($newimageid_args{"path"});

    # Cross-connect: Make the os descriptor first with the imagename, then take
    # the osid index and use it as the imageid index as well.
    $newimageid_args{"ezid"} = 1;
    # OSInfo->Create args not quite the same as Image->Create ones so copy 
    # newimageid_args into a new hash and fix up values.
    my %newosid_args = %newimageid_args;
    $newosid_args{"shared"} = 1
	if ($global);
    my $new_osinfo = OSinfo->Create($project, $this_user, $imagename,
				    \%newosid_args, \$usrerr);
    UserError($usrerr)
	if (defined($usrerr));
    fatal("Could not create new OSID!")
	if (!defined($new_osinfo));

    $newimageid_args{"path"} = $ipath;
    $osid = $new_osinfo->osid();
800

Leigh Stoller's avatar
Leigh Stoller committed
801 802 803 804 805 806 807
    #
    # Insert a submap entry.
    #
    if (defined($parentos)) {
	$new_osinfo->SetRunsOnParent($parentos);
    }

808 809 810 811 812 813 814 815 816 817 818 819 820
    #
    # Special option. Whole disk image, but only one partition that actually
    # matters. None of this matters for datasets.
    #
    my $loadlen  = 1;
    $newimageid_args{"part${loadpart}_osid"} = $osid;
    if ($newimageid_args{"wholedisk"}) {
	$loadlen  = 4;
	$loadpart = 0;
    }
    $newimageid_args{"loadpart"} = $loadpart;
    $newimageid_args{"loadlength"} = $loadlen;
    $newimageid_args{"default_osid"} = $osid;
821

822 823 824
    # Create the osidtoimageid mapping too.
    $newimageid_args{"makedefault"} = 1
	if ($node_types_selected);
825 826 827 828 829 830 831 832
}
my $new_image = Image->Create($project, $group, $this_user, $imagename, $osid,
			      \%newimageid_args, \$usrerr);
UserError($usrerr)
    if (defined($usrerr));
fatal("Could not create new Image!")
    if (!defined($new_image));

833 834
my $imageid  = $new_image->imageid();
my $imagepid = $new_image->pid();
835

836
if (defined($parentos)) {
837 838 839 840
    #
    # Temp hack until we put all mappings into XML file.
    #
    if ($parentos->osname() =~ /^XEN4/) {
841
        system("$RUNSONXEN $imagepid,$imagename");
842
    }
843 844
}

845 846 847 848 849 850 851 852 853 854 855 856
#
# If a target was specified, fire off image creation. It will return
# quickly enough (going into the background) that we can wait here for
# it.
#
if (defined($target)) {
    #
    # Use clone_image for a node, create_image for an EC2 target. We use
    # clone cause it will do the provenance, so we do not have to duplicate
    # that stuff here. Then it just calls create_image.
    #
    if ($target =~ /^.*@.*$/) {
Leigh Stoller's avatar
Leigh Stoller committed
857
	system("$CREATEIMAGE -p $imagepid $imagename '$target'");    }
858
    else {
Leigh Stoller's avatar
Leigh Stoller committed
859
	# Must be an imagename, not an imageid.
860 861 862 863 864 865
	system("$CLONEIMAGE $imagename '$target'");
    }
    if ($?) {
	fatal("Could not image capture from $target");
    }
}
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
# The web interface requires this line to be printed.
print "IMAGE $imagename/$imageid has been created\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 escapeshellarg($)
{
    my ($str) = @_;

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