Merge branch 'upstreammaster'
[sfa.git] / clientbin / 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 from sfa.util.xml import XML    
18
19 def create_parser():
20     command = sys.argv[0]
21     argv = sys.argv[1:]
22     usage = "%(command)s [options]" % locals()
23     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."""
24     parser = OptionParser(usage=usage,description=description)
25     parser.add_option("-d", "--debug", dest="DEBUG", action="store_true",
26         default=False,  help = "record file path")
27     parser.add_option("-k", "--key", dest="withkey", action="store_true",
28         default=False,  help = "print SSH keys and certificates")
29     parser.add_option("-p", "--plinfo", dest="plinfo", action="store_true",
30         default=False,  help = "print PlanetLab specific internal fields")
31    
32     return parser    
33
34
35 def printRec(record_dict, filters, options):
36     line = ""
37     if len(filters):
38         for filter in filters:
39             if options.DEBUG:  print "Filtering on %s" %filter
40             line += "%s: %s\n" % (filter, 
41                 printVal(record_dict.get(filter, None)))
42         print line
43     else:
44         # print the wole thing
45         for (key, value) in record_dict.iteritems():
46             if (not options.withkey and key in ('gid', 'keys')) or\
47                 (not options.plinfo and key == 'pl_info'):
48                 continue
49             line += "%s: %s\n" % (key, printVal(value))
50         print line
51
52
53 # fix the iteratable values
54 def printVal(value):
55     line = ""
56     if type(value) in (tuple, list):
57         for i in value:
58             line += "%s " % i
59     elif value != None:
60         line += value
61     return line.rstrip("\n")
62
63
64 def main():
65     parser = create_parser(); 
66     (options, args) = parser.parse_args()
67
68     stdin = sys.stdin.read()
69     
70     record = XML(stdin)
71     record_dict = record.todict()
72     
73     if options.DEBUG: 
74         pprint(record.toxml())
75         print "#####################################################"
76
77     printRec(record_dict, args, options)
78
79 if __name__ == '__main__':
80     try: main()
81     except ExpatError, e:
82         print "RecordError.  Is your record valid XML?"
83         print e
84     except Exception, e:
85         print e