clean up code for python < 2.7
[sfa.git] / sfa / client / sfaserverproxy.py
1 # XMLRPC-specific code for SFA Client
2
3 # starting with 2.7.9 we need to turn off server verification
4 import ssl
5 ssl_needs_unverified_context = hasattr(ssl, '_create_unverified_context')
6
7 import xmlrpclib
8 from httplib import HTTPS, HTTPSConnection
9
10 try:
11     from sfa.util.sfalogging import logger
12 except:
13     import logging
14     logger = logging.getLogger('sfaserverproxy')
15
16 ##
17 # ServerException, ExceptionUnmarshaller
18 #
19 # Used to convert server exception strings back to an exception.
20 #    from usenet, Raghuram Devarakonda
21
22 class ServerException(Exception):
23     pass
24
25 class ExceptionUnmarshaller(xmlrpclib.Unmarshaller):
26     def close(self):
27         try:
28             return xmlrpclib.Unmarshaller.close(self)
29         except xmlrpclib.Fault, e:
30             raise ServerException(e.faultString)
31
32 ##
33 # XMLRPCTransport
34 #
35 # A transport for XMLRPC that works on top of HTTPS
36
37 # targetting only python-2.7 we can get rid of some older code
38
39 class XMLRPCTransport(xmlrpclib.Transport):
40     
41     def __init__(self, key_file = None, cert_file = None, timeout = None):
42         xmlrpclib.Transport.__init__(self)
43         self.timeout=timeout
44         self.key_file = key_file
45         self.cert_file = cert_file
46         
47     def make_connection(self, host):
48         # create a HTTPS connection object from a host descriptor
49         # host may be a string, or a (host, x509-dict) tuple
50         host, extra_headers, x509 = self.get_host_info(host)
51         if not ssl_needs_unverified_context:
52             conn = HTTPSConnection(host, None, key_file = self.key_file,
53                                    cert_file = self.cert_file)
54         else:
55             conn = HTTPSConnection(host, None, key_file = self.key_file,
56                                    cert_file = self.cert_file,
57                                    context = ssl._create_unverified_context())
58
59         # Some logic to deal with timeouts. It appears that some (or all) versions
60         # of python don't set the timeout after the socket is created. We'll do it
61         # ourselves by forcing the connection to connect, finding the socket, and
62         # calling settimeout() on it. (tested with python 2.6)
63         if self.timeout:
64             if hasattr(conn, 'set_timeout'):
65                 conn.set_timeout(self.timeout)
66
67             if hasattr(conn, "_conn"):
68                 # HTTPS is a wrapper around HTTPSConnection
69                 real_conn = conn._conn
70             else:
71                 real_conn = conn
72             conn.connect()
73             if hasattr(real_conn, "sock") and hasattr(real_conn.sock, "settimeout"):
74                 real_conn.sock.settimeout(float(self.timeout))
75
76         return conn
77
78     def getparser(self):
79         unmarshaller = ExceptionUnmarshaller()
80         parser = xmlrpclib.ExpatParser(unmarshaller)
81         return parser, unmarshaller
82
83 class XMLRPCServerProxy(xmlrpclib.ServerProxy):
84     def __init__(self, url, transport, allow_none=True, verbose=False):
85         # remember url for GetVersion
86         # xxx not sure this is still needed as SfaServerProxy has this too
87         self.url=url
88         if not ssl_needs_unverified_context:
89             xmlrpclib.ServerProxy.__init__(self, url, transport, allow_none=allow_none,
90                                            verbose=verbose)
91         else:
92             xmlrpclib.ServerProxy.__init__(self, url, transport, allow_none=allow_none,
93                                            verbose=verbose,
94                                            context=ssl._create_unverified_context())
95
96     def __getattr__(self, attr):
97         logger.debug ("xml-rpc %s method:%s" % (self.url, attr))
98         return xmlrpclib.ServerProxy.__getattr__(self, attr)
99
100 ########## the object on which we can send methods that get sent over xmlrpc
101 class SfaServerProxy:
102
103     def __init__ (self, url, keyfile, certfile, verbose=False, timeout=None):
104         self.url = url
105         self.keyfile = keyfile
106         self.certfile = certfile
107         self.verbose = verbose
108         self.timeout = timeout
109         # an instance of xmlrpclib.ServerProxy
110         transport = XMLRPCTransport(keyfile, certfile, timeout)
111         self.serverproxy = XMLRPCServerProxy(url, transport, allow_none=True, verbose=verbose)
112
113     # this is python magic to return the code to run when 
114     # SfaServerProxy receives a method call
115     # so essentially we send the same method with identical arguments
116     # to the server_proxy object
117     def __getattr__(self, name):
118         def func(*args, **kwds):
119             return getattr(self.serverproxy, name)(*args, **kwds)
120         return func
121