examples/jexec2.rb
changeset 7 4460fc10c6a3
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/jexec2.rb	Tue Mar 03 22:23:45 2009 +0000
@@ -0,0 +1,43 @@
+#!/usr/bin/env ruby
+#
+# A 'smarter' jexec in ruby.
+#
+# Run a command in multiple jails in parallel.
+# Jails can be selected via host, ip, or jid.
+#
+#   "Run 'ls' in all jails that match the hostname 'trac':
+#       ./jexec2.rb trac ls
+#
+
+BEGIN {
+        require 'pathname'
+        basedir = Pathname.new( __FILE__ ).dirname.parent
+
+        $LOAD_PATH.unshift basedir + "ext" unless 
+                $LOAD_PATH.include? basedir + "ext"
+}
+
+require 'jail'
+
+jarg = ARGV.shift
+args = ARGV
+
+jails = BSD::Jail.find_all do |j|
+    j.jid     == jarg.to_i ||
+    j.ip.to_s == jarg      ||
+    j.host    =~ /#{jarg}/
+end or raise "Unable to find jails that match '#{jarg}'."
+
+
+jails.each do |j|
+    $deferr.puts "Parent #{Process.pid} about to attach to #{j.host} in a block!"
+    childpid = j.attach do
+        $deferr.puts "Child #{Process.pid} exec()ing:", "  " + args.join(" ")
+        exec( *args )
+    end
+
+    $deferr.puts "Parent: waiting on imprisoned child #{childpid}"
+    Process.waitpid( childpid )
+    $deferr.puts "Child exited with exit code: %d" % [ $?.exitstatus ]
+end
+