]> git.donarmstrong.com Git - dsa-puppet.git/blob - 3rdparty/modules/stdlib/lib/puppet/parser/functions/validate_cmd.rb
upgrade to stdlib 4.6.1
[dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / validate_cmd.rb
1 require 'puppet/util/execution'
2 require 'tempfile'
3
4 module Puppet::Parser::Functions
5   newfunction(:validate_cmd, :doc => <<-'ENDHEREDOC') do |args|
6     Perform validation of a string with an external command.
7     The first argument of this function should be a string to
8     test, and the second argument should be a path to a test command
9     taking a % as a placeholder for the file path (will default to the end).
10     If the command, launched against a tempfile containing the passed string,
11     returns a non-null value, compilation will abort with a parse error.
12
13     If a third argument is specified, this will be the error message raised and
14     seen by the user.
15
16     A helpful error message can be returned like this:
17
18     Example:
19
20         # Defaults to end of path
21         validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content')
22
23         # % as file location
24         validate_cmd($haproxycontent, '/usr/sbin/haproxy -f % -c', 'Haproxy failed to validate config content')
25
26     ENDHEREDOC
27     if (args.length < 2) or (args.length > 3) then
28       raise Puppet::ParseError, ("validate_cmd(): wrong number of arguments (#{args.length}; must be 2 or 3)")
29     end
30
31     msg = args[2] || "validate_cmd(): failed to validate content with command #{args[1].inspect}"
32
33     content = args[0]
34     checkscript = args[1]
35
36     # Test content in a temporary file
37     tmpfile = Tempfile.new("validate_cmd")
38     begin
39       tmpfile.write(content)
40       tmpfile.close
41
42       if checkscript =~ /\s%(\s|$)/
43         check_with_correct_location = checkscript.gsub(/%/,tmpfile.path)
44       else
45         check_with_correct_location = "#{checkscript} #{tmpfile.path}"
46       end
47
48       if Puppet::Util::Execution.respond_to?('execute')
49         Puppet::Util::Execution.execute(check_with_correct_location)
50       else
51         Puppet::Util.execute(check_with_correct_location)
52       end
53     rescue Puppet::ExecutionFailure => detail
54       msg += "\n#{detail}"
55       raise Puppet::ParseError, msg
56     rescue Exception => detail
57       msg += "\n#{detail.class.name} #{detail}"
58       raise Puppet::ParseError, msg
59     ensure
60       tmpfile.unlink
61     end
62   end
63 end