Fix error when sorting Job list by object.
[ganeti_webmgr.git] / ganeti_web / util / sshkeys.py
blob80c72daf28587c8a969a8aad20fb2fdff2f79d26
1 #!/usr/bin/env python
2 # coding: utf-8
4 from optparse import OptionParser
5 from urllib2 import urlopen
6 from urlparse import urlparse, urlunparse
7 import sys
9 from django.utils import simplejson as json
11 parser = OptionParser()
12 parser.add_option("-c", "--cluster", help="cluster to retrieve keys from")
13 parser.add_option("-i", "--instance", help="instance to retrieve keys from")
16 def main():
17 options, arguments = parser.parse_args()
18 if len(arguments) < 2:
19 parser.error("an API key and hostname are required")
20 if options.instance and not options.cluster:
21 parser.error("instances cannot be specified without a cluster")
23 app = Application(arguments[0], arguments[1],
24 cluster_slug=options.cluster, vm_name=options.instance)
25 app.run()
28 class ArgumentException(Exception):
29 """
30 There was a bad argument, or something like that.
31 """
34 class BadMimetype(Exception):
35 """
36 There was a bad MIME type, or something like that.
37 """
40 class Application(object):
41 def __init__(self, api_key, hostname, cluster_slug=None, vm_name=None):
42 if cluster_slug is not None:
43 if vm_name is not None:
44 path = "/cluster/%s/%s/keys/%s/" % (cluster_slug, vm_name,
45 api_key)
46 else:
47 path = "/cluster/%s/keys/%s/" % (cluster_slug, api_key)
48 else:
49 path = "/keys/%s/" % api_key
51 split = urlparse(hostname)
52 self.url = urlunparse(split._replace(path=path))
54 def get(self):
55 """
56 Gets the page specified in __init__
57 """
59 content = urlopen(self.url)
60 if content.info()["Content-Type"] != "application/json":
61 raise BadMimetype("It's not JSON")
62 return content.read()
64 def parse(self, content):
65 """
66 Parses returned results from JSON into Python list
67 """
69 return json.loads(content)
71 def printout(self, data):
72 """
73 Returns string with authorized_keys file syntax and some comments
74 """
76 s = ["%s added automatically for ganeti web manager user: %s" % i
77 for i in data]
78 return "\n".join(s)
80 def run(self):
81 """
82 Combines get, parse and printout methods.
83 """
84 try:
85 s = self.printout(self.parse(self.get()))
86 except Exception, e:
87 sys.stderr.write("Errors occured, could not "
88 "retrieve informations.\n")
89 sys.stderr.write(str(e)+"\n")
90 else:
91 sys.stdout.write(s)
93 if __name__ == "__main__":
94 main()