This file is indexed.

/usr/share/arc/CEinfo.pl is in nordugrid-arc-arex 5.3.0~rc1-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
#!/usr/bin/perl -w

package CEInfo;

########################################################
# Driver for information collection
########################################################

use File::Basename;
use Getopt::Long;
use Sys::Hostname;
use Data::Dumper;
use Cwd;

## enable this below to dump datastructures
## Note: Concise is not an ARC dependency!
## must be installed separately.
#use Data::Dumper::Concise;
## usage:
# print Dumper($datastructure); 

use strict;

# Some optional features that may be unavailable in older Perl versions.
# Should work with Perl v5.8.0 and up.
BEGIN {
    # Makes sure the GLUE document is valid UTF8
    eval {binmode(STDOUT, ":utf8")};
    # Used for reading UTF8 encoded grid-mapfile
    eval {require Encode; import Encode "decode"};
    # Fall back to whole-second precision if not avaiable
    eval {require Time::HiRes; import Time::HiRes "time"};
}

BEGIN {
    my $pkgdatadir = dirname($0);
    unshift @INC, $pkgdatadir;
}

# Attempt to recursively create directory
# takes absolute filename (absolute path and file name)
sub createdirs {
	my ($fullpathfilename, $log) = @_;
	my @paths;
	for (my $path = dirname $fullpathfilename; length $path > 1; $path = dirname $path) {
		push @paths, $path;
	}
	mkdir $_ for reverse @paths;
	$log->error("Failed to create log directory $paths[0]") if @paths and not -d $paths[0];
}

# minimal set of vars before loading the profiler
our $configfile;
our $NYTPROF_PRESENT = 0;

# Profiler config and code moved here because we need
# to get more data before main starts
BEGIN {
	use ConfigCentral;
    use LogUtils; 
    use Getopt::Long;
    
	LogUtils::level('WARNING');
    LogUtils::indentoutput(1);
	
    my $log = LogUtils->getLogger(__PACKAGE__);	
	my $nojobs;
	my $splitjobs;
	my $print_help;
	
	# Make a copy of @ARGV and restore it after extracting options from it.
	
	my @options = @ARGV;
	GetOptions("config:s" => \$configfile,
               "nojobs|n" => \$nojobs,
               "splitjobs|s" => \$splitjobs,
               "help|h"   => \$print_help );

	@ARGV = @options;

    unless ( $configfile ) {
        $log->warning("Performance code setup: No 'config' option, skipping performance configuration. See --help ");
    } else {
	
		my $perflogdir;
	    my $perflogfilepath;
	    my $enable_perflog_reporting = ConfigCentral::getValueOf($configfile,'common','enable_perflog_reporting');
	    
	    if (defined $enable_perflog_reporting && $enable_perflog_reporting) {
			# The profiling tool might be missing in some distributions.
			# Default is to assume is not present.
			$perflogdir = ConfigCentral::getValueOf($configfile,'common','perflogdir');
			$perflogdir ||= ($perflogdir) ? $perflogdir : '/var/log/arc/perfdata'; 
			# append and create raw folder for NYTProf database files
			
			my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
		    my $timestamp=POSIX::strftime("%Y%m%d%H%M%S", $sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
		    my $perflogfilename = 'infosys_'.$timestamp.'.perflog.raw';
		    $perflogfilepath = $perflogdir.'/perl_nytprof/'.$perflogfilename;
		    createdirs($perflogfilepath,$log);
		    if ( -e $perflogdir ) {
				  $ENV{NYTPROF} = "savesrc=0:start=no:file=".$perflogfilepath;
				  $NYTPROF_PRESENT = eval { require Devel::NYTProf; 1; };
	 		      if ($NYTPROF_PRESENT) {
					  DB::enable_profile($perflogfilepath);
					  $log->info("Performance reporting enabled. The database file will be stored in $perflogfilepath");
				  } else { $log->warning("Devel::NYTProf PERL module not installed. Performance data cannot be collected."); }
		    } else { $log->warning("Cannot access directory $perflogdir. Unable to open performance file $perflogfilepath. Check arc.conf perflogdir option, directories and permissions"); }
	    }
    }
    undef $log;
    no ConfigCentral;
    no LogUtils;
}

use ConfigCentral;
use LogUtils; 
use HostInfo;
use RTEInfo;
use GMJobsInfo;
use LRMSInfo;

use ARC0ClusterInfo;
use ARC1ClusterInfo;

use GLUE2xmlPrinter;
use GLUE2ldifPrinter;
use NGldifPrinter;
use InfosysHelper;

our $nojobs;
our $log = LogUtils->getLogger(__PACKAGE__);


sub timed {
    my ($fname, $func) = @_;
    my $t0 = time();
    my $result = &$func();
    my $dt = sprintf('%.3f', time() - $t0);
    $log->verbose("Time spent in $fname: ${dt}s");
    return $result;
}


sub main {

    LogUtils::level('INFO');
    LogUtils::indentoutput(1);
   
    # Parse command line options
    my $splitjobs;
    my $print_help;

    GetOptions("config:s" => \$configfile,
               "nojobs|n" => \$nojobs,
               "splitjobs|s" => \$splitjobs,
               "help|h"   => \$print_help ); 

    if ($print_help) { 
        print "Usage: $0 <options>
        --config      - location of arc.conf
        --nojobs|n    - don't include information about jobs
        --splitjobs|s - write job info in a separate XML file for each job in the controldir
        --help        - this help\n";
        exit 1;
    }

    unless ( $configfile ) {
        $log->error("a command line argument is missing, see --help ");
    }

    # Read ARC configuration
    our $config = timed 'ConfigCentral', sub { ConfigCentral::parseConfig($configfile) };

    # Dump config (uncomment if needed)
    #print Dumper($config);

     
    # Change level for root logger (affects all loggers from now on)
    LogUtils::level($config->{debugLevel}) if defined $config->{debugLevel};

    my $providerlog = $config->{ProviderLog} || "/var/log/arc/infoprovider.log";
    $log->info("Redirecting further messages to $providerlog");
    LogUtils::indentoutput(0);

    # Attempt to recursively create directory
    createdirs($providerlog,$log);

    open STDERR, ">>", $providerlog or $log->error("Failed to open to $providerlog");
    LogUtils::timestamps(1);
    $log->info("############## A-REX infoprovider started  ##############");

    fix_config($config);
    check_config($config);

    # start heartbeat
    InfosysHelper::heartbeatBeat($config);

    my $data = timed 'all info collectors', sub { CEInfo::collect($config) };
    $data->{nojobs} = $nojobs;

    # Print GLUE2 XML
    $log->info("Generating GLUE2 XML rendering");
        
    my $glue2data = timed 'ARC1ClusterInfo', sub { ARC1ClusterInfo::collect($data) };
    my $xmlPrinter = GLUE2xmlPrinter->new(*STDOUT, $splitjobs);
    $xmlPrinter->begin('InfoRoot');
    timed 'GLUE2xml', sub { $xmlPrinter->Domains($glue2data) };
    $xmlPrinter->end('InfoRoot');

    InfosysHelper::heartbeatBeat($config);

    # Glue1.2/1.3 cannot be generated without NorduGrid, so we force publishing
    if (!$config->{infosys_nordugrid} and $config->{infosys_glue12}) {
		$log->warning("NorduGrid schema disabled in arc.conf. Glue1.2/1.3 cannot be generated without NorduGrid Schema, reenabling");
		$config->{infosys_nordugrid} = 1;
	}

    # Generate ldif for infosys-ldap
	$log->info("Generating LDIF renderings");
	my $ngdata;
	$ngdata = timed 'ARC0ClusterInfo', sub { ARC0ClusterInfo::collect($data) }
		if ($config->{infosys_nordugrid} or $config->{infosys_glue12});

	my $print_ldif = sub {
		my ($fh) = @_;
		if ($config->{infosys_glue2_ldap}) {                
		   # introduced to find GLUE2 LDAP schema version
			my $glue2schemaversion;
			unless (open (GLUE2_SCHEMA, "</etc/ldap/schema/GLUE20.schema")) {
				$log->debug("CEinfo.pl didn't find GLUE20.schema in standard location. Will create LDIF in compatibitity mode.");
			} else {
				 my $linecnt=0;
				 while (my $line = <GLUE2_SCHEMA>) {
					chomp $line;
					next unless $line;
					if ($line =~ m/# Schema Version: (\d).*/) {
						$glue2schemaversion = $1; 
						$log->debug("GLUE2 schema version major identified. It is: $glue2schemaversion");
						last
					}
					if ($linecnt > 25) {
						$log->debug("Can't identify GLUE2 schema version. Will create LDIF in compatibility mode");
						last
					}
					$linecnt++;
				}
			close GLUE2_SCHEMA;
			}
			# override splitjobs for ldap if option specified in arc.conf
			if ( $config->{infosys_glue2_ldap_showactivities} ) { $splitjobs = 0 };
			$log->info("Generating GLUE2 LDIF rendering");
			my $ldifPrinter = GLUE2ldifPrinter->new($fh, $splitjobs, $glue2schemaversion);
			timed 'GLUE2ldif', sub { $ldifPrinter->Top($glue2data) };
		}
		if ($config->{infosys_nordugrid} or $config->{infosys_glue12}) {
			$log->info("Generating NorduGrid LDIF rendering");
			my $ldifPrinter = NGldifPrinter->new($fh, $config->{validity_ttl});
			timed 'NGldif', sub { $ldifPrinter->Top($ngdata) };
		}
	};

    InfosysHelper::heartbeatBeat($config);

	# only notifiy ldap infosys if ldap is enabled!
	if ($config->{infosys_nordugrid} or $config->{infosys_glue12} or $config->{infosys_glue2_ldap}) {
		# check that fifo is working and notify if so.
		if (InfosysHelper::createLdifScript($config, $print_ldif)) {
			if (InfosysHelper::notifyInfosys($config)) {
				$log->verbose("LDAP information system notified");
			} else {
				$log->warning("Failed to notify LDAP information system");
			}
		} else {
		   $log->warning("Failed to create ldif generator script for LDAP information system");
		}
	} else {
		$log->verbose("LDAP/ldif information generation is disabled. To enable it, enable one of the options infosys_nordugrid, infosys_glue12, infosys_glue2_ldap.");
	}
    
    InfosysHelper::heartbeatRemove($config);
    
    $log->info("############## A-REX infoprovider finished ##############");

    # close performance file if enabled
    DB::disable_profile() if ($NYTPROF_PRESENT && (defined $config->{enable_perflog_reporting}));
}


##################################################
# information collector
##################################################

sub collect($) {
    my ($config) = @_;

# uncomment for a dump of the whole config hash
# print Dumper($config);

    # get all local users from grid-map. Sort unique
    $log->info("Reading grid-mapfiles");
    my @localusers;
    my $usermap = {};
    if ($config->{gridmap}) {
        my %saw = ();
        $usermap = read_grid_mapfile($config->{gridmap});
        @localusers = grep !$saw{$_}++, values %$usermap;
    } else {
        $log->info("gridmap not configured");
        my $defaultuser = $config->{defaultLocalName};
        @localusers = ($defaultuser) if $defaultuser;
    }
    $log->warning("Cannot determine local users") unless @localusers;

    $log->info("Fetching job information from control directory (GMJobsInfo.pm)");
    my $gmjobs_info = get_gmjobs_info($config);

    $log->info("Updating job status information");
    # build the list of all jobs in state INLRMS
    my @jobids;
    for my $job (values %$gmjobs_info) {
        next unless $job->{status} and $job->{status} eq 'INLRMS';
        next unless defined $job->{localid} and length $job->{localid};
        push @jobids, $job->{localid};
    }

    InfosysHelper::heartbeatBeat($config);

    # build hash with all the input necessary for the renderers
    my $data = {};
    $data->{config} = $config;
    $data->{usermap} = $usermap;
    
    InfosysHelper::heartbeatBeat($config);
    
    $log->info("Updating frontend information (HostInfo.pm)");
    $data->{host_info} = get_host_info($config,\@localusers);
    
    InfosysHelper::heartbeatBeat($config);
    
    $log->info("Updating RTE information (RTEInfo.pm)");
    $data->{rte_info} = get_rte_info($config);
    
    InfosysHelper::heartbeatBeat($config);
    
    $data->{gmjobs_info} = $gmjobs_info;
    $log->info("Updating LRMS information (LRMSInfo.pm)");
    $data->{lrms_info} = get_lrms_info($config,\@localusers,\@jobids);

    $log->info("Discovering adotf values");
    fix_adotf($config->{service}, $data->{host_info});
    fix_adotf($_, $data->{host_info}) for values %{$config->{xenvs}};

	InfosysHelper::heartbeatBeat($config);

    return $data;
}


##################################################
# Calling other information collectors
##################################################

sub get_host_info($$) {
    my ($config,$localusers) = @_;

    my $host_opts = {};
    $host_opts->{localusers} = $localusers;
    $host_opts->{processes} = ['arched', 'gridftpd'];
    $host_opts->{x509_user_cert} = $config->{x509_user_cert};
    $host_opts->{x509_cert_dir} = $config->{x509_cert_dir};
    $host_opts->{wakeupperiod} = $config->{wakeupperiod};
    $host_opts->{sessiondir} = $config->{sessiondir};
    $host_opts->{control} = $config->{control};
    $host_opts->{remotegmdirs} = $config->{remotegmdirs};

    return timed 'HostInfo', sub { HostInfo::collect($host_opts) };
}

sub get_rte_info($) {
    my ($config) = @_;

    my $rte_opts;
    $rte_opts->{configfile} = $configfile;
    $rte_opts->{runtimedir} = $config->{runtimedir} if $config->{runtimedir};
    $rte_opts->{use_janitor} = $config->{use_janitor} if $config->{use_janitor};
    $rte_opts->{pkgdatadir} = dirname($0);

    return timed 'RTEInfo', sub { RTEInfo::collect($rte_opts) };
}

sub get_lrms_info($$$) {
    my ($config,$localusers,$jobids) = @_;

    # possibly any options from config are needed, so just clone it all
    my $lrms_opts = Storable::dclone($config);
    delete $lrms_opts->{$_} for qw(xenvs shares);
    $lrms_opts->{jobs} = $jobids;
    for my $share ( keys %{$config->{shares}} ) {
        $lrms_opts->{queues}{$share} = $config->{shares}{$share};
        $lrms_opts->{queues}{$share}{users} = $localusers;
    }

    return timed 'LRMSInfo', sub { LRMSInfo::collect($lrms_opts) };
}

sub get_gmjobs_info($) {
    my $config = shift;

    my $gmjobs_info = timed 'GMJobsInfo', sub { GMJobsInfo::collect($config->{control},
                                                                    $config->{remotegmdirs},
                                                                    $nojobs) };
    return fix_jobs($config, $gmjobs_info);
}


##################################################
# 
##################################################

# Check validity and fill in missing 'share' and 'queue' attributes of jobs.

sub fix_jobs {
    my ($config, $gmjobs_info) = @_;

    my ($lrms, $defaultshare) = split /\s+/, $config->{lrms} || '';
    for my $jobid (keys %$gmjobs_info) {
        my $job = $gmjobs_info->{$jobid};
        my $share = $job->{share};

        # If A-REX has not chosen a share for the job, default to one.
        if (not $share) {
            my $msg = "A-REX has not chosen a share for job $jobid";
            if ($defaultshare) {
                $log->info($msg.". Assuming default: ".$defaultshare);
                $share = $defaultshare;
            } else {
                my @shares = keys %{$config->{shares}};
                if (@shares == 1) {
                    $log->info($msg.". Assuming: ".$shares[0]);
                    $share = $shares[0];
                } else {
                    $log->warning($msg." and no default share is defined.");
                }
            }
        }

        # Set correct queue
        if ($share) {
            my $sconfig = $config->{shares}{$share};
            if ($sconfig) {
                $job->{queue} = $sconfig->{MappingQueue} || $share;
            } else {
                $log->warning("Job $jobid belongs to an invalid share '$share'");
                $share = undef;
            }
        }

        # Group jobs not belonging to any known share into a catch-all share named ''
        $job->{share} = $share || '';
    }
    return $gmjobs_info;
}


# reads grid-mapfile. Returns a ref to a DN => uid hash

sub read_grid_mapfile($) {
    my $gridmapfile = shift;
    my $usermap = {};

    unless (open MAPFILE, "<$gridmapfile") {
        $log->warning("can't open gridmapfile at $gridmapfile");
        return;
    }
    while (my $line = <MAPFILE>) {
        chomp($line);
        if ( $line =~ m/\"([^\"]+)\"\s+(\S+)/ ) {
            my $subject = $1;
            eval {
                $subject = decode("utf8", $subject, 1);
            };
            $usermap->{$subject} = $2;
        }
    }
    close MAPFILE;

    return $usermap;
}


# Alters the parsed configuration options by:
#  * adding some defaults
#  * flattening per-user options
# 20140225 - synched some options from GMConfig.cpp

sub fix_config {
    my ($config) = @_;

    my %config_defaults = (
                   arcversion     => '5.3.0rc1',
                   infosys_nordugrid   => 1,
                   infosys_glue12      => 0,
                   infosys_glue2_ldap  => 1,
                   GridftpdEnabled     => 0,
                   GridftpdMountPoint  => '/jobs',
                   GridftpdPort        => 2811,
                   GridftpdAllowNew    => 1,
                   GridftpdPidFile     => '/var/run/gridftpd.pid',
                   validity_ttl	  =>  1200,
                   SlapdPort      => 2135,
                   infosys_glue2_service_qualitylevel   => 'production',
                   shared_filesystem => 1,
                   enable_arc_interface => 1,
                   enable_emies_interface => 0,
                   infoproviders_timeout => 600
    );
 
    my %control_defaults = (
                  defaultttl  => '604800 2629744'
    );

    for (keys %config_defaults) {
        $config->{$_} = $config_defaults{$_} if not defined $config->{$_};
    }

    $config->{control} ||= {};
 
    for (keys %control_defaults) {
        $config->{control}->{"."}->{$_} = $control_defaults{$_} if not defined $config->{control}->{"."}->{$_};
    }


    $config->{service} ||= {};
    $config->{shares} ||= {};
    $config->{xenvs} ||= {};

    delete $config->{location} unless $config->{location} and %{$config->{location}};
    delete $config->{contacts} unless $config->{contacts} and @{$config->{contacts}};

    my $hostname = $config->{hostname} || hostname();
    {  
        my @dns = split /\./, $hostname;
        my $shorthost = shift @dns;
        my $dnsdomain = join ".", @dns;

        $log->info("AdminDomain config option is missing in XML. Defaulting to arc.conf values") unless $config->{AdminDomain};
        $log->info("AdminDomain name in [infosys/admindomain] block is missing or incorrect in arc.conf. Defaulting to UNDEFINEDVALUE") unless $config->{admindomain}{Name};

        chomp ($config->{admindomain}{Name} ||= "UNDEFINEDVALUE");
        chomp ($config->{AdminDomain} ||= "UNDEFINEDVALUE");
        
        
        $log->info("ClusterName config option is missing in XML. Trying cluster_alias...") unless $config->{service}{ClusterName};
        $log->info("ClusterAlias in XML or cluster-alias in arc.conf missing. Defaulting to $shorthost") unless $config->{service}{ClusterAlias};
        chomp ($config->{service}{ClusterName} ||= $config->{service}{ClusterAlias} ||= $shorthost);
    }

    # Manage A-REX WS interfaces publication
    if ($config->{endpoint} and $config->{endpoint} =~ m{^(https?)://([^:/]+)(?::(\d+))?(.*)}) {
        my ($proto,$host,$port,$mountpoint) = ($1,$2,$3,$4);
        $port ||= 80 if $proto eq "http";
        $port ||= 443 if $proto eq "https";
        $config->{arexhostport} = "$host:$port";
        # fix endpoint information if not complete
        $config->{endpoint} = "$proto://$host:$port$mountpoint"
    } else {
		# disable all WS interfaces
		$config->{enable_arc_interface} = 0;
		$config->{enable_emies_interface} = 0;
		$log->warning("arex_mount_point not configured. WS interfaces org.nordugrid.xbes and EMI-ES will not be published.");
	}
        
    # fire warning if GLUE2 Service Quality Level is not good
    # TODO: I'd like this to be done by InfoChecker
    if ($config->{infosys_glue2_service_qualitylevel}) {
        my $qualitylevelstring = $config->{infosys_glue2_service_qualitylevel};
        my $closedenumeration = {'development' => '1',
                                 'pre-production' => '1',
                                 'production' => '1',
                                 'testing' => '1'
                                };
        if (! $closedenumeration->{$qualitylevelstring} ) {
            $log->error("infosys_glue2_service_qualitylevel contains \"$qualitylevelstring\" which is an invalid value. Allowed value is one of: testing production pre-production development"); 
        }
    }

    # Cross-check MappingPolicy references and move them to the share wehre they belong
    for my $s (@{$config->{mappingpolicies}}) {
        $log->error("MappingPolicy must include a ShareName option")
            unless $s->{ShareName};
        $log->error("MappingPolicy must include a Rule option")
            unless $s->{Rule};
        $log->error("MappingPolicy must include a UserDomainID option")
            unless $s->{UserDomainID};
        for my $name (@{$s->{ShareName}}) {
            $log->error("MappingPolicy associated with non-existent Share: $name")
                unless $config->{shares}{$name};
            push @{$config->{shares}{$name}{mappingpolicies}}, $s;
        }
    }

}


# Does some consistency checks on the parsed configuration options

sub check_config {
    my ($config) = @_;

    $log->error("No queue or ComputingShare configured") unless %{$config->{shares}};
    $log->error("No ExecutionEnvironment configured") unless %{$config->{xenvs}};

    $log->error("No control directory configured")
        unless %{$config->{control}} or $config->{remotegmdirs};
    while (my ($user, $control) = each %{$config->{control}}) {
        $log->error("No control directory configured for user $user") unless $control->{controldir};
        $log->error("No session directory configured for user $user") unless $control->{sessiondir};
    }

    # Cross-check ExecutionEnvironment references
    for my $s (values %{$config->{shares}}) {
        next unless $s->{ExecutionEnvironmentName};
        for my $group (@{$s->{ExecutionEnvironmentName}}) {
            $log->error("ComputingShare associated with non-existent ExecutionEnvironment: $group")
                unless $config->{xenvs}{$group};
        }
    }
    for my $s (values %{$config->{xenvs}}) {
        delete $s->{NodeSelection} unless %{$s->{NodeSelection}};
    }

    my ($lrms, $defaultshare) = split /\s+/, $config->{lrms} || '';
    $log->error("defaultShare set to nonexistent ComputingShare")
        if $defaultshare and not $config->{shares}{$defaultshare};

    if ($config->{contacts}) {
        for (@{$config->{contacts}}) {
            $log->warning("Contact is missing Type") and next unless $_->{Type};
            $log->warning("Contact is missing Detail") and next unless $_->{Detail};
            $log->warning("Contact Detail is not an URI: ".$_->{Detail}) and next
                unless $_->{Detail} =~ m/^\w+:/;
        }
    }
}


# Replaces 'adotf' in config options with autodetected values

sub fix_adotf {
    my ($h, $hostinfo) = @_;
    if ($h->{nodecpu}) {
        if ($h->{nodecpu} =~ m/(.*?)(?:\s+stepping\s+(\d+))?\s+@\s+([.\d]+)\s*(M|G)Hz$/i) {
            $h->{CPUModel} ||= $1;
            $h->{CPUVersion} ||= $2;
            $h->{CPUClockSpeed} ||= ($4 eq 'G') ? int($3 * 1000) : int($3);
        } elsif ($h->{nodecpu} eq 'adotf') {
            $h->{CPUVendor} ||= 'adotf';
            $h->{CPUModel} ||= 'adotf';
            $h->{CPUClockSpeed} ||= 'adotf';
        } else {
            $log->warning("Invalid value for nodecpu option: ".$h->{nodecpu});
        }
        delete $h->{nodecpu};
    }
    if ($h->{OpSys} and grep {$_ eq 'adotf'} @{$h->{OpSys}}) {
        $h->{OpSys} = [ grep {$_ ne 'adotf'} @{$h->{OpSys}} ];
        unless (defined($hostinfo->{osname})) {
            $log->warning("Failed to autodetect value for 'OSName'. Enter correct value in config file");
            $h->{OSName} = 'unknown';
        }
        $h->{OSName} ||= 'adotf';
        $h->{OSVersion} ||= 'adotf';
        $h->{OSFamily} ||= 'adotf';
    }
    my %hostkey = (Platform => 'machine',
                   PhysicalCPUs => 'cpusocketcount',
                   LogicalCPUs => 'cputhreadcount',
                   CPUVendor => 'cpuvendor',
                   CPUModel => 'cpumodel',
                   CPUClockSpeed => 'cpufreq',
                   MainMemorySize => 'pmem',
                   VirtualMemorySize => 'vmem',
                   OSFamily => 'sysname',
                   OSName => 'osname',
                   OSVersion => 'osversion'
    );
    for my $key (keys %hostkey) {
        if (exists $h->{$key} and $h->{$key} eq 'adotf') {
            $log->warning("Failed to autodetect value for '$key'. Enter correct value in config file")
                unless defined $hostinfo->{$hostkey{$key}};
            $h->{$key} = $hostinfo->{$hostkey{$key}};
        }
    }
}

main();