cb765e035eb612ea25eece4ebfa61f5fcf9bb44b
[sfa.git] / sfa / client / getRecord.py
1 #!/usr/bin/python
2
3 """
4 Filters/Prints record objects
5
6
7 faiyaza at cs dot princeton dot edu
8 Copyright (c) 2009 Board of Trustees, Princeton University
9
10 """
11
12 import sys
13 import os
14 from optparse import OptionParser
15 from pprint import pprint
16 from xml.parsers.expat import ExpatError
17
18 from sfa.util.rspec import RecordSpec
19
20
21 def create_parser():
22     command = sys.argv[0]
23     argv = sys.argv[1:]
24     usage = "%(command)s [options]" % locals()
25     description = """getRecord will parse a supplied (via stdin) record and print all values or key/values, and filter results based on a given key or set of keys."""
26     parser = OptionParser(usage=usage,description=description)
27     parser.add_option("-d", "--debug", dest="DEBUG", action="store_true",
28         default=False,  help = "record file path")
29     parser.add_option("-k", "--key", dest="withkey", action="store_true",
30         default=False,  help = "print SSH keys and certificates")
31     parser.add_option("-p", "--plinfo", dest="plinfo", action="store_true",
32         default=False,  help = "print PlanetLab specific internal fields")
33    
34     return parser    
35
36
37 def printRec(record, filters, options):
38     line = ""
39     if len(filters):
40         for filter in filters:
41             if options.DEBUG:  print "Filtering on %s" %filter
42             line += "%s: %s\n" % (filter, 
43                 printVal(record.dict["record"].get(filter, None)))
44         print line
45     else:
46         # print the wole thing
47         for (key, value) in record.dict["record"].iteritems():
48             if (not options.withkey and key in ('gid', 'keys')) or\
49                 (not options.plinfo and key == 'pl_info'):
50                 continue
51             line += "%s: %s\n" % (key, printVal(value))
52         print line
53
54
55 # fix the iteratable values
56 def printVal(value):
57     line = ""
58     if type(value) in (tuple, list):
59         for i in value:
60             line += "%s " % i
61     elif value != None:
62         line += value
63     return line.rstrip("\n")
64
65
66 def main():
67     parser = create_parser(); 
68     (options, args) = parser.parse_args()
69
70     stdin = sys.stdin.read()
71     
72     record = RecordSpec(xml = stdin)
73     
74     if not record.dict.has_key("record"):
75         raise "RecordError", "Input record does not have 'record' tag."
76
77     if options.DEBUG: 
78         record.pprint()
79         print "#####################################################"
80
81     printRec(record, args, options)
82
83 if __name__ == '__main__':
84     try: main()
85     except ExpatError, e:
86         print "RecordError.  Is your record valid XML?"
87         print e
88     except Exception, e:
89         print e