【问题标题】:Puppet exceptions handling in custom functions (Puppet+Ruby)自定义函数中的 Puppet 异常处理 (Puppet+Ruby)
【发布时间】:2021-09-01 09:04:26
【问题描述】:

我创建了一个 puppet 函数(模块 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

为什么我无法挽救 puppet Ruby 函数中的 HTTP 异常?

【问题讨论】:

    标签: ruby http puppet


    【解决方案1】:

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

    但是,异常类对象确实有一个允许访问错误消息的成员。该成员是message 成员。因此,您可以快速更新自定义 Puppet 函数中的代码:

    puts "http://db.net:3013/api/nagios/sets.cfg " + e.message
    

    它应该按照您的初衷工作。另请注意,如果您在 Puppet 目录编译期间推迟该功能,它将在您的所有客户端上与 MRI 一起执行。这是一种替代解决方案,但成本/收益明显不佳。

    【讨论】:

    • 感谢您的回复。我不太关心打印错误消息,而是更关心在 ruby​​ 代码中拦截异常。如上所示,它根本不起作用。
    • @MaximMaximov 您能否详细说明您问题中错误消息的部分以及让您感到困惑的答案?我可以进一步澄清。正如答案和您的错误消息中所解释的,异常被捕获,但是如果没有明确定义的重载成员方法,您无法将对象隐式转换为字符串类型。
    • 谢谢。在我身边发现了一个错误。 e.message 确实...
    • @MaximMaximov 很高兴听到。那么请接受答案。
    猜你喜欢
    • 1970-01-01
    • 2021-12-17
    • 2014-04-03
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    相关资源
    最近更新 更多