Skip to content

Commit

Permalink
fixes theforeman#610 - tftp file fetching logging
Browse files Browse the repository at this point in the history
  • Loading branch information
lzap authored and ohadlevy committed Mar 17, 2011
1 parent 0373f6b commit 20618e9
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 4 deletions.
7 changes: 3 additions & 4 deletions lib/proxy/tftp.rb
@@ -1,5 +1,6 @@
require 'fileutils'
require 'pathname'
require "proxy/util"

module Proxy::TFTP
extend Proxy::Log
Expand Down Expand Up @@ -56,10 +57,8 @@ def fetch_boot_file dst, src
#as the dst might contain another sub directory
FileUtils.mkdir_p destination.parent

cmd = "wget --no-check-certificate -b -c -q #{src} -O \"#{destination}\" -o #{SETTINGS.log_file}"
logger.debug "Executing #{cmd}"
`#{cmd}`
$? == 0
cmd = "wget --no-check-certificate -nv -c #{src} -O \"#{destination}\""
Proxy::Util::CommandTask.new(cmd)
end

private
Expand Down
45 changes: 45 additions & 0 deletions lib/proxy/util.rb
@@ -1,4 +1,49 @@
require 'open3'

module Proxy::Util

class CommandTask
include Proxy::Log

# track all threads in the class variable
@@tasks = []

# create new task and spawn new thread logging all the cmd
# output to the proxy log. only the process' output is connected
# stderr is redirected to proxy error log, stdout to proxy debug log
def initialize(cmd)
# clean finished tasks from the array
@@tasks = @@tasks.collect { |t| nil unless t.is_a? String }.compact

# run the task in its own thread
logger.debug "Starting task (total: #{@@tasks.count}): #{cmd}"
@task = Thread.new(cmd) do |cmd|
Open3::popen3(cmd) do |stdin,stdout,stderr,thr|
# PIDs are not available under Ruby 1.8
pid = thr.nil? ? rand(9999) : thr.pid
stdout.each do |line|
logger.debug "[#{pid}] #{line}"
end
stderr.each do |line|
logger.error "[#{pid}] #{line}"
end
end
$?
end
@@tasks << @task
end

# wait for the task to finish and get the subprocess return code
def join
@task.value
end

# wait for all tasks to finish
def self.join_all
@@tasks.each { |aThread| aThread.join }
end
end

# searches for binaries in predefined directories and user PATH
# accepts a binary name and an array of paths to search first
# if path is ommited will search only in user PATH
Expand Down
16 changes: 16 additions & 0 deletions test/util_test.rb
Expand Up @@ -5,4 +5,20 @@ class ProxyUtilTest < Test::Unit::TestCase
def test_util_should_support_path
assert Proxy::Util.instance_methods.include? "which"
end

def test_commandtask_with_echo_exec
t = Proxy::Util::CommandTask.new('echo test')
assert_equal t.join, 0
end

def test_commandtask_with_wget_invalidport_exec
t = Proxy::Util::CommandTask.new("wget --no-check-certificate -c http://127.0.0.2 -O /dev/null")

# return code is not correct in Ruby<1.9 for open3 (http://redmine.ruby-lang.org/issues/show/1287)
if RUBY_VERSION =~ /1\.8\.\d+/
assert_equal t.join, 0
else
assert_equal t.join, 4
end
end
end

0 comments on commit 20618e9

Please sign in to comment.