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