Skip to content

Instantly share code, notes, and snippets.

@winebarrel
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save winebarrel/9447917 to your computer and use it in GitHub Desktop.
Save winebarrel/9447917 to your computer and use it in GitHub Desktop.
Kumogata+Serf- event_handler.rb
#!/usr/bin/env ruby
require 'fileutils'
require 'tempfile'
require 'socket'
HOSTS_PATH = '/etc/hosts'
EVENTS = %w(member-join member-leave member-failed)
EXCLUDES = %w(127.0.0.1)
def open_hosts
open(HOSTS_PATH) do |f|
f.flock(File::LOCK_EX)
yield(f)
end
end
def current_hosts(f)
rgx = /\A(#{EXCLUDES.map {|i| Regexp.escape(i) }.join('|')})\s+/
f.read.split("\n").grep(rgx).join("\n")
end
def serf_members
`serf members | grep -v #{Socket.gethostname}`.split("\n").map {|i|
i.split(/[\s:]+/)[0..1].reverse
}.map {|i| i.join("\t") }.join("\n")
end
def update_hosts
open_hosts do |hosts|
Tempfile.open(File.basename(__FILE__)) do |tmp|
tmp.puts current_hosts(hosts)
tmp.puts serf_members
tmp.flush
FileUtils.copy(tmp.path, hosts.path)
end
end
end
if EVENTS.include?(ENV['SERF_EVENT'])
update_hosts
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment