Last active
December 2, 2016 14:48
-
-
Save csabahenk/06e295f69b81f6a74c005aab237f3db6 to your computer and use it in GitHub Desktop.
gluster volfile parser / extractor
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 | |
module GlusterConf | |
extend self | |
class GlusterConfError < Exception | |
end | |
def assert x, *bool | |
bool.each { |b| raise GlusterConfError, "#{$.}: #{x}" unless bool } | |
end | |
LOGSEP = /\A\+---/ | |
IDP = proc {|x| x} | |
# extract conf from logs | |
def preparse src | |
vols = [] | |
in_vol = nil | |
is_log = nil | |
preprocess = nil | |
src.each { |l| | |
(preprocess || IDP)[l] =~ /\A\s*\Z/ and next | |
if in_vol | |
if is_log and l =~ LOGSEP | |
in_vol = false | |
else | |
vols.last << preprocess[l] | |
end | |
else | |
if l =~ /\A\s*(volume|type|option|subvolumes|end-volume)(\s|\Z)/ | |
in_vol == false and raise "mixed source" | |
in_vol = true | |
preprocess = IDP | |
is_log = false | |
vols << [l] | |
else | |
is_log = true | |
preprocess ||= proc { |x| x.sub /\A\s*\d+: /, "" } | |
if l =~ LOGSEP | |
in_vol = true | |
vols << [] | |
end | |
end | |
end | |
} | |
vols | |
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| | |
GlusterConf.module_eval { | |
preparse(f == "-" ? STDIN : IO.readlines(f)).each { |v| | |
print parse(v).to_yaml | |
} | |
} | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment