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