nsgen 6.52 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2003,2006 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#
#

#
# nsgen - Generate an NS file from some supplied values and a template
#

use Getopt::Long;
use XML::Parser;

sub usage() {
    print "Usage: $0 [-dh] [-o outputfile] [-v var=value ...] template\n";
    print "    -d             Turn on debugging output\n";
    print "    -h             This message\n";
    print "    -v var=value   Set <var> to <value> in the template\n";
    print "    -o outputfile  Put output in <outputfile> instead of stdout\n";
    return 1;
}

42 43 44 45 46 47 48 49 50
#
# Functions
#

sub readTemplate($);
sub processOptions($@);
sub substitute($$);
sub fatal($);

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
#
# Process command-line args
#
my $debug = 0;
my $help  = 0;
my @vars  = ();
my $outfile;
if (! GetOptions("d" => \$debug, "h" => \$help, "v=s" => \@vars, "o=s" =>
	\$outfile)) {
    exit usage();
}

if ($help) {
    exit usage();
}

if (@ARGV != 1) {
    exit usage();
}

my $template_file = shift @ARGV;

#
# Body
#
my ($template,$variables) = readTemplate($template_file);
processOptions($variables,@vars);
my $nsfile = substitute($template,$variables);
79 80 81 82 83 84 85 86 87
if ($outfile) {
    open(OF,">$outfile") or die "Unable to open $outfile: $!\n";
    print OF $nsfile;
    close OF;
} else {
    print $nsfile;
}

exit 0;
88 89 90 91

#
# Read the template XML file
#
92 93 94 95
sub startElement();
sub endElement();
sub processElement();

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
sub readTemplate($) {
    my ($template_file) = @_;
    open TF,"<$template_file" or fatal("Unable to open $template_file: $!");

    #
    # Create a parser.
    #
    my $parser = new XML::Parser(Style => 'Tree');
    $parser->setHandlers('Start'   => \&startElement,
			 'End'     => \&endElement,
			 'Char'    => \&processElement);
    #
    # Do the actual parsing
    #
    local ($vars,@nssections);
    fatal($@) if (eval { $parser->parse(*TF); return 1; } != 1);

    return (\@nssections,$vars);
}

#
# Handle the variables the user gave on the command line
#
sub processOptions($@) {
    my ($variables,@options) = @_;
    return unless @options;
    foreach my $option (@options) {
	#
	# Parse values
	#
	@optparts = split /=/, $option;
	if (@optparts != 2) {
	    fatal("Bad variable: $option");
	}
	my ($var, $value) = @optparts;
	
	#
	# Make sure they gave a real variable
	#
	if (!defined($variables->{$var})) {
	    fatal("Unknown variable $var");
	}
	$variables->{$var}{value} = $value;
    }
}

#
# Replace variables embedded in the template
#
145
sub substitute($$) {
146 147 148
    my ($template,$variables) = @_;
    my $nsfile = "";

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    #
    # Loop through each section of the template
    #
    foreach my $section (@$template) {
	my $lines = $section->{lines};
	my $depends_on = $section->{depends_on};
	my $action = $section->{action};

	#
	# Handle sections that depend on a variable that was not given - either
	# skip the section entirely, or comment it out.
	#
	if ($depends_on && !defined($variables->{$depends_on}{value})) {
	    if ($action eq "skip") {
		next;
	    } elsif ($action eq "comment") {
		$lines =~ s/^(\s*)([^\s#])/$1#$2/mg;
	    }
	}

	#
	# Replace all variables, which look like <Foo>
	#
172
        while ($lines =~ /<(\w+)\s*\/?>/) {
173 174 175 176 177 178 179 180 181 182 183 184 185
            if (!defined($variables->{$1})) {
                fatal("Unknown variable: $1");
            }

	    #
	    # Take the user value if given, default otherwise
	    #
	    my $value;
	    if (defined($variables->{$1}{value})) {
		$value = $variables->{$1}{value};
	    } else {
		$value = $variables->{$1}{default};
	    }
186
            $lines =~ s/<(\w+)\s*\/?>/$value/;
187
        }
188
        $nsfile .= $lines;
189
    }
190
    return $nsfile;
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
}

#
# XML parsing callbacks
#

#
# The beginning of an XML element
#
sub startElement() {
    debug("startElement called with: ", join(",",@_), "\n");
    my ($expat, $element, %attrs) = @_;
    if ($element eq "nstemplate") {
	# Nothing to do
    } elsif ($element eq "variable") {
	#
	# Got a variable - grab the default
	#
	$vars->{$attrs{name}} = {};

	if (defined($attrs{default})){
	    $vars->{$attrs{name}}->{default} = $attrs{default};
	} else {
	    $vars->{$attrs{name}}->{default} = undef;
	}
    } elsif ($element eq "nstext") {
	# Nothing to do
    } elsif ($element eq "section") {
	#
	# Start a fresh array of section lines, and grab a few optional
	# attributes
	#
	$current_section = [];
	$current_section_depends = undef;
	$current_section_action = undef;
	if ($attrs{depends_on}) {
	    $current_section_depends = $attrs{'depends_on'};
	}
	if ($attrs{action}) {
	    $current_section_action = $attrs{'action'};
	}
    }
}

#
# End of an XML element
#
sub endElement() {
    debug("endElement called with: ", join(",",@_), "\n");
    my ($expat, $element) = @_;
    if ($element eq "nstemplate") {
	# Nothing to do
    } elsif ($element eq "variable") {
	# Nothing to do
    } elsif ($element eq "nstext") {
	# Nothing to do
    } elsif ($element eq "section") {
	#
	# Eat blank lines off $current_section at the beginning and end, due to
	# the way that XML preserves whitespace. Lets us do more natural layout
	# in the XML file.
	#
	if ($$current_section[0] =~ /^\s*$/) {
	    shift @$current_section;
	}
	if ($$current_section[$#{$current_section}] =~ /^\s*$/) {
	    pop @$current_section;
	}

	#
	# Push into the global list of sections
	#
	push @nssections, {depends_on => $current_section_depends, action =>
	    $current_section_action, lines => join("",@$current_section)};
    }
}

#
# Process text in an XML element
#
sub processElement() {
    debug("processElement called with: ", join(",",@_), "\n");
    my ($expat, $string) = @_;
    
    #
    # Right now, we only have to do anything in the sections
    #
    SWITCH: for ($expat->current_element()) {
	(/^section$/) && do {
	    push @$current_section, $string;
	};
    }
}

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

     die("*** $0:\n".
	 "    $msg\n");
}       

#
# Debug
#
299
sub debug(@) {
300 301 302 303
    if ($debug) {
	print STDERR @_;
    }
}