module BetweenMeals::Util

Util classes need class vars :) rubocop:disable ClassVars

Public Instance Methods

exec(command, logger = nil, stream = nil) click to toggle source
# File lib/between_meals/util.rb, line 48
def exec(command, logger = nil, stream = nil)
  @@logger = logger if logger

  c = execute(command, stream)
  return c.status.exitstatus, c.stdout
end
exec!(command, logger = nil, stream = nil) click to toggle source
# File lib/between_meals/util.rb, line 41
def exec!(command, logger = nil, stream = nil)
  @@logger = logger if logger
  c = execute(command, stream)
  c.error!
  return c.status.exitstatus, c.stdout
end
time(logger = nil) { || ... } click to toggle source
# File lib/between_meals/util.rb, line 34
def time(logger = nil)
  @@logger = logger if logger
  t0 = Time.now
  yield
  info("Executed in #{format('%.2f', Time.now - t0)}s")
end

Private Instance Methods

chef_zero_running?(port, use_ssl) click to toggle source
# File lib/between_meals/util.rb, line 95
def chef_zero_running?(port, use_ssl)
  Timeout.timeout(1) do
    begin
      http = Net::HTTP.new('localhost', port)
      if use_ssl
        http.use_ssl = true
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end
      res = http.get('/')
      return res['Server'] == 'chef-zero'
    rescue StandardError
      return false
    end
  end
rescue Timeout::Error
  return false
end
execute(command, stream) click to toggle source
# File lib/between_meals/util.rb, line 61
def execute(command, stream)
  info("Running: #{command}")
  c = Mixlib::ShellOut.new(command, :live_stream => stream)
  c.run_command
  c.stdout.lines.each do |line|
    info("STDOUT: #{line.strip}")
  end
  c.stderr.lines.each do |line|
    info("STDERR: #{line.strip.red}")
  end
  return c
end
info(msg) click to toggle source
# File lib/between_meals/util.rb, line 57
def info(msg)
  @@logger&.info(msg)
end
port_open?(port) click to toggle source
# File lib/between_meals/util.rb, line 74
def port_open?(port)
  ips = Socket.ip_address_list
  ips.map!(&:ip_address)
  ips.each do |ip|
    begin
      Timeout.timeout(1) do
        begin
          s = TCPSocket.new(ip, port)
          s.close
          return true
        rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
          next
        end
      end
    rescue Timeout::Error
      next
    end
  end
  return false
end