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