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