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