Last active
August 20, 2017 07:32
-
-
Save teruo41/9a49cb3af662b510054d08035fe45e36 to your computer and use it in GitHub Desktop.
Exporting XFS inventory in JSON format
This file contains 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 python3 | |
import sys # for sys.stderr | |
import argparse | |
import subprocess | |
import json | |
class Xfsinv2json: | |
def parse_args(self): | |
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) | |
parser.add_argument("-f", "--filter", type=str, | |
help="Filtering option passed to xfsdump command\n" | |
+"using result of: 'xfsdump -I FILTER'") | |
parser.add_argument("-i", "--indent", type=int, default=4, | |
help="Indent width used when print JSON") | |
self.args = parser.parse_args() | |
def execute_xfsdump(self): | |
cmd = ["xfsdump", "-I"] | |
if self.args.filter: cmd.append(self.args.filter) | |
self.contents = subprocess.check_output(cmd).decode('utf-8') | |
def count_indent(self, s): | |
n = 0 | |
for c in s: | |
if c != u'\t': break | |
else: n += 1 | |
return n | |
def create_dict_ptrs(self): | |
def count_max_indent(s): | |
m = 0 | |
for l in s.splitlines(): | |
i = self.count_indent(l) | |
if m < i: m = i | |
return m | |
self.dict_ptrs = [ {} for i in range(count_max_indent(self.contents)+1) ] | |
def construct_nasted_dictionary(self): | |
def create_list_item(d, e): | |
# "file system 0:" => name="file system", num=0 | |
name = " ".join(e[0].split(" ")[0:len(e[0].split(" "))-1]) | |
num = int(e[0].split(" ")[-1]) | |
if not name in d: d[name] = [] | |
d[name].append({}) | |
return d[name][-1] # type => dict | |
for l in self.contents.splitlines(): | |
i = self.count_indent(l) | |
d = self.dict_ptrs[i] | |
if l == "xfsdump: Dump Status: SUCCESS": | |
self.success = True | |
continue | |
e = list(map(lambda x: x.strip("\t"), l.split(":"))) | |
if len(e) == 2 and l[-1] == ":": | |
# create new list item when the line ends with ":" | |
self.dict_ptrs[i+1] = create_list_item(d, e) | |
else: | |
d[e[0]] = ":".join(e[1:len(e)]) # value may contain ":" | |
def print_json(self): | |
print(json.dumps(self.dict_ptrs[0], | |
sort_keys=True, | |
indent=self.args.indent)) | |
def run(self): | |
self.parse_args() | |
self.execute_xfsdump() | |
self.create_dict_ptrs() | |
self.construct_nasted_dictionary() | |
if self.success: | |
self.print_json() | |
else: | |
print("Error executing xfsdump", file=sys.stderr) | |
if __name__ == "__main__": | |
Xfsinv2json().run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment