libptop_new.pm.in 54.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
# Copyright (c) 2010 University of Utah and the Flux Group.
# All rights reserved.
#
package libptopnew;

use strict;
use Exporter;
use lib "/usr/testbed/lib";
#use lib "@prefix@/lib";
use Node;
14
use Interface;
15
16
use OSinfo;
use libdb qw(TBGetSiteVar DBQueryFatal TBResolveNextOSID);
17
18
use vars qw(@ISA @EXPORT @EXPORT_OK);

19
20
21
22
sub FD_ADDITIVE  { return "FD_ADDITIVE"; }
sub FD_FIRSTFREE { return "FD_FIRSTFREE"; }
sub FD_ONCEONLY  { return "FD_ONCEONLY"; }

23
our $PGENISUPPORT = 1;
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
my $OURDOMAIN = "jonlab.tbres.emulab.net";
my $MAINSITE  = 0;
#my $PGENISUPPORT = @PROTOGENI_SUPPORT@;
#my $OURDOMAIN = "@OURDOMAIN@";
#my $MAINSITE  = @TBMAINSITE@;
my $cmuuid = TBGetSiteVar('protogeni/cm_uuid');
my $cmurn = "";
if ($PGENISUPPORT) {
    require GeniHRN;
    require GeniXML;
    $cmurn = GeniHRN::Generate($OURDOMAIN, "authority", "cm");
}


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

my $user_project = undef;
my $exempt_eid = undef;
43
my $available_only = 1;
44
my $print_widearea = 0;
45
46
47
48
my $print_shared = 0;
my $print_virtual = 0;
my $print_sim = 0;
my $genimode = 0;
49
50
my $delaycap_override = undef;
my $multiplex_override = undef;
51
52
53
54
55
my $debug = 0;

my $default_longitude = undef;
my $default_latitude = undef;
my $default_country = undef;
56
57
58

our %nodeList = ();
our %linkList = ();
59
60
our %interfaceList = ();

61
62
63
# Table of which types the user project is allowed to have.
# Keyed by type where 1 = allowed, 0 = denied, and ! exists = allowed
our %permissions = ();
64

65
66
# Map from auxtype names to real type names
our %auxtypemap = ();
67

68
69
# Map from type names to lists of features
our %typefeatures = ();
70

71
72
# Keyed by osids. Contains OsInfo structures
our %osinfo = ();
73

74
75
76
# Mapping between types and osids, and vice versa. Hash of arrays.
our %type_osid = ();
our %osid_type = ();
77

78
79
# Mapping between an osid and its subosids. Hash of arrays.
our %osid_subosid = ();
80

81
82
83
84
85
86
87
88
89
90
91
# Mapping between interface_type:base and bandwidth values based on
# interface_capabilities table. 'base' is the capkey prefix to one of
# the defspeed keys.
our %itype_bw = ();

# Keyed by $node:$iface, this is the amount of shared bandwidth
# available on that interface. Overrides the remaining_bandwidth from
# Interface. It should be the remaining bandwidth with the
# exempt_eid's bandwidth added back in.
our %sharedbw = ();

92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
sub ProcessArgs($)
{
    my ($optionsRef) = @_;
    my %options = %{ $optionsRef };
    if (defined($options{"p"})) {
	$user_project = $options{"p"};
    }
    if (defined($options{"e"})) {
	$exempt_eid = $options{"e"};
	usage()
	    if (!defined($user_project));
    }
    if (defined($options{"v"})) {
	$print_virtual = 1;
    }
    if (defined($options{"r"})) {
	$print_widearea = 1;
    }
    if (defined($options{"S"})) {
	$print_sim = 1;
    }
    if (defined($options{"h"})) {
	$print_shared = 1;
    }
    if (defined($options{"a"})) {
	$available_only = 0;
    }
    if (defined($options{"m"})) {
	$multiplex_override = $options{"m"};
    }
    if (defined($options{"d"})) {
	$debug = 1;
    }
    if (defined($options{"c"})) {
	$delaycap_override = $options{"c"};
    }
    if (defined($options{"g"})) {
	$genimode = 1;
	$print_shared = 1;
	$print_virtual = 1;
    }
}

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
#
# Initialize nodes hash based on nodes, reservations, and node_status tables
#
sub LookupNodes()
{
    my $dbresult;
    my $row;
    $dbresult = DBQueryFatal("select * from nodes");
    while ($row = $dbresult->fetchrow_hashref()) {
	CreateNode($row);
    }

    # Bulk lookup on reserved table
    $dbresult = DBQueryFatal("select * from reserved");
    while ($row = $dbresult->fetchrow_hashref()) {
	$nodeList{$row->{"node_id"}}->node()->SetReservedRow($row);
    }

    $dbresult = DBQueryFatal("select node_id, status from node_status");
    while (my ($node_id, $status) = $dbresult->fetchrow()) {
	$nodeList{$node_id}->set_status($status);
    }

    $dbresult = DBQueryFatal("select * from widearea_nodeinfo");
    while ($row = $dbresult->fetchrow_hashref()) {
	$nodeList{$row->{'node_id'}}->set_widearea($row);
    }
162
163
164
165

    TBGetSiteVar('general/default_longitude', \$default_longitude);
    TBGetSiteVar('general/default_latitude', \$default_latitude);
    TBGetSiteVar('general/default_country', \$default_country);
166
167
}

168
169
170
#
# Initialize project permissions table if the user specified a project.
#
171
sub LookupPermissions()
172
173
174
175
176
{
    if (defined($user_project)) {
        # By default a type is allowed for every project. If a type is
        # in the permissions table, it is allowed only for those
        # projects which it is attached to.
177
178
	my $dbresult =
	    DBQueryFatal("select distinct type ".
179
			   "from nodetypeXpid_permissions");
180
	while (my ($type) = $dbresult->fetchrow_array()) {
181
182
	    $permissions{$type} = 0;
	}
183
184
	$dbresult =
	    DBQueryFatal("select type ".
185
186
			   "from nodetypeXpid_permissions".
			   "where pid='$user_project'");
187
	while (my ($type) = $dbresult->fetchrow_array()) {
188
189
190
191
192
	    $permissions{$type} = 1;
	}
    }
}

193
194
195
#
# Lookup global usage counts on virtual nodes.
#
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
sub LookupGlobalCounts()
{
    my $condition = " ";
    if (defined($exempt_eid)) {
	$condition = "and not (pid='$user_project' and eid='$exempt_eid') "
    }
    my $dbresult = 
	DBQueryFatal("select phys_nodeid,count(phys_nodeid) ".
		     "from reserved as r ".
		     "left join nodes as n on n.node_id=r.node_id ".
		     "where n.node_id!=n.phys_nodeid ".
		     $condition.
		     "group by phys_nodeid");
    while (my ($node_id, $count) = $dbresult->fetchrow_array()) {
	$nodeList{$node_id}->set_globalcount($count);
    }
}

214
215
216
217
#
# Auxtypes can be associated with the main type of a node or with the
# node itself. Lookup both of these cases.
#
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
sub LookupAuxtypes()
{
    my $dbresult;
    #
    # Read the auxtypes for each type.
    # 
    $dbresult = DBQueryFatal("select auxtype,type from node_types_auxtypes");
    while (my ($auxtype,$type) = $dbresult->fetchrow_array()) {
	$auxtypemap{$auxtype} = $type;
    }

    #
    # Read in the node_auxtypes table for each node.
    #
    $dbresult = DBQueryFatal("select node_id, type, count from node_auxtypes");
    while (my ($node_id, $type, $count) = $dbresult->fetchrow_array()) {
	$nodeList{$node_id}->addAuxtype($type, $count);
    }
}

238
239
240
241
242
243
#
# Find features associated both with types and with nodes. Add the
# node features immediately and save the association between types and
# features. We will add those features to nodes when we iterate over
# all the nodes during processing.
#
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
sub LookupFeatures()
{
    my $dbresult;
    #
    # Read the features table for each type.
    # 
    $dbresult =
	DBQueryFatal("select type, feature, weight from node_type_features");
    while (my ($type, $feature, $weight) = $dbresult->fetchrow()) {
	if (! exists($typefeatures{$type})) {
	    $typefeatures{$type} = [];
	}
	push(@{ $typefeatures{$type} }, $feature.":".$weight);
    }

    #
    # Read the features table for each individual node
    #
    $dbresult =
	DBQueryFatal("select node_id, feature, weight from node_features");
    while (my ($node_id, $feature, $weight) = $dbresult->fetchrow()) {
	my $pnode = $nodeList{$node_id};
	if ($pnode->iswidearea()
	    || ($pnode->islocal() && ! $pnode->node()->sharing_mode())) {
	    $pnode->addFeatureString($feature.":".$weight);
	}
    }
}

273
274
275
276
#
# Bulk lookup on the os_info table. Find the mapping between types and
# osids and between osids and subosids.
#
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
sub LookupOsids()
{
    my $dbresult;
    my $row;
    # Bulk lookup on os_info table
    $dbresult = DBQueryFatal("select * from os_info");
    while ($row = $dbresult->fetchrow_hashref()) {
	my $os = OSinfo->LookupRow($row);
	$osinfo{$os->osid()} = $os;
    }

    #
    # Read the table of which image types are supported on which
    # hardware - we limit this to global images and ones that match
    # the PID (if given) We do this limiting for two reasons:
    # 1) To avoid an explosion in the number of features for nodes
    # 2) To avoid information leaks, allowing projects to see each
    #    other's images
    # 
    my $pidos = "";
    if (defined($user_project)) {
	$pidos = "or i.pid='$user_project'";
    }
    $dbresult =
	DBQueryFatal("select distinct oi.osid, oi.type ".
302
303
		     "from os_info as o ".
		     "left join osidtoimageid as oi on o.osid=oi.osid ".
304
305
306
		     "left join images as i on oi.imageid = i.imageid ".
		     "where i.global = 1 $pidos");
    while (my ($osid, $typename) = $dbresult->fetchrow()) {
307
308
309
310
	if (defined($typename)) {
	    hashpush(\%type_osid, $typename, $osid);
	    hashpush(\%osid_type, $osid, $typename);
	}
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
    }

    #
    # We also have to resolve the 'generic' OSIDs, which use the
    # nextosid field to redirect to another OSID
    #
    $dbresult = DBQueryFatal("select osid from os_info where " .
			     "nextosid is not null");
    while (my ($osid) = $dbresult->fetchrow()) {
	#
	# Check to see if they were allowed to use the real OSID
	#
	my $realosid = TBResolveNextOSID($osid, $user_project, $exempt_eid);
	if (exists($osid_type{$realosid})) {
	    foreach my $type (@{ $osid_type{$realosid} }) {
		hashpush(\%type_osid, $type, $osid);
	    }
	}
    }

    #
    # For subOS support (i.e., vnode OSes running atop vhost OSes), we
    # have to check both the subosid and all the parent_osid it can
    # run on.
    #
    my $subosidquery = "select distinct o.osid,o.parent_osid ".
	"from os_submap as o " .
	"left join osidtoimageid as oi1 on o.osid = oi1.osid " .
	"left join osidtoimageid as oi2 on o.parent_osid = oi2.osid " .
	"left join images as i1 on oi1.imageid = i1.imageid ".
	"left join images as i2 on oi2.imageid = i2.imageid ".
	"where (i1.global = 1";
    if (defined($user_project)) {
	$subosidquery .= " or i1.pid='$user_project'";
    }
    $subosidquery .= ") and (i2.global = 1";
    if (defined($user_project)) {
	$subosidquery .= " or i2.pid='$user_project'";
    }
    $subosidquery .= ")";
    $dbresult = DBQueryFatal($subosidquery);
    while (my ($subosid,$osid) = $dbresult->fetchrow()) {
	hashpush(\%osid_subosid, $osid, $subosid);
    }
}

357
#
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# Lookup interfaces and interface types. Important for determining
# bandwidth on links below and for printing out on nodes in genimode.
#
sub LookupInterfaces()
{
    my $dbresult;
    my $row;
    my %states = ();

    
    $dbresult = DBQueryFatal("select * from interface_state");
    while ($row = $dbresult->fetchrow_hashref()) {
	my $key = $row->{'node_id'}.':'.$row->{'iface'};
	$states{$key} = $row;
    }

    $dbresult = DBQueryFatal("select * from interfaces");
    while ($row = $dbresult->fetchrow_hashref()) {
	my $key = $row->{'node_id'}.':'.$row->{'iface'};
	my $iface = Interface->LookupRow($row, $states{$key});
	$interfaceList{$key} = $iface;
379
380
	my $node = $nodeList{$row->{'node_id'}};
	$node->addInterface($row->{'iface'});
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
    }

    $dbresult =
	DBQueryFatal("SELECT type,capkey,capval from interface_capabilities ".
		     "where capkey='protocols' or capkey like '%_defspeed'");
    while (my ($type,$capkey,$capval) = $dbresult->fetchrow_array()) {
	if ($capkey eq "protocols") {
#	    $interfaceprotocols{$type} = [ split(",", $capval) ];
	} elsif ($capkey =~ /^([-\w]+)_defspeed$/) {
	    $itype_bw{$type.":".$1} = $capval;
	} else {
	    die("Improper defspeed $capval for $type!\n");
	}
    }

    if (defined($exempt_eid)) {
	AddSharedBandwidth();
    }
}

#
# Bandwidth for shared nodes is calculated differently and already
# subtracts out all reserved capacity. So if the user specifies an
# exempt_eid, we must add back in that experiment's shared bandwidth.
#
sub AddSharedBandwidth()
{
    my $experiment = Experiment->Lookup($user_project, $exempt_eid);
    if (! defined($experiment)) {
	die("Could not look up experiment $user_project/$exempt_eid\n");
    }
    # Read the vinterfaces table to get any bandwidth in use by
    # this experiment.
    my $exptidx   = $experiment->idx();
    my $pstateDir = $experiment->WorkDir() . "/pstate";

    # This awful mess of creating a temporary table from a file on
    # boss is because the vinterfaces table itself will be purged of
    # experiment data when we are doing a swapmod. The only place
    # where the data remains is in the backup file.
    DBQueryFatal("create temporary table if not exists ".
		 "vinterfaces_${exptidx} like vinterfaces");

    DBQueryFatal("delete from vinterfaces_${exptidx}");
    
    DBQueryFatal("load data infile '$pstateDir/vinterfaces' ".
		 "into table vinterfaces_${exptidx}")
	    if (-e "$pstateDir/vinterfaces");
    
    my $result = DBQueryFatal("select * from vinterfaces_$exptidx ".
			      "where exptidx=$exptidx");

    while (my $row = $result->fetchrow_hashref()) {
	my $node      = $row->{'node_id'};
	my $iface     = $row->{'iface'};
	my $bandwidth = $row->{'bandwidth'};

	next
	    if (!defined($iface) || $bandwidth <= 0);
	next
	    if (! exists($interfaceList{"$node:$iface"}));

	if (! exists($sharedbw{"$node:$iface"})) {
	    $sharedbw{"$node:$iface"} =
		$interfaceList{"$node:$iface"}->remaining_bandwidth();
	}
	$sharedbw{"$node:$iface"} += $bandwidth;
    }
}

#
# Lookup wires. Let nodes know which other nodes they are connected to
# for later use when adding features. Add links between nodes for
# later printing.
455
456
#
sub LookupLinks()
457
{
458
459
460
    my $dbresult;
    my $row;
    $dbresult =
461
462
	DBQueryFatal("select w.type, w.node_id1, w.card1, w.port1, i1.iface, ".
		     "w.node_id2, w.card2, w.port2, i2.iface ".
463
		     "from wires as w ".
464
465
466
467
468
469
		     "left join interfaces as i1 ".
		     "on w.node_id1=i1.node_id and w.card1=i1.card ".
		     "and w.port1=i1.port ".
		     "left join interfaces as i2 ".
		     "on w.node_id2=i2.node_id and w.card2=i2.card ".
		     "and w.port2=i2.port ".
470
		     "where w.logical=0");
471
472
473
    while (my ($type, $node_id1, $card1, $port1, $iface1,
	       $node_id2, $card2, $port2, $iface2) = $dbresult->fetchrow()) {
	# Add connections between nodes for features later.
474
475
476
477
478
	if ($type ne 'Unused') {
	    my $node1 = $nodeList{$node_id1};
	    my $node2 = $nodeList{$node_id2};
	    if (defined($node1)) {
		$node1->addConnection($node_id2);
479
	    } elsif ($debug) {
480
481
482
483
		print STDERR "Unknown node: $node_id1\n";
	    }
	    if (defined($node2)) {
		$nodeList{$node_id2}->addConnection($node_id1);
484
	    } elsif ($debug) {
485
486
487
		print STDERR "Unknown node: $node_id2\n";
	    }
	}
488
489
	if ($type eq 'Trunk') {
	    # This is a switch/switch link potentially trunked to other wires.
490
	    if (! defined($iface1) && $debug) {
491
492
493
		print STDERR "Undefined interface for ".
		    "$node_id1:$card1:$port1\n";
	    }
494
	    if (! defined($iface2) && $debug) {
495
496
497
498
		print STDERR "Undefined interface for ".
		    "$node_id2:$card2:$port2\n";
	    }
	    my ($source, $dest, $sourcebw, $destbw);
499
#	    if ($node_id1 le $node_id2) {
500
501
502
503
		$source = $node_id1;
		$dest = $node_id2;
		$sourcebw = SwitchBandwidth($node_id1, $iface1);
		$destbw = SwitchBandwidth($node_id2, $iface2);
504
505
506
507
508
509
#	    } else {
#		$source = $node_id2;
#		$dest = $node_id1;
#		$sourcebw = SwitchBandwidth($node_id2, $iface2);
#		$destbw = SwitchBandwidth($node_id1, $iface1);
#	    }
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
	    my $name = "link-$source:$dest";
	    if (! exists($linkList{$name})) {
		$linkList{$name} = libptop::plink->CreateTrunk($name,
							       $source,
							       $dest);
	    }
	    $linkList{$name}->addTrunk($sourcebw, $destbw);
	} elsif ($type eq 'Node') {
	    # Add a switch/node or node/node link.
	    my $link = libptop::plink->Create();
	    $link->set_source($node_id1);
	    $link->set_sourceif($iface1);
	    if (! defined($iface1)) {
		$link->set_sourceif($card1.".".$port1);
	    }
	    $link->set_sourcecard($card1);
	    $link->set_sourceport($port1);
	    $link->set_dest($node_id2);
	    $link->set_destif($iface2);
	    if (! defined($iface2)) {
		$link->set_destif($card2.".".$port2);
	    }
	    $link->set_destcard($card2);
	    $link->set_destport($port2);

	    $link->processLink();
	    $linkList{$link->name()} = $link;
	}
538
    }
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
}

# Accessors
sub Nodes() { return \%nodeList; }
sub Links() { return \%linkList; }

# Add new nodes and links
sub CreateNode($)
{
    my ($row) = @_;
    my $node = libptop::pnode->Create($row);
    Nodes()->{$node->name()} = $node;
    return $node;
}

554
555
556
557
558
559
560
561
sub TypeAllowed($)
{
    my ($type) = @_;
    return (! defined($user_project)
	    || ! exists($permissions{$type})
	    || $permissions{$type});
}

562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
sub NodeBandwidth($$)
{
    my ($nodename, $iface) = @_;
    my $node = $nodeList{$nodename};
    if ($node->node()->sharing_mode()) {
	return ShareBandwidth($nodename, $iface);
    } else {
	return TypeBandwidth($nodename, $iface, "ethernet");
    }
}

sub SwitchBandwidth($$)
{
    my ($nodename, $iface) = @_;
    my $node = $nodeList{$nodename};
    # Default to 100 MBit. The default should never be used unless
    # there is an error in the database. If the wires table references
    # a node which doesn't exist, for instance.
    my $result = Math::BigInt->new(100000);
    if (defined($node)) {
582
	my $basetype = $node->get_basetype();
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
	$result = TypeBandwidth($nodename, $iface, $basetype);
    }
    return $result;
}

sub TypeBandwidth($$$)
{
    my ($node, $iface, $base) = @_;
    # Default to 100 MBit. The default should never be used unless
    # there is an error in the database. If a trunk wire exists
    # without corresponding interface rows for both ends, for
    # instance.
    my $result = 100000;
    if (defined($iface)) {
	if (exists($interfaceList{"$node:$iface"})) {
	    my $type = $interfaceList{"$node:$iface"}->type();
	    if (exists($itype_bw{"$type:$base"})) {
		$result = $itype_bw{"$type:$base"};
	    }
	}
    }
    return Math::BigInt->new($result);
}

sub ShareBandwidth($$)
{
    my ($node, $iface) = @_;
    my $result = new Math::BigInt->new(0);
    if (exists($sharedbw{"$node:$iface"})) {
	$result = $sharedbw{"$node:$iface"};
    } elsif (exists($interfaceList{"$node:$iface"})) {
	$result = $interfaceList{"$node:$iface"}->remaining_bandwidth();
    }
    return Math::BigInt->new($result);
}

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
sub make_ip($)
{
    my ($in) = @_;
    my @octets = split(/\./, $in);
    my $result = 0;
    my $i = 0;
    for (; $i < scalar(@octets); ++$i) {
	$result = (($result << 8) | $octets[$i]);
    }
    return $result;
}

sub is_routable($)
{
    my @privateIps   = (make_ip("10.0.0.0"), make_ip("172.16.0.0"),
			make_ip("192.168.0.0"));
    my @privateMasks = (8, 12, 16);

    my ($in) = @_;
    my $result = 0;
    if (defined($in) && $in =~ /\d+\.\d+\.\d+\.\d+/) {
	$result = 1;
	my $ip = make_ip($in);
	my $i = 0;
	for ($i = 0; $i < scalar(@privateIps); ++$i) {
	    my $mask = (0xffffffff << (32 - $privateMasks[$i]));
	    if (($ip & $mask) == ($privateIps[$i] & $mask)) {
		$result = 0;
	    }
	}
    }
    return $result;
}

sub is_public_interface($)
{
    my ($key) = @_;
    my $result = (exists($interfaceList{$key})
		  && $interfaceList{$key}->role() eq "ctrl"
		  && is_routable($interfaceList{$key}->IP()));
    return $result;
}

662
663
664
665
666
667
668
669
670
671
672
# Push a value onto an array contained within a hash
sub hashpush($$$)
{
    my ($hashref, $key, $value) = @_;
    if (! exists($hashref->{$key})) {
	$hashref->{$key} = [$value];
    } else {
	push(@{ $hashref->{$key} }, $value);
    }
}

673
674
675
676
677
678
###############################################################################
# Physical Nodes. These contain the all of the per-node state used to
# generate ptop or xml files.

package libptop::pnode;

679
680
use libdb qw(TBOSID TB_OPSPID TBDB_NODESTATE_ISUP TBDB_NODESTATE_PXEWAIT
             TBDB_NODESTATE_POWEROFF TBDB_NODESTATE_ALWAYSUP);
681
682
683
684
685
686
687
688
689

sub Create($$)
{
    my ($class, $row) = @_;

    my $self = {};

    $self->{'NODE'} = Node->LookupRow($row);
    $self->{'PTYPES'} = [];
690
    $self->{'FEATURES'} = [];
691
    $self->{'FLAGS'} = {};
692
693
    $self->{'GLOBALCOUNT'} = undef;
    $self->{'AUXTYPES'} = {};
694
    $self->{'CONNECTIONS'} = {};
695
    $self->{'INTERFACES'} = [];
696
697
    $self->{'STATUS'} = undef;
    $self->{'WIDEAREA'} = undef;
698
699
700
701
702
703

    bless($self, $class);
    return $self;
}

# Accessors
704
705
706
707
sub name($)        { return $_[0]->{'NODE'}->node_id(); }
sub node($)        { return $_[0]->{'NODE'}; }
sub type($)        { return $_[0]->node()->NodeTypeInfo(); }
sub globalcount($) { return $_[0]->{'GLOBALCOUNT'}; }
708
sub status($)      { return $_[0]->{'STATUS'}; }
709
710

sub set_globalcount { $_[0]->{'GLOBALCOUNT'} = $_[1]; }
711
712
sub set_status($)   { $_[0]->{'STATUS'} = $_[1]; }
sub set_widearea($) { $_[0]->{'WIDEAREA'} = $_[1]; }
713

714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
sub get_basetype($)
{
    my ($self) = @_;
    my $result = undef;
    $self->node()->NodeTypeAttribute("forwarding_protocols", \$result);
    if (! defined($result)) {
	$result = "ethernet";
    }
    return $result;
}

sub is_exclusive($)
{
    my ($self) = @_;
    return ! ($self->node()->sharing_mode());
}

731
sub widearea($$)
732
{
733
734
735
736
737
738
739
740
741
742
743
    my ($self, $key) = @_;
    my $result = undef;
    if (defined($self->{'WIDEAREA'})) {
	$result = $self->{'WIDEARE'}->{$key};
    }
    return $result;
}

sub isreserved($)
{
    my ($self) = @_;
744
    my $node = $self->node();
745
746
747
    my $pre_pid = $node->reserved_pid();
    my $reserved_eid = $node->eid();
    my $reserved_pid = $node->pid();
748
749
    # A node is reserved to a project if it has a reserved_pid, and
    # that pid is not the user's pid.
750
751
752
    my $pre_reserved = defined($pre_pid)
	               && (! defined($user_project)
			   || $user_project ne $pre_pid);
753
754
755
756
757
758
759
    # A node is reserved to an experiment if it has a reserved_eid,
    # a reserved_pid, and one of those is not the user's pid/eid.
    my $exp_reserved = defined($reserved_eid)
	               && defined($reserved_pid)
	               && (! defined($exempt_eid)
			   || $reserved_eid ne $exempt_eid
			   || $reserved_pid ne $user_project);
760
761
762
763
764
765
766
    return $pre_reserved || $exp_reserved;
}

sub available($;$)
{
    my ($self, $tagRef) = @_;
    my $node = $self->node();
767
768
769
770
771
772
773
774
775
776

    my $typeallowed = (libptopnew::TypeAllowed($node->class())
		       && libptopnew::TypeAllowed($node->type()));

    # Nodes are free if they are nonlocal, or if they are up and
    # not-reserved, or if they are shared.
    #
    # And they must also be allowed for the current project by the
    # nodetypeXpid_permissions table.
    my $isfree = ((!$self->islocal()
777
		   || (! $self->isreserved() && $self->isup())
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
		   || $self->isshared())
		  && $typeallowed);

    # And if they are a subnode, their parent must be available:

    # A bit of recursion to ensure that subnodes are only listed as
    # available if their parent is. The tags bit is to try to ensure
    # we don't loop forever if there is a subnode-loop. See also willPrint().
    if ($isfree && $node->issubnode()) {
	my %tags = {};
	if (defined($tagRef)) {
	    %tags = %{ $tagRef };
	}
	$tags{$self->name()} = 1;
	my $parent = $node->phys_nodeid();
	if (! exists($tags{$parent})) {
	    $isfree = $isfree && $nodeList{$parent}->available(\%tags);
	}
    }
    return $isfree;
}

sub isswitch($)
{
    my ($self) = @_;
    my $role = $self->node()->role();
    return ($role eq 'testswitch' || $role eq 'widearea_switch'
	    || ($role eq 'testnodefoo' && $self->node()->isswitch()));
}

sub islocal($)
{
    my ($self) = @_;
    my $node = $self->node();
    my $isremotenode = $node->isremotenode();
    my $wa_attrvalue = $node->NodeTypeAttribute('dedicated_widearea');
    return ( $node->role() eq 'testnode'
	     && ((! defined($isremotenode) || $isremotenode == 0)
		 || (defined($wa_attrvalue) && $wa_attrvalue == 1)));
}

sub iswidearea($)
{
    my ($self) = @_;
    my $node = $self->node();
    my $isremotenode = $node->isremotenode();
    my $isvirtnode = $node-> isvirtnode();
    my $wa_attrvalue = $node->NodeTypeAttribute('dedicated_widearea');
    return ($node->role() eq 'testnode'
	    && defined($isremotenode)
	    && $isremotenode == 1
	    && (! defined($isvirtnode) || $isvirtnode == 0)
	    && $node->type() ne 'pcfedphys'
	    && (! defined($wa_attrvalue) || $wa_attrvalue == 0));
}

sub isshared($)
{
    my ($self) = @_;
    my $node = $self->node();
    # In shared mode, allow allocated nodes whose sharing_mode is set.
    return (defined($node->erole())
	    && $node->erole() eq "sharedhost"
	    && $self->isup());
}

sub isup($)
{
    my ($self) = @_;
    my $eventstate = $self->node()->eventstate();
    return defined($eventstate)
	&& ($eventstate eq TBDB_NODESTATE_ISUP()
	    || $eventstate eq TBDB_NODESTATE_PXEWAIT()
	    || $eventstate eq TBDB_NODESTATE_POWEROFF()
	    || $eventstate eq TBDB_NODESTATE_ALWAYSUP());
}

sub willPrint($;$)
{
    my ($self, $tagRef) = @_;
    my $node = $self->node();

    # In geni mode, disallow nodes tagged protogeni_exclude from being printed.
    my $geniExclude = 0;
    $node->NodeAttribute("protogeni_exclude", \$geniExclude);
    my $geniok = (! defined($geniExclude) || $geniExclude == 0);
    my $result = ($self->isswitch()
		  || $self->islocal()
		  || ($self->iswidearea() && $print_widearea)
		  || ($self->isshared() && $print_shared))
	&& (! $available_only || $self->available($)))
	&& (! $genimode || $geniok);

    # A bit of recursion to ensure that subnodes are only printed if
    # their parent is. The tags bit is to try to ensure we don't loop
    # forever if there is a subnode-loop. See also available()).
    if ($result && $node->issubnode()) {
	my %tags = {};
	if (defined($tagRef)) {
	    %tags = %{ $tagRef };
	}
	$tags{$self->name()} = 1;
	my $parent = $node->phys_nodeid();
	if (! exists($tags{$parent})) {
	    $result = $result && $nodeList{$parent}->willPrint(\%tags);
	}
    }
    return $result;
}

888
sub addPType($$$;$)
889
{
890
891
892
    my ($self, $newname, $newvalue, $newstatic) = @_;
    push(@{ $self->{'PTYPES'} },
	 libptop::pnode_type->Create($newname, $newvalue, $newstatic));
893
894
}

895
sub addFeature($$$;$$)
896
{
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
    my ($self, $newname, $newvalue, $newflag, $newvolatile) = @_;
    push(@{ $self->{'FEATURES'} },
	 libptop::feature->Create($newname, $newvalue,
				  $newflag, $newvolatile));
}

sub addFeatureString($$)
{
    my ($self, $newfeature) = @_;
    push(@{ $self->{'FEATURES'} },
	 libptop::feature->CreateFromString($newfeature));
}

sub addFlag($$$)
{
    my ($self, $key, $value) = @_;
913
    $self->{'FLAGS'}->{$key} = $value;
914
915
916
917
918
919
}

sub addAuxtype($$$)
{
    my ($self, $key, $value) = @_;
    $self->{'AUXTYPES'}->{$key} = $value;
920
921
}

922
923
924
925
926
927
sub addConnection($$)
{
    my ($self, $name) = @_;
    $self->{'CONNECTIONS'}->{$name} = 1;
}

928
929
930
931
932
933
sub addInterface($$)
{
    my ($self, $name) = @_;
    push(@{ $self->{'INTERFACES'} }, $name);
}

934
935
936
937
938
939
940
941
sub processSwitch($)
{
    my ($self) = @_;
    if (! $self->isswitch()) {
	return;
    }

    # Add switch and lan types
942
943
944
    $self->addPType("switch", 1);
    if (!(defined($MAINSITE) && $MAINSITE && $self->name() eq "procurve1")) {
	$self->addPType("lan", undef, 1);
945
946
947
    }

    # Add real-switch feature
948
    $self->addFeature('real-switch', 0);
949
950
951
952
953
954
955
956
}

sub processLocal($)
{
    my ($self) = @_;
    if (! $self->islocal()) {
	return;
    }
957
958
959
960
961
962
963
964
965
    my $node = $self->node();
    my $type = $self->type();
    # XXX temporary hack until node reboot avoidance 
    # is available. Nodes running the FBSD-NSE image
    # will have a feature def-osid-fbsd-nse 0.0
    # This is used by assign to prefer these pnodes
    # first before using others.
    if($node->def_boot_osid() && 
       $node->def_boot_osid() eq  TBOSID(TB_OPSPID, "FBSD-NSE")) { 
966
	$self->addFeature('FBSD-NSE', 0.0);
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
    }
    $self->addPType($node->type(), 1);
    # Might be equal, which assign would sum as two, not one!
    #
    # XXX: Temporary hack - don't mark switches that are testnodes
    # as having class 'switch' - assign treats those specially. We
    # use the knowledge that 'real' switches don't hit this point!
    #
    if ($node->type() ne $node->class() && $node->class() ne "switch") {
	$self->addPType($node->class(), 1);
    }

    $self->addDelayCapacity();
    if ($node->sharing_mode()) {
	$self->addShared();
    }
    $self->processAuxtypes();
984
    $self->processOsFeatures();
985
986
987
988
989
990
991
992
    $self->processConnections();
    # This is for the case that we are modifying an existing experiment - tell
    # assign to prefer nodes the user has already allocated
    if (defined($exempt_eid) && $available_only
	&& defined($node->eid()) && defined($node->pid())) {
	$self->addFeature('already_reserved', 0);
    }
    $self->processSubnode();
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
}

sub addDelayCapacity($)
{
    my ($self) = @_;
    my $delay = $self->type()->delay_capacity();
    if (defined($delaycap_override) &&
	$delaycap_override > 0 &&
	$delaycap_override < $delay) {
	$delay = $delaycap_override
    }
    $self->addPType("delay", $delay);
    $self->addPType("delay-".$self->node()->type(), $delay);
    
}

#
# Shared mode features
#
sub addShared($)
{
    my ($self) = @_;
    my $node = $self->node();
    #
    # Add a feature that says this node should not be picked
    # unless the corresponding desire is in the vtop. This
    # allows the node to be picked, subject to other type constraints.
    #
1021
    $self->addFeature('pcshared', 1.0, undef, 1);
1022
1023
1024
1025
1026
1027
1028

    #
    # The pool daemon may override the share weight.
    #
    my $sharedweight = undef;
    $node->NodeAttribute("shared_weight", \$sharedweight);
    if (defined($sharedweight)) {
1029
	$self->addFeature('shareweight', $sharedweight);
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
    } else {
	#
	# The point of this feature is to have assign favor shared nodes
	# that already have nodes on them, so that they are well packed.
	# Shared nodes with just a few vnodes on them are avoided so that
	# they will free up eventually. 
	#
	my $maxvnodes = 10;
	my $weight    = 0.5;
	my $gcount    = 0.0;
	if (defined($self->globalcount())) {
	    $gcount = $self->globalcount();
	}

	if (exists($self->{'AUXTYPES'}->{'pcvm'})) {
	    $maxvnodes = $self->{'AUXTYPES'}->{'pcvm'};
	}

	#
	# No point in the feature if no room left. 
	#
	if ($maxvnodes > $gcount) {
	    my $factor = ($gcount / $maxvnodes);
	    if ($factor < 0.25) {
		$weight = 0.8;
	    }
	    elsif ($factor > 0.75) {
		$weight = 0.1;
	    }
	    else {
		$weight = 0.3;
	    }
1062
	    #addFeature('shareweight', $weight);
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
	}
    }
}

#
# Add any auxiliary types
#
sub processAuxtypes($)
{
    my ($self) = @_;
    my $node = $self->node();
    my $needvirtgoo = 0;
    foreach my $auxtype (keys(%{ $self->{'AUXTYPES'} })) {
	my $count = $self->{'AUXTYPES'}->{$auxtype};
	my $realtypename;

	# Map an auxtype back to its real type, unless it is a real type.
	if (defined($auxtypemap{$auxtype})) {
	    $realtypename = $auxtypemap{$auxtype};
	} else {
	    $realtypename = $auxtype;
	}
	my $realtype = NodeType->Lookup($realtypename);
	my $is_virtual = ($realtype->isvirtnode() && $count > 0);
	if (! $is_virtual) {
	    $self->addPType($auxtype, $count);
	} elsif ($print_virtual) {
	    $needvirtgoo = 1;
	    #
	    # If the node is shared, must subtract the current global count
	    # from the max first, to see if there is any room left.
	    #
	    if ($node->sharing_mode() && defined($self->globalcount())) {
		$count -= $self->globalcount();
	    }
	    if (defined($multiplex_override)
		&& $multiplex_override <= $count) {
		$count = $multiplex_override;
	    }

	    #
	    # Add in machine specific auxtypes that use the same count.
	    #
	    $self->addPType($node->type()."-vm", $count);

	    # And a legacy type.
	    my $legacy_type = $node->type();
	    if (($legacy_type =~ s/pc/pcvm/)) {
		$self->addPType($legacy_type, $count);
	    }
	    $self->addPType($auxtype, $count);
	}
    }
    if ($needvirtgoo) {
	$self->processVirtGoo();
    }
    my $simcap = $self->type()->simnode_capacity();
    my $needsim = ($print_sim && defined($simcap) && $simcap > 0);
    if ($needsim) {
	$self->processSim($simcap);
    }
    if ($needsim || $needvirtgoo) {
	$self->addPType("lan", undef, 1);
    }
    if (($needvirtgoo && ! $node->sharing_mode())
	|| $needsim) {
	$self->processCpuRam();
    }
}

sub processVirtGoo($)
{
    my ($self) = @_;
    # Add trivial bw spec., but only if the node type has it
    my $trivspeed = $self->type()->trivlink_maxspeed();
    if ($trivspeed) {
	$self->addFlag("trivial_bw", $trivspeed);
    }
    if (! $self->node()->sharing_mode()) {
	# This number can be use for fine-tuning packing
1143
	$self->addFeature('virtpercent', 100, libptopnew::FD_ADDITIVE());
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
    }
    # Put this silly feature in so that we can try to keep vnodes
    # on the same pnode they were before - but only if updating
    if (defined($exempt_eid)) {
	$self->addFeature($self->node()->node_id(), 0.0);
    }
}

sub processSim($$)
{
    my ($self, $simcap) = @_;
    #
    # Use user specified multiplex factor
    #
    my $cap = $simcap;
    if (defined($multiplex_override) && $multiplex_override <= $simcap) {
	$cap = $multiplex_override;
    }
    $self->addPType("sim", $cap);
    # Add trivial bw spec.
    $self->addFlag("trivial_bw", 100000);
}

sub processCpuRam($)
{
    my ($self) = @_;
    my $cpu_speed = $self->type()->frequency();
    my $ram = $self->type()->memory();
    # Add CPU and RAM information
1173
    $self->addFeature('cpu', $cpu_speed, libptopnew::FD_ADDITIVE())
1174
	if (defined($cpu_speed));
1175
    $self->addFeature('ram', $ram, libptopnew::FD_ADDITIVE())
1176
	if (defined($ram));
1177
1178
    $self->addFeature('cpupercent', 92, libptopnew::FD_ADDITIVE()); # XXX Hack
    $self->addFeature('rampercent', 80, libptopnew::FD_ADDITIVE()); # XXX Hack
1179
1180
}

1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
#
# Add in OS features.
#
sub processOsFeatures($)
{
    my ($self) = @_;
    my $node = $self->node();
    if ($node->sharing_mode()) {
	#
	# A shared node is running just one OS, and we put that in
	# so that the user can specify which of the current VM types
	# is wanted.
	#
	my $osid = $node->def_boot_osid();
1195
	$self->addFeature('OS-'.$osid, 0.5);
1196
1197
1198
	# Add any subOSes the shared node osid can support
	if (defined($osid_subosid{$osid})) {
	    foreach my $subosid (@{ $osid_subosid{$osid} }) {
1199
		$self->addFeature('OS-'.$osid.'-'.$subosid, 0);
1200
1201
1202
	    }
	}
    } elsif (exists($type_osid{$node->type()})) {
1203
1204
#	my $default = $self->type()->default_osid();
#	my $default_used = 0;
1205
1206
1207
1208
1209
	#
	# Add in features for all of the OSes that this node (as
	# evidenced by its type) can support
	#
	foreach my $o1 (@{ $type_osid{$node->type()} }) {
1210
	    $self->addFeature('OS-'.$o1, 0);
1211
	    foreach my $o2 (@{ $osid_subosid{$o1} }) {
1212
		$self->addFeature('OS-'.$o1.'-'.$o2, 0);
1213
	    }
1214
1215
1216
1217
#	    if ($o1 eq $default) {
#		print STDERR "Equal: OS-".$o1."\n";
#		$default_used = 1;
#	    }
1218
	}
1219
1220
1221
1222
#	if (! $default_used) {
#	    print STDERR "OS-".$default."\n";
#	    $self->addFeature('OS-'.$default, 0);
#	}
1223
1224
1225
1226
1227
1228
1229
1230
1231
    } elsif (! $self->type()->imageable() &&
	     defined($self->type()->default_osid())) {
	#
	# If node is not imageable (and thus no entries in osidtoimageid,
	# then assume it always has its default OSID loaded and ready to
	# go, so that assign will agree to the allocation (assign_wrapper
	# adds a desire that says it has to be running the OSID the user
	# has selected, or the default OSID from the node_types table).
	#
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
	$self->addFeature('OS-'.$self->type()->default_osid(), 0);
    }
}

sub processConnections($)
{
    my ($self) = @_;
    if (! $self->node()->sharing_mode()) {
	foreach my $name (keys(%{ $self->{'CONNECTIONS'} })) {
	    $self->addFeature('connected-to-'.$name, 0.0);
	}
    }
}

sub processSubnode($)
{
    my ($self) = @_;
    my $node = $self->node();
    if ($node->issubnode()) {
	$self->addFlag('subnode_of', $node->phys_nodeid());
1252
1253
1254
    }
}

1255
1256
1257
sub processWidearea($)
{
    my ($self) = @_;
1258
    my $node = $self->node();
1259
1260
1261
    if (! $self->iswidearea()) {
	return;
    }
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282

    #
    # Grab the global allocation count of vnodes on this pnode (if there
    # is one). This modifies the counts below.  If the count has already
    # been reached, then do not put this node into the ptop file.
    #
    my $maxvnodes = $self->type()->GetAttribute("global_capacity");
    
    if (defined($maxvnodes) && defined($self->globalcount())) {
	$maxvnodes -= $self->globalcount();
	if ($maxvnodes <= 0) {
	    return;
	}
    }

    #
    # Mark any nodes that are not up with a feature, so that they won't
    # normally get assigned. We want to include them, though, because we
    # allow people to do fix-node to down nodes
    #
    if (! defined($self->status())) {
1283
1284
1285
1286
	if ($debug) {
	    print STDERR "Widearea node does not have a status: ".
		$node->node_id()."\n";
	}
1287
1288
1289
	return;
    }
    if (! defined($node->eid()) || ! defined($node->pid())) {
1290
1291
1292
1293
	if ($debug) {
	    print STDERR "Widearea node is not reserved to an eid or pid".
		$node->node_id()."\n";
	}
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
	return;
    }
    if ($self->status() ne 'up' ||
	($node->eid() eq NODEDEAD_EID() || $node->pid() eq NODEDEAD_PID())) {
	if ($genimode) {
	    return;
	}
	$self->addFeature('down', 1);
    }

    my $site = $self->widearea('site');
    if ($site) {
	$self->addFeature($site, 0.99, libptopnew::FD_FIRSTFREE());
    }

    #
    # Add any auxiliary types.
    #
    foreach my $auxtype (keys(%{ $self->{'AUXTYPES'} })) {
	my $count = $self->{'AUXTYPES'}->{$auxtype};
	if (defined($maxvnodes) && $maxvnodes < $count) {
	    $count = $maxvnodes;
	}
	if (defined($multiplex_override) && $multiplex_override < $count) {
	    $count = $multiplex_override;
	}
	$self->addPType($auxtype, $count);
    }

    # Add trivial bw spec.
    $self->addFlag("trivial_bw", 400000);

    # Indicate that these nodes are beautiful and unique snowflakes
    $self->addFlag("unique", 1);

    $self->processOsFeatures();

    #
    # Put in a feature indicating whether or not this node has a bandwidth
    # cap
    #
    my $bwlimit = $self->widearea('bwlimit');
    if (!defined($bwlimit) || $bwlimit eq "-1") {
	$self->addFeature('nobwlimit', 0);
    } else {
	$self->addFeature('bwlimit', 0);
    }

1342
1343
}

1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
sub processTypeFeatures($)
{
    my ($self) = @_;
    if ($self->iswidearea()
	|| ($self->islocal() && ! $self->node()->sharing_mode())) {
	if (exists($typefeatures{$self->node()->type()})) {
	    foreach my $feature (@{ $typefeatures{$self->node()->type()} }) {
		$self->addFeatureString($feature);
	    }
	}
    }
}

1357
1358
1359
1360
1361
sub toString($)
{
    my ($self) = @_;
    my $result = "node " . $self->name();

1362
    # Print types
1363
1364
1365
    foreach my $type (@{ $self->{'PTYPES'} }) {
	$result .= " " . $type->toString();
    }
1366
1367
1368
1369
1370
1371
    $result .= " -";
    # Print features
    foreach my $feature (@{ $self->{'FEATURES'} }) {
	$result .= " " . $feature->toString();
    }
    $result .= " -";
1372
1373
1374
1375
1376
1377
1378
1379
1380
    foreach my $flag (keys(%{ $self->{'FLAGS'} })) {
	my $value = $self->{'FLAGS'}->{$flag};
	# Special case for the unique flag. :)
	if ($flag eq "unique") {
	    $result .= " $flag";
	} else {
	    $result .= " $flag:$value";
	}
    }
1381
1382
1383
1384
1385
1386
1387
1388
    return $result;
}

sub toXML($$)
{
    my ($self, $parent) = @_;
    my $xml = GeniXML::AddElement("node", $parent);
    my $urn = GeniHRN::Generate($OURDOMAIN, "node", $self->name());
1389
1390
1391
1392
1393
1394
1395
1396
1397
    my $exclusive = "false";
    if ($self->is_exclusive()) {
	$exclusive = "true";
    }
    my $available = "false";
    if ($self->available()) {
	$available = "true";
    }
    my $availablexml = GeniXML::AddElement("available", $xml);
1398
1399
1400
    if (GeniXML::IsVersion0($xml)) {
	GeniXML::SetText("component_manager_uuid", $xml, $cmurn);
	GeniXML::SetText("component_uuid", $xml, $urn);
1401
1402
1403
	my $exclusivexml = GeniXML::AddElement("exclusive", $xml);
	$exclusivexml->appendText($exclusive);
	$availablexml->appendText($available);
1404
1405
1406
    } else {
	GeniXML::SetText("component_manager_id", $xml, $cmurn);
	GeniXML::SetText("component_id", $xml, $urn);
1407
1408
	GeniXML::SetText("exclusive", $xml, $exclusive);
	GeniXML::SetText("now", $availablexml, $available);
1409
1410
1411
    }
    GeniXML::SetText("component_name", $xml, $self->name());

1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
    # Location
    my ($lat, $long, $country);

    if ($self->iswidearea()) {
	$lat = $self->node()->WideAreaInfo("latitude");
	$long = $self->node()->WideAreaInfo("longitude");
	$country = $self->node()->WideAreaInfo("country");
    }
    if (! defined($lat) || ! defined($long)) {
	$lat = $default_latitude;
	$long = $default_longitude;
    }
    if (! defined($country)) {
	$country = $default_country;
    }
    if (defined($lat) && defined($long) && defined($country)) {
	my $location = GeniXML::AddElement("location", $xml);
	GeniXML::SetText("country", $location, $country);
	GeniXML::SetText("longitude", $location, $long);
	GeniXML::SetText("latitude", $location, $lat);
    }

1434
    # Add types
1435
    foreach my $type (@{ $self->{'PTYPES'} }) {
1436
	$type->toXML($xml, $self->type());
1437
    }
1438
1439
1440
1441
    # Add features
    foreach my $feature (@{ $self->{'FEATURES'} }) {
	$feature->toXML($xml);
    }
1442
1443
1444
1445
    # Add interfaces
    foreach my $interface (@{ $self->{'INTERFACES'} }) {
	$self->interfaceToXML($xml, $interface);
    }
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466

    if (! GeniXML::IsVersion0($xml)) {
	foreach my $flag (keys(%{ $self->{'FLAGS'} })) {
	    my $value = $self->{'FLAGS'}->{$flag};
	    if ($flag eq 'trivial_bw') {
		my $triv = GeniXML::AddElement("trivial_bandwidth", $xml,
					       $GeniXML::EMULAB_NS);
		GeniXML::SetText("value", $triv, $value);
	    } elsif ($flag eq 'subnode_of') {
		my $suburn = GeniHRN::Generate($OURDOMAIN, "node", $value);
		my $relation = GeniXML::AddElement("relation", $xml);
		GeniXML::SetText("type", $relation, "subnode_of");
		GeniXML::SetText("component_id", $relation, $suburn);
	    } elsif ($flag eq 'unique') {
		GeniXML::AddElement("unique", $xml, $GeniXML::EMULAB_NS);
	    } elsif ($flag eq 'disallow_trivial_mix') {
		GeniXML::AddElement("disallow_trivial_mix", $xml,
				    $GeniXML::EMULAB_NS);
	    }
	}
    }
1467
1468
}

1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
sub interfaceToXML($$$)
{
    my ($self, $parent, $name) = @_;
    my $key = $self->node()->node_id() . ":" . $name;
    my $role = $interfaceList{$key}->role();
    my $urn = GeniHRN::GenerateInterface($OURDOMAIN, $self->node()->node_id(),
					 $name);
    my $xml = GeniXML::AddElement("interface", $parent);
    GeniXML::SetText("component_id", $xml, $urn);
    if ($role eq "ctrl") {
	GeniXML::SetText("role", $xml, "control");
    } elsif ($role eq "expt") {
	GeniXML::SetText("role", $xml, "experimental");
    }
    if (libptopnew::is_public_interface($key)) {
	my $ip = $interfaceList{$key}->IP();
	GeniXML::SetText("public_ipv4", $xml, $ip);
   }
    if (! GeniXML::IsVersion0($xml)) {
	my $child = GeniXML::AddElement("interface", $xml,
					$GeniXML::EMULAB_NS);
	GeniXML::SetText("name", $child, $name);
    }
}

1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
###############################################################################
# Physical Node Type. These are the types which are printed out in the
# ptopgen file. Note that there is not a one-to-one correspondence
# between these types and the 'type' of the node in the database.

package libptop::pnode_type;

sub Create($$;$$)
{
    my ($class, $name, $slots, $isstatic) = @_;

    my $self = {};

    $self->{'NAME'} = $name;
    $self->{'SLOTS'} = $slots;
    $self->{'ISSTATIC'} = 0;
    if (defined($isstatic)) {
	$self->{'ISSTATIC'} = 1;
    }

    bless($self, $class);
    return $self;
}

# Accessors
sub name($)       { return $_[0]->{'NAME'}; }
sub slots($)      { return $_[0]->{'SLOTS'}; }
sub isstatic($)   { return $_[0]->{'ISSTATIC'}; }

sub toString($)
{
    my ($self) = @_;
    my $result = "";
    if ($self->isstatic()) {
	$result .= "*";
    }
    $result .= $self->name().":";
    if (defined($self->slots())) {
	$result .= $self->slots();
    } else {
	$result .= "*";
    }
    return $result;
}

sub toXML($$)
{
1541
    my ($self, $parent, $mainType) = @_;
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
    my $slots = $self->slots();
    if (! defined($slots)) {
	$slots = "unlimited";
    }
    my $xml;
    if (GeniXML::IsVersion0($parent)) {
	$xml = GeniXML::AddElement("node_type", $parent);
	GeniXML::SetText("type_name", $xml, $self->name());
	GeniXML::SetText("type_slots", $xml, $slots);
	if ($self->isstatic()) {
	    GeniXML::SetText("static", $xml, "true");
	}
1554
1555
1556
1557
1558
1559
	# Add OSIDs for version 0.2. These are global to the node
	# rather than inside a particular type tag.
	if (GeniXML::GetXmlVersion($parent) eq $GeniXML::RSPEC_0_2
	    && $mainType eq $self->name()) {
	    $self->osidToXML($parent, $mainType);
	}
1560
1561
1562
1563
1564
    } else {
	my $sliverxml;
	if ($self->name() eq "pc") {
	    $sliverxml = GeniXML::AddElement("sliver_type", $parent);
	    GeniXML::SetText("name", $sliverxml, "raw-pc");
1565
	    $self->osidToXML($sliverxml, $mainType);
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
	}
	if ($self->name() eq "pcvm") {
	    $sliverxml = GeniXML::AddElement("sliver_type", $parent);
	    GeniXML::SetText("name", $sliverxml, "emulab-openvz");
	}
	$xml = GeniXML::AddElement("hardware_type", $parent);
	GeniXML::SetText("name", $xml, $self->name());
	my $elab = GeniXML::AddElement("node_type", $xml, $GeniXML::EMULAB_NS);
	GeniXML::SetText("type_slots", $elab, $slots);
	if ($self->isstatic()) {
	    GeniXML::SetText("static", $elab, "true");
	}
    }
}

1581
1582
1583
1584
1585
1586
1587
sub osidToXML($$$)
{
    my ($self, $parent, $type) = @_;
    my $default = $type->default_osid();
    foreach my $osid (@{ $type_osid{$type->type()} }) {
	my $os = $osinfo{$osid};
	if (! defined($os)) {
1588
1589
1590
	    if ($debug) {
		print STDERR "Undefined osid: ".$osid."\n";
	    }
1591
1592
1593
	    next;
	}
	if ($os->protogeni_export() ||
1594
	    (defined($default) && $default eq $osid)) {
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
	    # Fill out new disk image tag
	    my $disk = GeniXML::AddElement("disk_image", $parent);
	    GeniXML::SetText("name", $disk, $os->osname());
	    GeniXML::SetText("os", $disk, $os->OS());
	    GeniXML::SetText("version", $disk, $os->version());
	    GeniXML::SetText("description", $disk, $os->description());
	    if (defined($default) && $default eq $type->type()) {
		GeniXML::SetText("default", $disk, "true");
	    }
	}
    }
}

1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
###############################################################################
# Physical Node Type. These are the types which are printed out in the
# ptopgen file. Note that there is not a one-to-one correspondence
# between these types and the 'type' of the node in the database.

package libptop::feature;

sub CreateFromString($$)
{
    my ($class, $str) = @_;

    my $self = libptop::feature->Create($class, undef, undef);

    my ($name, $value) = split(/:/, $str, 2);
    my $flags = "";
    if ($name =~ /^\?\+/) {
	$self->set_additive();
	$name = substr($name, 2);
1626
    } elsif ($name =~ /^\*&/) {
1627
1628
	$self->set_firstfree();
	$name = substr($name, 2);
1629
    } elsif ($name =~ /^\*!/) {
1630
1631
	$self->set_onceonly();
	$name = substr($name, 2);
1632
1633
    } elsif ($value >= 1.0) {
	$self->set_violatable();
1634
1635
1636
1637
1638
1639
1640
    }
    $self->{'NAME'} = $name;
    $self->{'VALUE'} = $value;

    return $self;
}

1641
sub Create($$$;$$)
1642
{
1643
    my ($class, $name, $value, $flag, $violatable) = @_;
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654

    my $self = {};

    $self->{'NAME'} = $name;
    $self->{'VALUE'} = $value;
    $self->{'VIOLATABLE'} = 0;
    $self->{'ADDITIVE'} = 0;
    $self->{'FIRSTFREE'} = 0;
    $self->{'ONCEONLY'} = 0;

    bless($self, $class);
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668

    if (defined($violatable)) {
	$self->set_violatable();
    }
    if (defined($flag)) {
	if ($flag eq libptopnew::FD_ADDITIVE()) {
	    $self->set_additive();
	} elsif ($flag eq libptopnew::FD_FIRSTFREE()) {
	    $self->set_firstfree();
	} elsif ($flag eq libptopnew::FD_ONCEONLY()) {
	    $self->set_onceonly();
	}
    }

1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
    return $self;
}

sub set_violatable($)  { $_[0]->{'VIOLATABLE'} = 1; }
sub set_additive($)    { $_[0]->{'ADDITIVE'} = 1; }
sub set_firstfree($)   { $_[0]->{'FIRSTFREE'} = 1; }
sub set_onceonly($)    { $_[0]->{'ONCEONLY'} = 1; }

sub violatable($)      { return $_[0]->{'VIOLATABLE'}; }
sub additive($)        { return $_[0]->{'ADDITIVE'}; }
sub firstfree($)       { return $_[0]->{'FIRSTFREE'}; }
sub onceonly($)        { return $_[0]->{'ONCEONLY'}; }

sub toString($)
{
    my ($self) = @_;
    my $result = "";
    if ($self->violatable()) {
	# No representation as flat string
    }
    if ($self->additive()) {
	$result .= "?+";
    } elsif ($self->firstfree()) {
	$result .= "*&";
    } elsif ($self->onceonly()) {
	$result .= "*!";
    }
    $result .= $self->{'NAME'}.':'.$self->{'VALUE'};
    return $result;
}

sub toXML($$)
{
    my ($self, $parent) = @_;
    if (! GeniXML::IsVersion0($parent)) {
	my $xml = GeniXML::AddElement("fd", $parent, $GeniXML::EMULAB_NS);
	GeniXML::SetText("name", $xml, $self->{'NAME'});
	GeniXML::SetText("weight", $xml, $self->{'VALUE'});
	if ($self->violatable()) {
	    GeniXML::SetText("violatable", $xml, "true");
	}
	if ($self->additive()) {
	    GeniXML::SetText("local_operator", $xml, "+");
	} elsif ($self->firstfree()) {
	    GeniXML::SetText("global_operator", $xml, "FirstFree");
	} elsif ($self->onceonly()) {
	    GeniXML::SetText("global_operator", $xml, "OnceOnly");
	}
    }
}

1720
1721
1722
1723
1724
1725
1726
###############################################################################
# Physical Wires. These contain the all of the per-link state used to
# generate ptop or xml files.

package libptop::plink;

use libdb qw(TBOSID TB_OPSPID);
1727
use Math::BigInt;
1728

1729
sub Create($)
1730
1731
1732
1733
1734
1735
1736
{
    my ($class) = @_;

    my $self = {};
    $self->{'NAME'} = undef;
    $self->{'SOURCE'} = undef;
    $self->{'SOURCE_IF'} = undef;
1737
1738
    $self->{'SOURCE_CARD'} = undef;
    $self->{'SOURCE_PORT'} = undef;
1739
1740
    $self->{'DEST'} = undef;
    $self->{'DEST_IF'} = undef;
1741
1742
1743
    $self->{'DEST_CARD'} = undef;
    $self->{'DEST_PORT'} = undef;
    $self->{'BW'} = new Math::BigInt 0;
1744
1745
1746
1747
1748
1749
1750
1751
1752
    $self->{'DELAY'} = 0;
    $self->{'LOSS'} = 0.0;
    $self->{'TYPES'} = [];
    $self->{'INTERCONNECT'} = 0;

    bless($self, $class);
    return $self;
}

1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
sub CreateTrunk($$$$)
{
    my ($class, $name, $source, $dest) = @_;
    my $self = $class->Create();
    $self->set_name($name);
    $self->set_source($source);
    $self->set_sourceif($dest);
    $self->set_dest($dest);
    $self->set_destif($source);
    $self->set_interconnect();
1763
    $self->add_type("ethernet");
1764
1765
1766
    return $self;
}

1767
1768
1769
sub name($)             { return $_[0]->{'NAME'}; }
sub source($)           { return $_[0]->{'SOURCE'}; }
sub sourceif($)         { return $_[0]->{'SOURCE_IF'}; }
1770
1771
sub sourcecard($)       { return $_[0]->{'SOURCE_CARD'}; }
sub sourceport($)       { return $_[0]->{'SOURCE_PORT'}; }
1772
1773
sub dest($)             { return $_[0]->{'DEST'}; }
sub destif($)           { return $_[0]->{'DEST_IF'}; }
1774
1775
sub destcard($)         { return $_[0]->{'DEST_CARD'}; }
sub destport($)         { return $_[0]->{'DEST_PORT'}; }
1776
1777
1778
1779
1780
1781
1782
1783
1784
sub bw($)               { return $_[0]->{'BW'}; }
sub delay($)            { return $_[0]->{'DELAY'}; }
sub loss($)             { return $_[0]->{'LOSS'}; }
sub types($)            { return $_[0]->{'TYPES'}; }
sub interconnect($)     { return $_[0]->{'INTERCONNECT'}; }

sub set_name($$)        { $_[0]->{'NAME'} = $_[1]; }
sub set_source($$)      { $_[0]->{'SOURCE'} = $_[1]; }
sub set_sourceif($$)    { $_[0]->{'SOURCE_IF'} = $_[1]; }
1785
1786
sub set_sourcecard($$)  { $_[0]->{'SOURCE_CARD'} = $_[1]; }
sub set_sourceport($$)  { $_[0]->{'SOURCE_PORT'} = $_[1]; }
1787
1788
sub set_dest($$)        { $_[0]->{'DEST'} = $_[1]; }
sub set_destif($$)      { $_[0]->{'DEST_IF'} = $_[1]; }
1789
1790
sub set_destcard($$)    { $_[0]->{'DEST_CARD'} = $_[1]; }
sub set_destport($$)    { $_[0]->{'DEST_PORT'} = $_[1]; }
1791
1792
1793
1794
1795
1796
1797
1798
1799
sub set_bw($$)          { $_[0]->{'BW'} = $_[1]; }
sub set_interconnect($) { $_[0]->{'INTERCONNECT'} = 1; }

sub add_type($$)
{
    my ($self, $type) = @_;
    push(@{ $self->{'TYPES'} }, $type);
}

1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
sub willPrint($)
{
    my ($self) = @_;
    my $bwok = $self->bw() > 0;
    my $node1 = $nodeList{$self->source()};
    my $node2 = $nodeList{$self->dest()};
    my $nodesok = defined($node1) && defined($node2)
	&& $node1->willPrint() && $node2->willPrint();
    return $bwok && $nodesok;
}

sub addTrunk($$$)
{
    my ($self, $sourcebw, $destbw) = @_;
    my $bw = $sourcebw;
    if ($destbw < $sourcebw) {
	$bw = $destbw;
    }
    $self->set_bw($self->bw() + $bw);
}

# Figure out what kind of link this is and then dispatch to the proper
# function to find out its properties.
sub processLink($)
{
    my ($self) = @_;
    # This is a node/node or switch/node link
    my $source = $nodeList{$self->source()};
    my $dest = $nodeList{$self->dest()};
    if ($source->isswitch()) {
	# This is a switch/node link
	$self->processSwitchNode($self->source(), $self->dest(),
				 $self->destif());
    } elsif ($dest->isswitch()) {
	# This is a node/switch link
	$self->processSwitchNode($self->dest(), $self->source(),
				 $self->sourceif());
    } else {
	# This is a node/node link
	$self->processNodeNode();
    }
}

sub standardName($)
{
    my ($self) = @_;
    $self->set_name("link-".$self->source().":".$self->sourceif()."-".
		    $self->dest().":".$self->destif());
}

sub processSwitchNode($$$$)
{
    my ($self, $switch, $node, $nodeif) = @_;
1853
1854
    my $switchRef = $nodeList{$switch};
    my $nodeRef = $nodeList{$node};
1855
1856
    $self->standardName();
    $self->set_bw(libptopnew::NodeBandwidth($node, $nodeif));
1857
1858
1859
1860
1861
1862
    my $basetype = $nodeRef->get_basetype();
    $self->add_type($basetype);
    $self->add_type($basetype."-".$switchRef->node()->node_id());
    $self->add_type($basetype."-".$self->bw());
    my $ifaceType = $interfaceList{"$node:$nodeif"}->type();
    $self->add_type($basetype."-".$ifaceType);
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
}

sub processNodeNode($)
{
    my ($self) = @_;
    $self->standardName();
    my $sourcebw = libptopnew::NodeBandwidth($self->source(),
					     $self->sourceif());
    my $destbw = libptopnew::NodeBandwidth($self->dest(), $self->destif());
    my $bw = $sourcebw;
    if ($destbw < $sourcebw) {
	$bw = $destbw;
    }
    $self->set_bw($bw);
1877
    $self->add_type("ethernet");
1878
1879
}

1880
1881
1882
1883
1884
1885
1886
sub toString($)
{
    my ($self) = @_;
    my $result = "link ";
    $result .= $self->name() . " ";
    $result .= $self->source() . ":" . $self->sourceif() . " ";
    $result .= $self->dest() . ":" . $self->destif() . " ";
1887
1888
1889
    $result .= $self->bw()->bstr() . " ";
    $result .= $self->delay() . " ";
    $result .= $self->loss() . " ";
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
    $result .= "1 " . join(" ", @{ $self->types() });
    return $result;
}

sub toXML($$)
{
    my ($self, $parent) = @_;
    my $xml = GeniXML::AddElement("link", $parent);
    my $urn = GeniHRN::Generate($OURDOMAIN, "link", $self->name());
    my $cmurn = GeniHRN::Generate($OURDOMAIN, "authority", "cm");
    if (GeniXML::IsVersion0($xml)) {
	GeniXML::SetText("component_manager_uuid", $xml, $cmurn);
	GeniXML::SetText("component_uuid", $xml, $urn);
	my $bw = GeniXML::AddElement("bandwidth", $xml);
1904
	$bw->appendText($self->bw()->bstr());
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
	my $latency = GeniXML::AddElement("latency", $xml);
	$latency->appendText($self->delay());
	my $loss = GeniXML::AddElement("packet_loss", $xml);
	$loss->appendText($self->loss());
    } else {
	my $cm = GeniXML::AddElement("component_manager", $xml);
	GeniXML::SetText("name", $cm, $cmurn);
	GeniXML::SetText("component_id", $xml, $urn);
	$self->propertyToXml($xml, $self->source(), $self->sourceif(),
			     $self->dest(), $self->destif(),
1915
1916
			     $self->bw()->bstr(), $self->delay(),
			     $self->loss());
1917
1918
	$self->propertyToXml($xml, $self->dest(), $self->destif(),
			     $self->source(), $self->sourceif(),