Skip to content

Instantly share code, notes, and snippets.

@csabahenk
Last active December 2, 2016 14:48
Show Gist options
  • Save csabahenk/06e295f69b81f6a74c005aab237f3db6 to your computer and use it in GitHub Desktop.
Save csabahenk/06e295f69b81f6a74c005aab237f3db6 to your computer and use it in GitHub Desktop.
gluster volfile parser / extractor
#!/usr/bin/env ruby
module GlusterConf
extend self
class GlusterConfError < Exception
end
def assert x, *bool
bool.each { |b| raise GlusterConfError, "#{$.}: #{x}" unless bool }
end
def parse src
volh = {}
vol = {}
src.each { |l|
ls = l.split
case ls[0]
when "volume"
assert l, ls.size == 2, vol.empty?
vol["name"] = ls[1]
when "type"
assert l, ls.size == 2, vol["name"], !vol["type"]
vol["type"] = ls[1]
when "option"
assert l, ls.size == 3, vol["name"]
(vol["option"] ||= {})[ls[1]] = case ls[2]
when /\A\d+\Z/
Integer ls[2]
when /\Aon|yes|true|enable\Z/i
true
when /\Aoff|no|false|disable\Z/i
false
else
ls[2]
end
when "subvolumes"
assert l, ls.size > 1, vol["name"], !vol["subvolumes"]
vol["subvolumes"] = ls[1..-1]
when "end-volume"
assert l, ls.size == 1, vol["name"], vol["type"]
volh[vol["name"]] = vol
vol = {}
when nil
else
assert l, false
end
}
# XXX we could have more proper check to see if graph is a tree
subvolumes = []
volh.each_value { |vol| subvolumes.concat(vol["subvolumes"] || []) }
topvols = volh.keys - subvolumes
assert "ambiguous toplevel volume: #{topvols.join(", ")}", topvols.size == 1
topvol = volh[topvols[0]]
volh.each_value { |vol| (vol["subvolumes"] || []).map! { |w| volh.fetch w } }
topvol
end
end
if __FILE__ == $0
require 'yaml'
$*.each { |f|
print GlusterConf.parse(
f == "-" ? STDIN : IO.readlines(f)).to_yaml
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment