Pingr - https://gist.github.com/bradland/2cf4e427cd7b61bbd9498f16ee156e84

I wrote this to scratch an itch. It's a script, intended to be copied as a 
single file to locations where I may find it useful, so is a lot of 
refactoring that could (should, really) be done, but I don't plan on doing. 
I'm also sticking to Ruby core and Stdlib only, so that I don't need to 
rely on gems in the execution environment. I've never used threads before, 
and I'm looking for feedback on how I'm using them and what mistakes I'm 
making.

*What is it?*
Pingr, short for ping reporter, audibly announces the status of a host. The 
script relies on system utilities ping and say (OS X utility that speaks 
the supplied string argument aloud). Ping is used to determine host status, 
and say is used to make the announcement. The script uses Open3#popen3 to 
launch the ping command and monitor output, which is then (very 
simplistically) analyzed to determine how status. If the host changes 
status, the change is announced.

*Blocking*
When I first wrote the script, there was no `announce` method. I simply 
called the `say` method from within `update_status`. For example, 
`update_status` used to look like this:

# Update host status
def update_status(line)
  previous_status = @host_status


  @host_status = parse_line(line)


  if @host_status != previous_status
    case @host_status
    when :up
      say "Host #{@host} is up."
    when :down
      say "Host #{@host} is down."
    else
      say "Unknown status encountered."
    end
  end
end

The problem is that this method blocks while Kernel#` runs, so a change in 
host status interrupted output (which is just relayed from ping). My desire 
is for the script to continue to relay the output of the ping command while 
the host status announcement is being made.

*Hello Thread/Queue*
I wanted announcements to stop blocking script execution, but I also didn't 
want announcements to be made over each other in the event that a status 
change occurred *during* an announcement. This meant I needed not only a 
thread, but also a queue. My solution was to have the `update_status` 
method drop messages on the queue, and use an announcement method named 
`announce`, which spawns a thread that watches the queue.

I'm happy to hear feedback about this script in general, but I'm especially 
curious to hear if I've done something boneheaded with the way I'm spawning 
a new thread.

Thanks!

-- 
-- 
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby
--- 
You received this message because you are subscribed to the Google Groups "SD 
Ruby" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to