GeniCM.pm.in 164 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1
2
#!/usr/bin/perl -wT
#
3
# GENIPUBLIC-COPYRIGHT
Leigh B Stoller's avatar
Leigh B Stoller committed
4
# Copyright (c) 2008-2011 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# All rights reserved.
#
package GeniCM;

#
# The server side of the CM interface on remote sites. Also communicates
# with the GMC interface at Geni Central as a client.
#
use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw ( );

use GeniDB;
use Genixmlrpc;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
22
23
use GeniResponse;
use GeniTicket;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
24
use GeniCredential;
25
use GeniCertificate;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
26
use GeniSlice;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
27
use GeniAggregate;
28
use GeniAuthority;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
29
use GeniSliver;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
30
use GeniUser;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
31
use GeniRegistry;
32
use GeniUtil;
33
use GeniHRN;
34
use GeniXML;
35
use GeniUsage;
36
use libtestbed;
37
use emutil;
38
39
use EmulabConstants;
use libEmulab;
40
use Lan;
41
use Experiment;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
42
43
use English;
use Data::Dumper;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
44
use XML::Simple;
45
use XML::LibXML;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
46
use Date::Parse;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
47
use POSIX qw(strftime tmpnam);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
48
use Time::Local;
49
use Compress::Zlib;
50
use File::Temp qw(tempfile);
51
use MIME::Base64;
52
use Digest::SHA1 qw(sha1_hex);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
53
54
55
56
57
58
59
60

# Configure variables
my $TB		   = "@prefix@";
my $TBOPS          = "@TBOPSEMAIL@";
my $TBAPPROVAL     = "@TBAPPROVALEMAIL@";
my $TBAUDIT   	   = "@TBAUDITEMAIL@";
my $BOSSNODE       = "@BOSSNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
61
my $MAINSITE       = @TBMAINSITE@;
62
my $ELABINELAB     = @ELABINELAB@;
63
my $PGENIDOMAIN    = "@PROTOGENI_DOMAIN@";
64
my $PROTOUSER 	   = "elabman";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
65
my $CREATEEXPT     = "$TB/bin/batchexp";
66
my $ENDEXP         = "$TB/bin/endexp";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
67
my $NALLOC	   = "$TB/bin/nalloc";
68
my $NFREE	   = "$TB/bin/nfree";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
69
my $AVAIL	   = "$TB/sbin/avail";
70
my $PTOPGEN	   = "$TB/libexec/ptopgen";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
71
72
my $TBSWAP	   = "$TB/bin/tbswap";
my $SWAPEXP	   = "$TB/bin/swapexp";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
73
74
my $PLABSLICE	   = "$TB/sbin/plabslicewrapper";
my $NAMEDSETUP     = "$TB/sbin/named_setup";
75
my $EXPORTS_SETUP  = "$TB/sbin/exports_setup";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
76
77
my $VNODESETUP     = "$TB/sbin/vnode_setup";
my $GENTOPOFILE    = "$TB/libexec/gentopofile";
78
my $IPASSIGN       = "$TB/libexec/ipassign_wrapper";
79
my $TARFILES_SETUP = "$TB/bin/tarfiles_setup";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
80
81
82
my $MAPPER         = "$TB/bin/mapper";
my $VTOPGEN        = "$TB/bin/vtopgen";
my $SNMPIT         = "$TB/bin/snmpit";
83
my $RESERVEVLANS   = "$TB/sbin/protogeni/reservevlans";
84
my $NEWGROUP       = "$TB/bin/newgroup";
85
86
my $NEWPROJECT     = "$TB/sbin/newproj";
my $MAKEPROJECT    = "$TB/sbin/mkproj";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
87
my $PRERENDER      = "$TB/libexec/vis/prerender";
88
89
my $SUDO           = "/usr/local/bin/sudo";
my $WAP            = "$TB/sbin/withadminprivs";
90
my $XMLLINT	   = "/usr/local/bin/xmllint";
91
my $ADDAUTHORITY   = "$TB/sbin/protogeni/addauthority";
92
my $EMULAB_PEMFILE = "@prefix@/etc/genicm.pem";
93
my $TARINSTALL     = "/usr/local/bin/install-tarfile";
94
my $API_VERSION    = 1;
95
my $USELOCALPROJ   = 0;
96
97
98
99
100
101
102
103
104
105
106

#
# Tell the client what API revision we support.  The correspondence
# between revision numbers and API features is to be specified elsewhere.
# No credentials are required.
#
sub GetVersion()
{
    return GeniResponse->Create( GENIRESPONSE_SUCCESS, $API_VERSION );
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
107
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
108
# Respond to a Resolve request. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
109
110
111
112
113
114
#
sub Resolve($)
{
    my ($argref) = @_;
    my $uuid       = $argref->{'uuid'};
    my $cred       = $argref->{'credential'};
115
116
    my $type       = lc( $argref->{'type'} );
    my $hrn        = $argref->{'hrn'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
117
118
119
120

    if (! defined($cred)) {
	return GeniResponse->MalformedArgsResponse();
    }
121
122
123
124
    if (defined($uuid) && GeniHRN::IsValid($uuid)) {
	$hrn  = $uuid;
	$uuid = undef;
    }
125
126
127
128
129
130
131
132
133
134
135
136
    if( defined( $hrn ) && GeniHRN::IsValid( $hrn ) ) {
	my ($auth,$t,$id) = GeniHRN::Parse( $hrn );

	return GeniResponse->Create( GENIRESPONSE_ERROR, undef,
				     "Authority mismatch" )
	    if( $auth ne $OURDOMAIN );

	$type = lc( $t );
	
	$hrn = $id;	
    }
    if (! (defined($type) && ($type =~ /^(node)$/))) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
137
138
139
	return GeniResponse->MalformedArgsResponse();
    }
    # Allow lookup by uuid or hrn.
140
    if (! defined($uuid) && !defined( $hrn ) ) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
141
142
143
144
145
146
	return GeniResponse->MalformedArgsResponse();
    }
    if (defined($uuid) && !($uuid =~ /^[-\w]*$/)) {
	return GeniResponse->MalformedArgsResponse();
    }

147
148
149
150
    my $credential = CheckCredential($cred);
    return $credential
	if (GeniResponse::IsResponse($credential));

151
    if ($type eq "node") {
152
	require Interface;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
153
154
155
	my $node;
	
	if (defined($uuid)) {
156
	    $node= GeniUtil::LookupNode($uuid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
157
158
	}
	else {
159
	    $node= GeniUtil::LookupNode($hrn);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
160
	}
161
	if (! defined($node)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
162
163
164
	    return GeniResponse->Create(GENIRESPONSE_SEARCHFAILED,
					undef, "Nothing here by that name");
	}
165

166
	my $rspec = GetAdvertisement(0, $node->node_id(), "0.1", undef);
167
168
169
170
	if (! defined($rspec)) {
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					"Could not start avail");
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
171
172
	
	# Return a blob.
173
	my $blob = { "hrn"          => "${PGENIDOMAIN}." . $node->node_id(),
Leigh B. Stoller's avatar
Leigh B. Stoller committed
174
		     "uuid"         => $node->uuid(),
175
		     "role"	    => $node->role(),
176
177
		     "hostname"     =>
			 GeniUtil::FindHostname($node->node_id()),
178
179
		     "physctrl"     => 
			 Interface->LookupControl( $node->phys_nodeid() )->IP(),
180
181
		     "urn"          => GeniHRN::Generate( $OURDOMAIN,
							  "node",
182
183
							  $node->node_id() ),
		     "rspec"        => $rspec
Leigh B. Stoller's avatar
Leigh B. Stoller committed
184
185
186
187
188
189
190
		   };

	return GeniResponse->Create(GENIRESPONSE_SUCCESS, $blob);
    }
    return GeniResponse->Create(GENIRESPONSE_UNSUPPORTED);
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
191
192
193
194
195
196
#
# Discover resources on this component, returning a resource availablity spec
#
sub DiscoverResources($)
{
    my ($argref) = @_;
197
    my $credstr   = $argref->{'credential'};
198
    my $available = $argref->{'available'} || 0;
199
    my $compress  = $argref->{'compress'} || 0;
200
    my $version   = $argref->{'rspec_version'} || undef;
201
202
203
204

    my $credential = CheckCredential($credstr);
    return $credential
	if (GeniResponse::IsResponse($credential));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
205

206
207
    return DiscoverResourcesAux($available,
				$compress, $version, [$credential]);
208
209
}
# Helper function for V2.
210
sub DiscoverResourcesAux($$$$)
211
{
212
    my ($available, $compress, $version, $credentials) = @_;
213
    my $user_urn  = $ENV{'GENIRN'};
214
215
216
217
    $version   = "0.2"
	if (!defined($version));

    # Sanity check since this can come from client.
218
219
220
    if (! ($version eq "0.1" || $version eq "0.2" || $version eq "2"
	|| $version eq "PG 0.1" || $version eq "PG 0.2"
	|| $version eq "PG 2")) {
221
222
223
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "Improper version request");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
224

225
226
227
    # Oh, for $*%(s sake.  Frontier::RPC2 insists on representing a
    # Boolean as its own object type -- which Perl always interprets as
    # true, regardless of the object's value.  Undo all of that silliness.
228
229
230
231
232
233
    if (defined($available) && ref($available) eq 'Frontier::RPC2::Boolean') {
	$available = $available->value;
    }
    if (defined($compress) && ref($compress) eq 'Frontier::RPC2::Boolean') {
	$compress = $compress->value;
    }
234

Leigh B. Stoller's avatar
Leigh B. Stoller committed
235
236
237
238
    #
    # A sitevar controls whether external users can get any nodes.
    #
    my $allow_externalusers = 0;
239
    if (!GetSiteVar('protogeni/allow_externalusers', \$allow_externalusers)){
240
241
	      # Cannot get the value, say no.
	      $allow_externalusers = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
242
    }
243
244
245
246
247
248
249

    # Figure out if user has a credentials that exempts him
    # from the following policy. If external users are blocked access
    # and he presents a credential that exempts him from it, 
    # then he should get access.
    my $isExempted = 0;
    foreach my $credential (@$credentials) {
250
        if (GeniXML::PolicyExists('allow_externalusers', $credential) == 1) {
251
252
253
254
255
256
        $isExempted = 1;
        last;
      }
    }

    if (!$allow_externalusers && !$isExempted) {
257
	my $user = GeniUser->Lookup($user_urn, 1);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
258
259
260
261
262
263
264
	# No record means the user is remote.
	if (!defined($user) || !$user->IsLocal()) {
	    return GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
					"External users temporarily denied");
	}
    }

265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
    #
    # See if one of the credentials is a slice credential. If it is, and
    # that slice is active, pass it to ptopgen so that it includes the current
    # resources as available.
    #
    my $experiment = undef;
    foreach my $credential (@$credentials) {
	my ($auth, $type, $id) = GeniHRN::Parse($credential->target_urn());
	if ($type eq "slice") {
	    # Might not exist here yet.
	    my $slice = GeniSlice->Lookup($credential->target_urn());
	    if (defined($slice)) {
		# See if the local experiment exists yet.
		$experiment = Experiment->Lookup($slice->uuid());
	    }
	    last;
	}
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
284
    #
285
    # Acquire the advertisement from ptopgen and compress it if requested.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
286
    #
287
    my $xml = GetAdvertisement($available, undef, $version, $experiment);
288
    if (! defined($xml)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
289
290
291
292
	return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
				    "Could not start avail");
    }

293
294
295
296
297
298
    if( $compress ) {
	my $coder = Frontier::RPC2->new();
	my $base64 = encode_base64( compress( $xml ) );
	$xml = $coder->base64( $base64 );	
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
299
300
    return GeniResponse->Create(GENIRESPONSE_SUCCESS, $xml);
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
301

302
303
304
#
# Use ptopgen in xml mode to spit back an xml file. 
#
305
sub GetAdvertisement($$$$)
306
{
307
    my ($available, $pc, $version, $experiment) = @_;
308
    my $xml = undef;
309
310
    my $gotlock = 0;
    my $filename = "/var/tmp/protogeni_resources.xml";
311

312
313
314
315
316
317
318
    $version = "0.1"
	if ($version eq "PG 0.1");
    $version = "0.2"
	if ($version eq "PG 0.2");
    $version = "2"
	if ($version eq "PG 2");

319
    my $invocation = "$PTOPGEN -x -g $version -r -p GeniSlices";
320
321
322
323
    if (defined($experiment)) {
	my $eid = $experiment->eid();
	$invocation .= " -e $eid";
    }
324
325
326
327
    $invocation .= " -a" unless $available;
    if (defined($pc)) {
	$invocation .= " -1 $pc";
    }
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
    if (!defined($pc)) {
      again:
	#
	# Grab a global script lock. This will ensure that only one ptopgen
	# runs at a time, and everyone else who comes along while that first
	# one is running, will share the same results file.
	#
	# Need to use a well known name, unless we want to share that name
	# via the DB. Lets be simple about it for now.
	#
	if ((my $locked = TBScriptLock("discover", 1)) != TBSCRIPTLOCK_OKAY()) {
	    if ($locked == TBSCRIPTLOCK_IGNORE) {
		#
		# Previous locker finished ptopgen.
		# Grab the file if it exists (small race), otherwise
		# try again from the top.
		#
		if (open(AVAIL, "$filename")) {
		    $xml = "";
		    while (<AVAIL>) {
			$xml .= $_;
		    }
		    close(AVAIL);
		    return $xml;
		}
		goto again;
	    }
	    else {
		print STDERR "Could not get ptopgen lockfile\n";
		return undef;
	    }
	}
	else {
	    #
	    # We got the lock so we get to run ptopgen.
	    #
	    $gotlock = 1;
	}
    }
367
    if (open(AVAIL, "$invocation |")) {
368
	$xml = "";
369
370
371
372
373
	while (<AVAIL>) {
	    $xml .= $_;
	}
	close(AVAIL);
    }
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
    #
    # The lock holder has to create the new version of the file for
    # anyone waiting. Need to do this atomically so that anyone still
    # reading the previous version does not get inconsistent data.
    #
    if ($gotlock) {
	my ($fh, $tempname) = tempfile(UNLINK => 0, DIR => "/var/tmp");
	if (!defined($fh)) {
	    print STDERR "Could not create temporary file: $!\n";
	    $xml = undef;
	}
	else {
	    print $fh $xml;
	    close($fh);
	    if (! rename($tempname, $filename)) {
		print STDERR "Could not rename temporary file: $!\n";
		$xml = undef;
	    }
	}
	TBScriptUnlock();
    }
395
396
397
    return $xml;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
398
#
399
# Update a ticket with a new rspec.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
400
#
401
sub UpdateTicket($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
402
403
{
    my ($argref) = @_;
404
405
406
407
408
409
410
411
412
413

    return GetTicket($argref, 1);
}

#
# Respond to a GetTicket request. 
#
sub GetTicket($;$)
{
    my ($argref, $isupdate) = @_;
414
    my $rspecstr   = $argref->{'rspec'};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
415
    my $impotent   = $argref->{'impotent'};
416
417
    my $credstr    = $argref->{'credential'};
    my $tickstr    = $argref->{'ticket'};
418
419
420
421
422
423
424
    my $ticket;

    # Default to no update
    $isupdate = 0
	if (!defined($isupdate));
    $impotent = 0
	if (!defined($impotent));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
425

426
    if (! defined($credstr)) {
427
	return GeniResponse->MalformedArgsResponse();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
428
    }
429
    if (!defined($rspecstr)) {
430
431
	return GeniResponse->MalformedArgsResponse();
    }
432
433
434
435
    if (! ($rspecstr =~ /^[\040-\176\012\015\011]+$/)) {
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "Improper characters in rspec");
    }
436
437
438
439
    my $credential = CheckCredential($credstr);
    return $credential
	if (GeniResponse::IsResponse($credential));

440
    if ($isupdate) {
441
442
443
	$ticket = CheckTicket($tickstr);
	return $ticket
	    if (GeniResponse::IsResponse($ticket));
444
    }
445
    return GetTicketAux($credential,
446
			$rspecstr, $isupdate, $impotent, 0, 1, $ticket);
447
}
448

449
sub GetTicketAux($$$$$$$)
450
{
451
452
    my ($credential, $rspecstr, $isupdate, $impotent, $v2, $level,
	$ticket) = @_;
453
    
454
455
456
457
458
459
    defined($credential) &&
	($credential->HasPrivilege( "pi" ) or
	 $credential->HasPrivilege( "instantiate" ) or
	 $credential->HasPrivilege( "bind" ) or
	 return GeniResponse->Create( GENIRESPONSE_FORBIDDEN, undef,
				      "Insufficient privilege" ));
460
    
461
462
    my $slice_urn = $credential->target_urn();
    my $user_urn  = $credential->owner_urn();
463
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
464
    #
465
    # Create user from the certificate.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
466
    #
467
    my $user = CreateUserFromCertificate($credential);
468
469
470
    return $user
	if (GeniResponse::IsResponse($user));
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
471
    #
472
    # Create slice from the certificate.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
473
    #
474
475
    my $slice = GeniSlice->Lookup($slice_urn);
    if (!defined($slice)) {
476
	if ($isupdate) {
477
	    print STDERR "Could not locate slice $slice_urn for Update\n";
478
	    return GeniResponse->Create(GENIRESPONSE_ERROR, undef,
479
480
481
					"No slice found for UpdateTicket");
	}
	$slice = CreateSliceFromCertificate($credential, $user);
482
483
	return $slice
	    if (GeniResponse::IsResponse($slice));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
484
    }
485
    
486
    return GetTicketAuxAux($slice, $user, $rspecstr,
487
488
			   $isupdate, $impotent, $v2, $level, $ticket,
			   [$credential]);
489
}
490
sub GetTicketAuxAux($$$$$$$$$)
491
{
492
493
    my ($slice, $user, $rspecstr, 
        $isupdate, $impotent, $v2, $level, $ticket, $credentials) = @_;
494
495
496
    my $response    = undef;
    my $restorevirt = 0;	# Flag to restore virtual state
    my $restorephys = 0;	# Flag to restore physical state
497
498
    require OSinfo;
    require VirtExperiment;
499
500
501
502
503
504

    #
    # We need this below to sign the ticket.
    #
    my $authority = GeniCertificate->LoadFromFile($EMULAB_PEMFILE);
    if (!defined($authority)) {
505
	print STDERR " Could not load authority for $EMULAB_PEMFILE\n";
506
507
508
	return GeniResponse->Create(GENIRESPONSE_ERROR);
    }

509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
    #
    # Run xmllint on the rspec to catch format errors.
    #
    my ($fh, $filename) = tempfile(UNLINK => 0);
    if (!defined($fh)) {
	print STDERR "Could not create temp file for rspec\n";
	return GeniResponse->Create(GENIRESPONSE_ERROR);
    }
    print $fh $rspecstr;
    close($fh);
    my $xmlerrors = `$XMLLINT --noout $filename 2>&1`;
    unlink($filename);
    if ($?) {
	return GeniResponse->Create(GENIRESPONSE_ERROR,
				    $xmlerrors,
				    "rspec is not well formed");
    }

527
528
    my $rspec = GeniXML::Parse($rspecstr);
    if (! defined($rspec)) {
529
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
530
				    "Error Parsing rspec XML");
531
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
532

533
534
535
536
537
538
    my $rspecVersion = GeniXML::GetXmlVersion($rspec);
    if (! defined($rspecVersion)) {
	return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "Unknown RSpec Version");
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
539
540
541
542
    #
    # A sitevar controls whether external users can get any nodes.
    #
    my $allow_externalusers = 0;
543
    if (!GetSiteVar('protogeni/allow_externalusers', \$allow_externalusers)){
544
545
546
547
548
549
550
551
552
553
554
555
556
557
	    # Cannot get the value, say no.
	    $allow_externalusers = 0;
    }

    # Figure out if user has a credentials that exempts him
    # from the following policy. If external users are blocked access
    # and he presents a credential that exempts him from it, 
    # then he should get access.
    my $isExempted = 0;
    foreach my $credential (@$credentials) {
      if (1 == GeniXML::PolicyExists('allow_externalusers', $credential)) {
        $isExempted = 1;
        last;
      }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
558
    }
559
560
561

    if (!$allow_externalusers && !$isExempted && !$user->IsLocal()) {
	    return GeniResponse->Create(GENIRESPONSE_UNAVAILABLE, undef,
Leigh B. Stoller's avatar
Leigh B. Stoller committed
562
563
564
565
				    "External users temporarily denied");
    }
    
    #
566
    # For now all tickets expire very quickly (minutes), but once the
Leigh B. Stoller's avatar
Leigh B. Stoller committed
567
    # ticket is redeemed, it will expire according to the rspec request.
568
569
    # If nothing specified in the rspec, then it will expire when the
    # slice record expires, which was given by the expiration time of the
570
571
    # slice credential, or the local policy max_sliver_lifetime. See
    # CreateSliceFromCertificate() in this file.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
572
    #
Jonathon Duerig's avatar
Jonathon Duerig committed
573
    my $expires = GeniXML::GetExpires($rspec);
574
    if (defined($expires)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
575
576
577
578
579
580
581
582
583
584
585
586
	if (! ($expires =~ /^[-\w:.\/]+/)) {
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"Illegal valid_until in rspec");
	}
	# Convert to a localtime.
	my $when = timegm(strptime($expires));
	if (!defined($when)) {
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"Could not parse valid_until");
	}
	
	#
587
	# Do we need a policy limit?
Leigh B Stoller's avatar
Leigh B Stoller committed
588
589
590
591
592
	# A sitevar controls the sliver lifetime.
	#
	my $max_sliver_lifetime = 0;
	if (!GetSiteVar('protogeni/max_sliver_lifetime',
			\$max_sliver_lifetime)){
593
594
	    # Cannot get the value, default it to 90 days.
	    $max_sliver_lifetime = 90;
Leigh B Stoller's avatar
Leigh B Stoller committed
595
596
597
598
599
600
601
602
603
604
605
606
607
	}

	# Check if the user has a credential that lets him obtain slivers
	# with extended sliver lifetime. If so allow him to get sliver.
	foreach my $credential (@$credentials) {
	    my $nodes = GeniXML::FindNodesNS("//n:max_sliver_lifetime",
					     $credential->extensions(),
					     $GeniUtil::EXTENSIONS_NS);
	    if ($nodes->size > 0) {
		$max_sliver_lifetime = int($nodes->pop()->string_value);
		last;
	    }
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
608
	my $diff = $when - time();
609
610
611
612
613
614
	if ($diff < (60 * 5)) {
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					"such a short life for a sliver? ".
					"More time please.");
	}
	elsif ($diff > (3600 * 24 * $max_sliver_lifetime)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
615
	    return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
616
617
			"expiration is greater then the maximum number ".
			"of minutes " . (60 * 24 * $max_sliver_lifetime));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
618
	}
619
620
621
622
623
624

	#
	# Must be before the slice expires.
	#
	my $slice_expires = $slice->expires();
	if (defined($slice_expires)) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
625
	    $slice_expires = str2time($slice_expires);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
626
	    if ($when > $slice_expires) {
627
628
629
630
		return GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				    "valid_until is past slice expiration");
	    }
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
631
    }
632
633
634
635
636
637
638

    #
    # Lock the ticket so it cannot be released.
    #
    if (defined($ticket) && $ticket->stored() && $ticket->Lock() != 0) {
	return GeniResponse->BusyResponse("ticket");
    }
639
640
641
    if (defined($ticket)) {
	$ticket->SetSlice($slice);
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
642
643
644
645
646
647
    
    #
    #
    # Lock the slice from further access.
    #
    if ($slice->Lock() != 0) {
648
649
650
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
	return GeniResponse->BusyResponse("slice");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
651
    }
652
653
654
    # Shutdown slices get nothing.
    if ($slice->shutdown()) {
	$slice->UnLock();
655
656
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
657
658
659
	return GeniResponse->Create(GENIRESPONSE_FORBIDDEN, undef,
				    "Slice has been shutdown");
    }
660
661
662
663
664
665
666
667
    # Ditto for expired.
    if ($slice->IsExpired()) {
	$slice->UnLock();
	$ticket->UnLock()
	    if (defined($ticket) && $ticket->stored());
	return GeniResponse->Create(GENIRESPONSE_REFUSED, undef,
				    "Slice has expired");
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
668

669
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
670
    # For now, there can be only a single toplevel aggregate per slice.
671
    # The existence of an aggregate means the slice is active here. 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
672
    #
673
    my $aggregate = GeniAggregate->SliceAggregate($slice);
674
675
676
677
678
    if (!$isupdate) {
	if (defined($aggregate)) {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Already have an aggregate for slice");
	    goto bad;
679
680
	}
    }
681
682
683
684
685
    elsif ($v2 && $level && !defined($ticket) && !defined($aggregate)) {
	print STDERR "No aggregate for $slice in version two API\n";
	$response = GeniResponse->Create(GENIRESPONSE_ERROR);
	goto bad;
    }
686
687
688
689

    #
    # Firewall hack; just a flag in the rspec for now.
    #
690
691
692
    my $needsfirewall = GeniXML::GetText("needsfirewall", $rspec);
    if (defined($needsfirewall)) {
	if ($slice->SetFirewallFlag($needsfirewall) != 0) {
693
694
	    $response = GeniResponse->Create(GENIRESPONSE_ERROR);
	    goto bad;
695
696
	}
    }
697
698

    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
699
    # We need this now so we can form a virtual topo.
700
    #
701
702
703
704
705
706
707
708
709
710
711
    my $slice_experiment = GeniExperiment($slice, $user);
    if (GeniResponse::IsResponse($slice_experiment)) {
	$response = $slice_experiment;
	$slice_experiment = undef;
	goto bad;
    }
    my $realuser = FlipToUser($slice, $user);
    if (! (defined($realuser) && $realuser)) {
	$response = GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					 "FlipToUser Error");
	print STDERR "Error flipping to real user\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
712
713
714
715
	goto bad;
    }
    my $pid = $slice_experiment->pid();
    my $eid = $slice_experiment->eid();
716
717
718
719
720

    #
    # Mark the experiment locally as coming from the cooked interface.
    # This changes what tmcd returns to the local nodes.
    #
721
    my $generated_by = GeniXML::GetText("generated_by", $rspec);
722
723
    if (defined($generated_by) &&
	$generated_by eq "libvtop") {
724
725
726
727
	$slice_experiment->Update({"geniflags" =>
				       $Experiment::EXPT_GENIFLAGS_EXPT|
				       $Experiment::EXPT_GENIFLAGS_COOKED});
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
728
729
730
731
732
733
734
735
736
737
738
739
740
    
    #
    # Create a virt topology object. We are going to load this up as we
    # process the rspec.
    #
    my $virtexperiment = VirtExperiment->CreateNew($slice_experiment);
    if (!defined($virtexperiment)) {
	print STDERR "Could not create VirtExperiment object!\n";
	$response = GeniResponse->Create(GENIRESPONSE_ERROR);
	goto bad;
    }
    # Turn off fixnode; we will control this on the commandline.
    $virtexperiment->allowfixnode(0);
741
    $virtexperiment->multiplex_factor(1);
742

743
744
745
746
747
748
    if ($MAINSITE) {
	$virtexperiment->NewTableRow("virt_vtypes",
				     {"name"     => "pcfast",
				      "members"  => "pc3000 d710",
				      "weight"   => 0.5});
    }
749
750
751
752
753
    # Need to move this someplace else; the parser adds a bunch.
    $virtexperiment->NewTableRow("virt_agents",
				 {"vnode"      => "*",
				  "vname"      => "ns",
				  "objecttype" => "6"});
754

Leigh B. Stoller's avatar
Leigh B. Stoller committed
755
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
756
757
    # An rspec is a structure that requests specific nodes. If those
    # nodes are available, then reserve it. Otherwise the ticket
Leigh B. Stoller's avatar
Leigh B. Stoller committed
758
759
    # cannot be granted.
    #
760
761
762
    my %namemap  = ();
    my %colomap  = ();
    my %ifacemap = ();
Jonathon Duerig's avatar
Jonathon Duerig committed
763
    my %iface2node = ();
764
    my %vportmap = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
765
    my %nodemap  = ();
766
    my %bridgemap= ();
767
    my @nodeids  = ();
768
    my %lannodes = ();
769
    # For stitching, keep track of external nodes and links.
770
771
772
773
    my %external_nodemap  = ();
    my %external_linkmap  = ();
    my %external_vportmap = ();
    my %stitching_paths   = ();
774
775
776
777
778
779
780
781

    #
    # If this is a ticket update, we want to seed the namemap with
    # existing nodes. This is cause the rspec might refer to wildcards
    # that were already bound in a previous call. We also want to know
    # what nodes are currently reserved in case we have to release some.
    #
    if ($isupdate) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
	$slice_experiment->ClearBackupState();
	if ($slice_experiment->BackupVirtualState()) {
	    print STDERR "Could not backup virtual state!\n";
	    $response = GeniResponse->Create(GENIRESPONSE_ERROR);
	    goto bad;
	}
	if ($slice_experiment->RemoveVirtualState()) {
	    print STDERR "Could not remove virtual state!\n";
	    $response = GeniResponse->Create(GENIRESPONSE_ERROR);
	    goto bad;
	}
	$restorevirt = 1;

	if ($slice_experiment->BackupPhysicalState()) {
	    print STDERR "Could not backup physical state!\n";
	    $response = GeniResponse->Create(GENIRESPONSE_ERROR);
	    goto bad;
	}
800
801
802
803
804
805
806
	my $oldrspec;
	if ($v2 && defined($aggregate)) {
	    $oldrspec = $aggregate->GetManifest(0);
	}
	else {
	    $oldrspec = $ticket->rspec();
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
807
	
808
	foreach my $ref (GeniXML::FindNodes("n:node",
809
					    $oldrspec)->get_nodelist()) {
810
	    # Let remote nodes pass through.
811
	    next
812
		if (!GeniXML::IsLocalNode($ref));
813

814
815
	    # Skip lan nodes; they are fake.
	    next
816
		if (GeniXML::IsLanNode($ref));
817

818
	    my $node_nickname = GeniXML::GetVirtualId($ref);
Jonathon Duerig's avatar
Jonathon Duerig committed
819
	    my $colocate      = GeniXML::GetColocate($ref);
820
	    my $component_id  = GeniXML::GetNodeId($ref);
821
822
	    my $vnode_id      = GeniXML::GetVnodeId($ref);
	    my $node = GeniUtil::LookupNode($vnode_id);
823
824
	    if (!defined($node)) {
		$response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
825
				 "Bad resource $component_id in ticket");
826
827
		goto bad;
	    }
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
	    #
	    # Is the node a virtual node? Must be an update to an
	    # existing sliver/ticket, since we now return the node_id
	    # of the allocated virtual node, not the physical node.
	    #
	    if ($node->isvirtnode()) {
		my $pnode = Node->Lookup($node->phys_nodeid());
		if (!defined($pnode)) {
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "No physical resource for $component_id");
		    goto bad;
		}
		$node = $pnode;
	    }
843
844
845
846
847
	    $namemap{$node_nickname} = $node;
	    $colomap{$colocate} = $node
		if (defined($colocate));
	}
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
848

849
    print GeniXML::Serialize($rspec);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
850

851
    foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
852
	my $component_id  = GeniXML::GetNodeId($ref);
853
	my $vnode_id      = GeniXML::GetVnodeId($ref);
854
	my $manager_id    = GeniXML::GetManagerId($ref);
855
	my $node_nickname = GeniXML::GetVirtualId($ref);
Jonathon Duerig's avatar
Jonathon Duerig committed
856
857
858
859
	my $colocate      = GeniXML::GetColocate($ref);
	my $subnode_of    = GeniXML::GetSubnodeOf($ref);
	my $virtualization_type = GeniXML::GetVirtualizationType($ref);
	
860
	my $virtualization_subtype
Jonathon Duerig's avatar
Jonathon Duerig committed
861
862
                          = GeniXML::GetVirtualizationSubtype($ref);
	my $exclusive     = GeniXML::GetExclusive($ref);
863
	my $pctype;
864
	my $osname;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
865
	my $node;
866
	my $isbridge;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
867

868
869
870
871
872
873
874
875
	# Always populate iface2node mapping, even if we let the node
	# pass through.
	foreach my $linkref (GeniXML::FindNodes("n:interface",
						$ref)->get_nodelist()) {
	    my $virtual_id   = GeniXML::GetInterfaceId($linkref);
	    $iface2node{$virtual_id} = $node_nickname;
	}

876
	# Let remote nodes pass through.
877
878
879
880
	if (! GeniXML::IsLocalNode($ref)) {
	    $external_nodemap{$node_nickname} = $ref;
	    next;
	}
881

882
883
884
885
886
	#
	# Lan nodes are fake and do not go into the virt topo. Need
	# to remember them though, for when we do the links below.
	# They are still in the returned ticket though. 
	#
887
	if (GeniXML::IsLanNode($ref)) {
888
889
890
891
	    $lannodes{$node_nickname} = $ref;
	    next;
	}

892
893
894
	#
	# Check for disk_image request. Specified as a URN. 
	#
895
	my $diskref = GeniXML::GetDiskImage($ref);
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
	if (defined($diskref)) {
	    my $dname = GeniXML::GetText("name", $diskref);

	    if (defined($dname)) {
		if (! GeniHRN::IsValid($dname)) {
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Malformed image URN: $dname");
		    goto bad;
		}
		my ($auth,$type,$id) = GeniHRN::Parse($dname);
		my ($ospid,$os) = ($id =~ m{(.*)//(.*)});
		if ($type ne "image" || !defined($ospid) || !defined($os)){
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Malformed image URN: $dname");
		    goto bad;
		}
		#
915
916
		# For now, the project has to be emulab-ops or the
		# the current project.
917
		#
918
919
		if (! ($ospid eq TBOPSPID() ||
		       $ospid eq $slice_experiment->pid())) {
920
921
922
923
924
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				 "Illegal project name in URN: $dname");
		    goto bad;
		}
925
		my $osinfo = OSinfo->Lookup($ospid, $os);
926
927
928
		if (!defined($osinfo)) {
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
929
					     "Unknown image URN: $dname");
930
931
932
933
934
935
936
937
938
		    goto bad;
		}
		#
		# This is only going to be used in raw mode. 
		#
		$osname = $os;
	    }
	}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
939
940
941
	if (defined($virtualization_type)) {
	    if ($virtualization_type eq "emulab-vnode") {
		if (defined($virtualization_subtype)) {
942
943
		    $pctype = "pcvm";
		    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
944
945
946
947
948
949
		    if ($virtualization_subtype eq "emulab-jail") {
			$osname = "FBSD-JAIL";
		    }
		    elsif ($virtualization_subtype eq "emulab-openvz") {
			$osname = "OPENVZ-STD";
		    }
950
951
952
953
		    elsif ($virtualization_subtype eq "emulab-spp") {
			$osname = "SPPVM-FAKE";
			$pctype = "sppvm";
			# Lets force to shared node.
Jonathon Duerig's avatar
Jonathon Duerig committed
954
			if (! GeniXML::SetExclusive($ref, 0)) {
955
956
957
			    $response
				= GeniResponse->Create(GENIRESPONSE_BADARGS,
						       undef,
958
959
				       "Malformed rspec: ".
				       "Cannot set exclusive tag to false");
960
961
962
			    goto bad;
			}
			$exclusive = 0;
963
964
			# Kludge for libvtop.
			$virtexperiment->multiplex_factor(1);
965
			$virtexperiment->encap_style("vlan");
966
		    }
967
968
969
970
971
972
973
974
		    elsif ($virtualization_subtype eq "emulab-bbg") {
			$osname = "BBGENIVM-FAKE";
			$pctype = "bbgenivm";
			# Lets force to shared node.
			GeniXML::SetExclusive($ref, 0);
			$exclusive = 0;
			$virtexperiment->encap_style("vlan");
		    }
975
976
		    elsif ($virtualization_subtype eq "raw"
			   || $virtualization_subtype eq "raw-pc") {
977
978
979
			$pctype = undef;
			goto raw;
		    }
980
981
982
983
		    elsif ($virtualization_subtype eq "delay") {
			$isbridge = 1;
			$pctype   = undef;
		    }
984
985
986
987
988
989
990
991
		    else {
			$response
			    = GeniResponse->Create(GENIRESPONSE_BADARGS,
						   undef,
				       "Malformed rspec: ".
				       "Unknown virtualization_subtype");
			goto bad;
		    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
992
993
994
995
996
997
998
999
		}
		else {
		    goto raw;
		}
	    }
	    else {
	      raw:
		# Lets force to exclusive real node.
Jonathon Duerig's avatar
Jonathon Duerig committed
1000
		if (! GeniXML::SetExclusive($ref, 1)) {
1001
1002
		    $response = GeniResponse->Create(GENIRESPONSE_BADARGS,
						     undef,
1003
			"Malformed rspec: Cannot set exclusive tag to true");
1004
1005
1006
		    goto bad;
		}
		$exclusive = 1;
1007
1008
1009
1010
1011
		my $subtype = "raw-pc";
		if (GeniXML::IsVersion0($ref)) {
		    $subtype = "raw";
		}
		if (! GeniXML::SetVirtualizationSubtype($ref, $subtype)) {
1012
1013
		    $response = GeniResponse->Create(GENIRESPONSE_BADARGS,
						     undef,
1014
			"Malformed rspec: Cannot set virtualization_type to raw");
1015
1016
		    goto bad;
		}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1017
1018
1019
1020
	    }
	}
	else {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
1021
				     "Must provide a virtualization_type");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1022
1023
1024
	    goto bad;

	}
1025
1026
1027
1028
1029
1030
	if (!defined($node_nickname)) {
	    $response = GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Must provide a virtual_id for nodes");
	    goto bad;
	}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1031
	#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1032
	# Allow wildcarding.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1033
	#
1034
	if (!defined($component_id) || $component_id eq "*") {
1035
1036
1037
1038
1039
	    if (defined($colocate) && exists($colomap{$colocate})) {
		$node = $colomap{$colocate};
	    }
	    elsif ($isupdate && exists($namemap{$node_nickname})) {
		$node = $namemap{$node_nickname};
1040
	    }
1041
1042
	    # If the node still isn't bound and doesn't have a pctype,
	    # use the user-specified one.
1043
1044
1045
1046
1047
1048
1049
1050
1051
	    if (GeniXML::IsVersion0($ref)) {
		if (! defined($node) && ! defined($pctype)) {
		    my $usertype = GeniXML::FindFirst("n:node_type", $ref);
		    if (defined($usertype)) {
			$pctype = GeniXML::GetText("type_name", $usertype);
		    }
		}
	    } else {
		my $usertype = GeniXML::FindFirst("n:hardware_type", $ref);
1052
		if (defined($usertype)) {
1053
		    $pctype = GeniXML::GetText("name", $usertype);
1054
1055
		}
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1056
1057
	}
	else {
1058
	    $node = GeniUtil::LookupNode($vnode_id);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1059
1060
1061
1062

	    if (!defined($node)) {
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
1063
					 "Bad resource $component_id");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1064
1065
		goto bad;
	    }
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
	    #
	    # Is the node a virtual node? Must be an update to an
	    # existing sliver/ticket, since we now return the node_id
	    # of the allocated virtual node, not the physical node.
	    #
	    if ($node->isvirtnode()) {
		if (!$isupdate ||
		    !exists($namemap{$node_nickname})) {
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
				     "Bad resource for $node_nickname");
		    goto bad;
		}
		$node = $namemap{$node_nickname};
	    }
1081
1082
	    $pctype = $node->type()
		if (!defined($pctype));
1083
1084
	}
	#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1085
	# If no osname by this point, try for the default.
1086
1087
	#
	if (defined($node) && !defined($osname)) {
1088
1089
1090
1091
1092
	    if (defined($node->default_osid())) {	    
		my $osinfo = OSinfo->Lookup($node->default_osid());
		$osname = $osinfo->osname()
		    if (defined($osinfo));
	    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1093
	}
1094
1095
1096
	# The slot does not like to be NULL.
	$osname = ""
	    if (!defined($osname));
1097
	
1098
1099
1100
	# Need some kind of default.
	$pctype = "pc"
	    if (!defined($pctype));
1101
	
1102
1103
1104
1105
1106
	my $nodeblob = {"vname"   => $node_nickname,
			"type"    => $pctype,
			"osname"  => $osname,
			"ips"     => '', # deprecated
			"cmd_line"=> '', # bogus
1107
			"routertype" => "static-ddijk",
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1108
1109
			"fixed"   => (defined($subnode_of) ? $subnode_of :
				      defined($node) ? $node->node_id() : ""),
1110
			    
1111
			};
1112

1113
1114
1115
1116
	if ($isbridge) {
	    $nodeblob->{'role'} = "bridge";
	}

1117
	# Tarball and startup command.
1118
	my $tarfiles = GeniXML::GetTarball($ref);
1119
	if (defined($tarfiles)) {
1120
	    if (! TBcheck_dbslot($tarfiles, "virt_nodes", "tarfiles",
1121
				 TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
1122
1123
1124
1125
1126
		$response =
		    GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					 "Invalid tarfiles");
		goto bad;
	    }
1127
	    $nodeblob->{'tarfiles'} = $tarfiles;
1128
	}
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
	if (GeniXML::IsVersion0($ref)) {
	    my $startupcmd = GeniXML::GetStartupCommand($ref);
	    if (defined($startupcmd)) {
		if (! TBcheck_dbslot($startupcmd, "virt_nodes", "startupcmd",
				     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
		    $response =
			GeniResponse->Create(GENIRESPONSE_BADARGS, undef,
					     "Invalid startup command");
		    goto bad;
		}
		$nodeblob->{'startupcmd'} = $startupcmd;
	    }
	}
	elsif (my @services = GeniXML::GetServices($ref)) {
	    my $count = 0;
	    my $startfile = $slice_experiment->UserDir() . "/geni_startup";
	    $nodeblob->{'startupcmd'} = $startfile;
	    
	    if (!open(STARTUP, ">$startfile")) {
		$response = GeniResponse->Create(GENIRESPONSE_ERROR, undef,
						 "Error creating startfile");
		goto bad;
	    }
	    print STARTUP "#!/bin/sh\n\n";
	    print STARTUP "# Redirect all output to a file\n";
	    print STARTUP "exec &> /var/tmp/startup.log\n\n";

	    #
	    # It would be nice to interleave "install" with "execute", but
	    # Emulab's tarfiles support arranges to copy the files locally,
	    # and rewrites the names. Need to hook into that support somehow,
	    # but for now tarfiles are all installed as a block above. 
	    #
	    foreach my $service (@services) {
		my $type = $service->{'type'};

		if ($type eq "execute") {
		    my $shell = $service->{'shell'};
		    my $cmd   = $service->{'cmd'};
		    my $log   = "/var/tmp/startup-${count}.txt";
		    my $stat  = "/var/tmp/startup-${count}.status";

		    #
		    # Support only sh and csh. Maybe perl later.
		    #
1174
1175
1176
		    if (! (defined($shell) &&
			   ($shell eq "csh" || $shell eq "sh" ||
			    $shell eq "/bin/csh" || $shell eq "/bin/sh"))) {
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
			$response =
			    GeniResponse->Create(GENIRESPONSE_ERROR, undef,
						 "Invalid shell in execute");
			goto bad;
		    }
		    if (! ($shell =~ /bin/)) {
			$shell = "/bin/$shell";
		    }
		    print STARTUP "echo -n 'Services execution $count at '\n";
		    print STARTUP "date\n\n";
		    print STARTUP "$shell -c \"$cmd\" >$log 2>&1\n";
		    print STARTUP "status=\$?\n";
		    print STARTUP "echo \"\$status\" > $stat\n";
		    print STARTUP
		      "echo \"Execution $count exited with status \$status\"\n";
		    print STARTUP "echo '----------------------------------'\n";
		    $count++;
		}
	    }
	    print STARTUP "exit 0\n";
	    close(STARTUP);
	    chmod(0755, $startfile);
	}
1200
1201
1202
1203
1204
1205
1206

	my $virtnode = $virtexperiment->NewTableRow("virt_nodes", $nodeblob);
	if (!defined($virtnode)) {
	    $response = GeniResponse->Create(GENIRESPONSE_ERROR, undef,
					     "Error creating virtnode");
	    goto bad;
	}
1207

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1208
1209
1210
1211
1212
1213
	$virtexperiment->NewTableRow("virt_node_desires",
				     {"vname"    => $node_nickname,
				      "desire"   => "pcshared",
				      "weight"   => 0.95})
	    if (!defined($exclusive) || !$exclusive);