Merge branch 'geni-v3' of ssh://git.onelab.eu/git/sfa into geni-v3
[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 # python 2.7 xmlrpclib has changed its internal code
38 # it now calls 'getresponse' on the obj returned by make_connection
39 # while it used to call 'getreply'
40 # regardless of the version, httplib.HTTPS does implement getreply, 
41 # while httplib.HTTPSConnection has getresponse
42 # so we create a dummy instance to check what's expected
43 need_HTTPSConnection=hasattr(xmlrpclib.Transport().make_connection('localhost'),'getresponse')
44
45 class XMLRPCTransport(xmlrpclib.Transport):
46     
47     def __init__(self, key_file=None, cert_file=None, timeout=None):
48         xmlrpclib.Transport.__init__(self)
49         self.timeout=timeout
50         self.key_file = key_file
51         self.cert_file = cert_file
52         
53     def make_connection(self, host):
54         # create a HTTPS connection object from a host descriptor
55         # host may be a string, or a (host, x509-dict) tuple
56         host, extra_headers, x509 = self.get_host_info(host)
57         if need_HTTPSConnection:
58             if not ssl_needs_unverified_context:
59                 conn = HTTPSConnection(host, None, key_file = self.key_file,
60                                        cert_file = self.cert_file)
61             else:
62                 conn = HTTPSConnection(host, None, key_file = self.key_file,
63                                        cert_file = self.cert_file,
64                                        context = ssl._create_unverified_context())
65         else:
66             conn = HTTPS(host, None, key_file=self.key_file, cert_file=self.cert_file)
67
68         # Some logic to deal with timeouts. It appears that some (or all) versions
69         # of python don't set the timeout after the socket is created. We'll do it
70         # ourselves by forcing the connection to connect, finding the socket, and
71         # calling settimeout() on it. (tested with python 2.6)
72         if self.timeout:
73             if hasattr(conn, 'set_timeout'):
74                 conn.set_timeout(self.timeout)
75
76             if hasattr(conn, "_conn"):
77                 # HTTPS is a wrapper around HTTPSConnection
78                 real_conn = conn._conn
79             else:
80                 real_conn = conn
81             conn.connect()
82             if hasattr(real_conn, "sock") and hasattr(real_conn.sock, "settimeout"):
83                 real_conn.sock.settimeout(float(self.timeout))
84
85         return conn
86
87     def getparser(self):
88         unmarshaller = ExceptionUnmarshaller()
89         parser = xmlrpclib.ExpatParser(unmarshaller)
90         return parser, unmarshaller
91
92 class XMLRPCServerProxy(xmlrpclib.ServerProxy):
93     def __init__(self, url, transport, allow_none=True, verbose=False):
94         # remember url for GetVersion
95         # xxx not sure this is still needed as SfaServerProxy has this too
96         self.url=url
97         if not ssl_needs_unverified_context:
98             xmlrpclib.ServerProxy.__init__(self, url, transport, allow_none=allow_none,
99                                            verbose=verbose)
100         else:
101             xmlrpclib.ServerProxy.__init__(self, url, transport, allow_none=allow_none,
102                                            verbose=verbose,
103                                            context=ssl._create_unverified_context())
104
105     def __getattr__(self, attr):
106         logger.debug ("xml-rpc %s method:%s" % (self.url, attr))
107         return xmlrpclib.ServerProxy.__getattr__(self, attr)
108
109 ########## the object on which we can send methods that get sent over xmlrpc
110 class SfaServerProxy:
111
112     def __init__ (self, url, keyfile, certfile, verbose=False, timeout=None):
113         self.url=url
114         self.keyfile=keyfile
115         self.certfile=certfile
116         self.verbose=verbose
117         self.timeout=timeout
118         # an instance of xmlrpclib.ServerProxy
119         transport = XMLRPCTransport(keyfile, certfile, timeout)
120         self.serverproxy = XMLRPCServerProxy(url, transport, allow_none=True, verbose=verbose)
121
122     # this is python magic to return the code to run when 
123     # SfaServerProxy receives a method call
124     # so essentially we send the same method with identical arguments
125     # to the server_proxy object
126     def __getattr__(self, name):
127         def func(*args, **kwds):
128             return getattr(self.serverproxy, name)(*args, **kwds)
129         return func
130