自定义函数(Puppet+Ruby)中的Puppet异常处理



我创建了一个puppet函数(module puppet::Parser::Functions)Newfunction ()) getfromdb它尝试从db.net主机获取url数据,更新本地缓存文件并返回url.body的内容。在http请求服务器失败的情况下,它使用本地缓存数据文件。

为了实现这一点,我想在函数中捕获异常:

require "net/http"
require "uri"

uri = URI("http://db.net:3013/api/nagios/sets.cfg")
begin
puts "here"
res = Net::HTTP.get_response(uri)
puts "No here"
rescue Errno::ECONNREFUSED => e
puts "http://db.net:3013/api/nagios/sets.cfg " + e
else
puts "Fetching: http://db.net:3013/api/nagios/sets.cfg"
end

3013端口上的服务器没有运行.这是我在木偶输出中得到的:

Info: Scope(Class[ZSX::Service::Monitor]): ------------------ Applying service class z::service::monitor
Info: Scope(Class[Nagios::Server2]): Applying class nagios::server2
here
Error: Evaluation Error: Error while evaluating a Function Call, no implicit conversion of Errno::ECONNREFUSED into String (file: /modules/nagios/manifests/server2.pp, line: 115, column: 13) on node puppet-node.net

而在irb控制台中它的行为不同:

irb(main):018:0>     begin
irb(main):019:1*       puts "here"
irb(main):020:1>       res = Net::HTTP.get_response(uri)
irb(main):021:1>       puts "No here"
irb(main):022:1>     rescue Errno::ECONNREFUSED => e
irb(main):023:1>       puts "Could not fetch: http://db.net:3013/api/nagios/sets.cfg " + e
irb(main):024:1>     else
irb(main):025:1*       puts "Fetching: http://db.net:3013/api/nagios/sets.cfg"
irb(main):026:1>     end
here
Could not fetch: http://db.net:3013/api/nagios/sets.cfg Connection refused - connect(2)
=> nil

为什么我不能拯救HTTP异常在傀儡Ruby函数?

我将假设当您在IRB中测试此函数时,您正在使用Ruby的MRI (Matz的Ruby解释器又名CRuby)。当您执行非延迟的自定义Puppet函数时,它将在另一个解释器(JRuby)中的Puppet master上执行。在JRuby中,异常是一个对象,它没有重载的成员方法来强制转换成字符串,就像MRI中那样。因此,当您将代码作为自定义Puppet函数执行时,您将看到一个错误消息,即您不能将对象隐式地强制转换为字符串。

然而,异常类对象确实有一个允许访问错误消息的成员。这个元素是message。因此,您可以对自定义Puppet函数中的代码进行快速更新:
puts "http://db.net:3013/api/nagios/sets.cfg " + e.message

,它应该按照你的初衷工作。还请注意,如果在Puppet编目编译期间推迟该函数,它将在所有客户机上与MRI一起执行。这是另一种解决方案,但显然成本/效益很低。

最新更新