Last active
August 29, 2015 13:57
-
-
Save winebarrel/9447917 to your computer and use it in GitHub Desktop.
Kumogata+Serf- event_handler.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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