source: fedd/fedd/remote_service.py @ f069052

axis_examplecompt_changesinfo-opsversion-1.30version-2.00version-3.01version-3.02
Last change on this file since f069052 was f069052, checked in by Ted Faber <faber@…>, 15 years ago

Two changes. Get allow_any_CA checking to work (i.e., self signed certs or
certs signed by an unknown entity) and put more of the ZSI-dependent stuff into
the hidden parts or remote_services. Now those routines will find all the
relevant classes and part names from the naming conventions.

  • Property mode set to 100644
File size: 15.5 KB
Line 
1#!/usr/local/bin/python
2
3import copy
4
5from socket import error as socket_error
6
7import M2Crypto.httpslib
8from M2Crypto import SSL
9from M2Crypto.m2xmlrpclib import SSL_Transport
10from M2Crypto.SSL import SSLError
11from ZSI import ParseException, FaultException, SoapWriter
12
13from service_error import service_error
14from xmlrpclib import ServerProxy, dumps, loads, Fault, Error, Binary
15
16import fedd_services
17import fedd_internal_services
18from util import fedd_ssl_context
19from fedid import fedid
20import parse_detail
21
22# Turn off the matching of hostname to certificate ID
23SSL.Connection.clientPostConnectionCheck = None
24
25# Used by the remote_service_base class.
26def to_binary(o):
27    """
28    A function that converts an object into an xmlrpclib.Binary using
29    either its internal packing method, or the standard Binary constructor.
30    """
31    pack = getattr(o, 'pack_xmlrpc', None)
32    if callable(pack): return Binary(pack())
33    else: return Binary(o)
34
35# Classes that encapsulate the process of making and dealing with requests to
36# WSDL-generated and XMLRPC remote accesses. 
37
38class remote_service_base:
39    """
40    This invisible base class encapsulates the functions used to massage the
41    dictionaries used to pass parameters into and out of the RPC formats.  It's
42    mostly a container for the static methods to do that work, but defines some
43    maps sued by sub classes on apply_to_tags
44    """
45    # A map used to convert fedid fields to fedid objects (when the field is
46    # already a string)
47    fedid_to_object = ( ('fedid', lambda x: fedid(bits=x)),)
48    # A map used by apply_to_tags to convert fedids from xmlrpclib.Binary
49    # objects to fedid objects in one sweep.
50    decap_fedids = (('fedid', lambda x: fedid(bits=x.data)),)
51    # A map used to encapsulate fedids into xmlrpclib.Binary objects
52    encap_fedids = (('fedid', to_binary),)
53
54    @staticmethod
55    def pack_soap(container, name, contents):
56        """
57        Convert the dictionary in contents into a tree of ZSI classes.
58
59        The holder classes are constructed from factories in container and
60        assigned to either the element or attribute name.  This is used to
61        recursively create the SOAP message.
62        """
63        if getattr(contents, "__iter__", None) != None:
64            attr =getattr(container, "new_%s" % name, None)
65            if attr: obj = attr()
66            else:
67                raise TypeError("%s does not have a new_%s attribute" % \
68                        (container, name))
69            for e, v in contents.iteritems():
70                assign = getattr(obj, "set_element_%s" % e, None) or \
71                        getattr(obj, "set_attribute_%s" % e, None)
72                if isinstance(v, type(dict())):
73                    assign(remote_service_base.pack_soap(obj, e, v))
74                elif getattr(v, "__iter__", None) != None:
75                    assign([ remote_service_base.pack_soap(obj, e, val ) \
76                            for val in v])
77                elif getattr(v, "pack_soap", None) != None:
78                    assign(v.pack_soap())
79                else:
80                    assign(v)
81            return obj
82        else: return contents
83
84    @staticmethod
85    def unpack_soap(element):
86        """
87        Convert a tree of ZSI SOAP classes intro a hash.  The inverse of
88        pack_soap
89
90        Elements or elements that are empty are ignored.
91        """
92        methods = [ m for m in dir(element) \
93                if m.startswith("get_element") or m.startswith("get_attribute")]
94        if len(methods) > 0:
95            rv = { }
96            for m in methods:
97                if m.startswith("get_element_"):
98                    n = m.replace("get_element_","",1)
99                else:
100                    n = m.replace("get_attribute_", "", 1)
101                sub = getattr(element, m)()
102                if sub != None:
103                    if isinstance(sub, basestring):
104                        rv[n] = sub
105                    elif getattr(sub, "__iter__", None) != None:
106                        if len(sub) > 0: rv[n] = \
107                                [remote_service_base.unpack_soap(e) \
108                                    for e in sub]
109                    else:
110                        rv[n] = remote_service_base.unpack_soap(sub)
111            return rv
112        else: 
113            return element
114
115    @staticmethod
116    def apply_to_tags(e, map):
117        """
118        Map is an iterable of ordered pairs (tuples) that map a key to a
119        function.
120        This function walks the given message and replaces any object with a
121        key in the map with the result of applying that function to the object.
122        """
123        if isinstance(e, dict):
124            for k in e.keys():
125                for tag, fcn in map:
126                    if k == tag:
127                        if isinstance(e[k], list):
128                            e[k] = [ fcn(b) for b in e[k]]
129                        else:
130                            e[k] = fcn(e[k])
131                    elif isinstance(e[k], dict):
132                        remote_service_base.apply_to_tags(e[k], map)
133                    elif isinstance(e[k], list):
134                        for ee in e[k]:
135                            remote_service_base.apply_to_tags(ee, map)
136        # Other types end the recursion - they should be leaves
137        return e
138
139    @staticmethod
140    def strip_unicode(obj):
141        """Walk through a message and convert all strings to non-unicode
142        strings"""
143        if isinstance(obj, dict):
144            for k in obj.keys():
145                obj[k] = remote_service_base.strip_unicode(obj[k])
146            return obj
147        elif isinstance(obj, basestring) and not isinstance(obj, str):
148            return str(obj)
149        elif getattr(obj, "__iter__", None):
150            return [ remote_service_base.strip_unicode(x) for x in obj]
151        else:
152            return obj
153
154    @staticmethod
155    def make_unicode(obj):
156        """Walk through a message and convert all strings to unicode"""
157        if isinstance(obj, dict):
158            for k in obj.keys():
159                obj[k] = remote_service_base.make_unicode(obj[k])
160            return obj
161        elif isinstance(obj, basestring) and not isinstance(obj, unicode):
162            return unicode(obj)
163        elif getattr(obj, "__iter__", None):
164            return [ remote_service_base.make_unicode(x) for x in obj]
165        else:
166            return obj
167
168
169
170class soap_handler(remote_service_base):
171    """
172    Encapsulate the handler code to unpack and pack SOAP requests and responses
173    and call the given method.
174
175    The code to decapsulate and encapsulate parameters encoded in SOAP is the
176    same modulo a few parameters.  This is a functor that calls a fedd service
177    trhough a soap interface.  The parameters are the typecode of the request
178    parameters, the method to call (usually a bound instance of a method on a
179    fedd service providing class), the constructor of a response packet and the
180    name of the body element of that packet.  The handler takes a ParsedSoap
181    object (the request) and returns an instance of the class created by
182    constructor containing the response.  Failures of the constructor or badly
183    created constructors will result in None being returned.
184    """
185    def __init__(self, service_name, method, typecode=None,
186            constructor=None, body_name=None):
187        self.method = method
188
189        response_class_name = "%sResponseMessage" % service_name
190        request_class_name = "%sRequestMessage" % service_name
191
192        if body_name: self.body_name = body_name
193        else: self.body_name = "%sResponseBody" % service_name
194
195        if constructor: self.constructor = constructor
196        else:
197            self.constructor = self.get_class(response_class_name)
198            if not self.constructor:
199                raise service_error(service_error.internal,
200                        "Cannot find class for %s" % response_class_name)
201
202        if typecode: self.typecode = typecode
203        else: 
204            req = self.get_class(request_class_name)
205            if req:
206                self.typecode = req.typecode
207            else:
208                raise service_error(service_error.internal,
209                        "Cannot find class for %s" % request_class_name)
210
211            if not self.typecode:
212                raise service_error(service_error.internal,
213                        "Cannot get typecode for %s" % class_name)
214
215    def get_class(self, class_name):
216        return getattr(fedd_services, class_name, None) or \
217                getattr(fedd_internal_services, class_name, None)
218
219    def __call__(self, ps, fid):
220        req = ps.Parse(self.typecode)
221        # Convert the message to a dict with the fedid strings converted to
222        # fedid objects
223        req = self.apply_to_tags(self.unpack_soap(req), self.fedid_to_object)
224
225        msg = self.method(req, fid)
226
227        resp = self.constructor()
228        set_element = getattr(resp, "set_element_%s" % self.body_name, None)
229        print "set_element_%s" % self.body_name
230        if set_element and callable(set_element):
231            try:
232                set_element(self.pack_soap(resp, self.body_name, msg))
233                return resp
234            except (NameError, TypeError):
235                return None
236        else:
237            return None
238
239class xmlrpc_handler(remote_service_base):
240    """
241    Generate the handler code to unpack and pack XMLRPC requests and responses
242    and call the given method.
243
244    The code to marshall and unmarshall XMLRPC parameters to and from a fedd
245    service is largely the same.  This helper creates such a handler.  The
246    parameters are the method name, and the name of the body struct that
247    contains the response.  A handler is created that takes the params response
248    from an xmlrpclib.loads on the incoming rpc and a fedid and responds with
249    a hash representing the struct ro be returned to the other side.  On error
250    None is returned.  Fedid fields are decapsulated from binary and converted
251    to fedid objects on input and encapsulated as Binaries on output.
252    """
253    def __init__(self, service_name, method):
254        self.method = method
255        self.body_name = "%sResponseBody" % service_name
256
257    def __call__(self, params, fid):
258        msg = None
259
260        p = self.apply_to_tags(params[0], self.decap_fedids)
261        try:
262            msg = self.method(p, fid)
263        except service_error, e:
264            raise Fault(e.code_string(), e.desc)
265        if msg != None:
266            return self.make_unicode(self.apply_to_tags(\
267                    { self.body_name: msg }, self.encap_fedids))
268        else:
269            return None
270
271class service_caller(remote_service_base):
272    def __init__(self, service_name, request_message=None, 
273            request_body_name=None, tracefile=None):
274        self.service_name = service_name
275
276        if getattr(fedd_services.feddBindingSOAP, service_name, None):
277            self.locator = fedd_services.feddServiceLocator
278            self.port_name = 'getfeddPortType'
279        elif getattr(fedd_internal_services.feddInternalBindingSOAP, 
280                service_name, None):
281            self.locator = fedd_internal_services.feddInternalServiceLocator
282            self.port_name = 'getfeddInternalPortType'
283
284        if request_message: self.request_message = request_message
285        else:
286            request_message_name = "%sRequestMessage" % service_name
287            self.request_message = \
288                    getattr(fedd_services, request_message_name, None) or \
289                    getattr(fedd_internal_services, request_message_name, None)
290            if not self.request_message:
291                raise service_error(service_error.internal,
292                        "Cannot find class for %s" % request_message_name)
293
294        if request_body_name: self.request_body_name = request_body_name
295        else: self.request_body_name = "%sRequestBody" % service_name
296
297        self.tracefile = tracefile
298        self.__call__ = self.call_service
299
300    def serialize_soap(self, req):
301        """
302        Return a string containing the message that would be sent to call this
303        service with the given request.
304        """
305        msg = self.request_message()
306        set_element = getattr(msg, "set_element_%s" % self.request_body_name,
307                None)
308        if not set_element:
309            raise service_error(service_error.internal,
310                    "Cannot get element setting method for %s" % \
311                            self.request_body_name)
312        set_element(self.pack_soap(msg, self.request_body_name, req))
313        sw = SoapWriter()
314        sw.serialize(msg)
315        return unicode(sw)
316
317    def call_xmlrpc_service(self, url, req, cert_file=None, cert_pwd=None, 
318            trusted_certs=None, context=None, tracefile=None):
319        """Send an XMLRPC request.  """
320
321
322        # If a context is given, use it.  Otherwise construct one from
323        # components.  The construction shouldn't call out for passwords.
324        if context:
325            ctx = context
326        else:
327            try:
328                ctx = fedd_ssl_context(cert_file, trusted_certs, 
329                        password=cert_pwd)
330            except SSL.SSLError:
331                raise service_error(service_error.server_config,
332                        "Certificates misconfigured")
333
334        # Of all the dumbass things.  The XMLRPC library in use here won't
335        # properly encode unicode strings, so we make a copy of req with
336        # the unicode objects converted.  We also convert the url to a
337        # basic string if it isn't one already.
338        r = self.strip_unicode(copy.deepcopy(req))
339        url = str(url)
340       
341        transport = SSL_Transport(ctx)
342        port = ServerProxy(url, transport=transport)
343        # Make the call, and convert faults back to service_errors
344        try:
345            remote_method = getattr(port, self.service_name, None)
346            resp = remote_method(self.apply_to_tags(\
347                    { self.request_body_name: r}, self.encap_fedids))
348        except socket_error, e:
349            raise service_error(service_error.protocol, 
350                    "Cannot connect to %s: %s" % (url, e[1]))
351        except SSLError, e:
352            raise service_error(service_error.protocol,
353                    "SSL error contacting %s: %s" % (url, e.message))
354        except Fault, f:
355            raise service_error(None, f.faultString, f.faultCode)
356        except Error, e:
357            raise service_error(service_error.protocol, 
358                    "Remote XMLRPC Fault: %s" % e)
359
360        return self.apply_to_tags(resp, self.decap_fedids) 
361
362    def call_soap_service(self, url, req, cert_file=None, cert_pwd=None,
363            trusted_certs=None, context=None, tracefile=None):
364        """
365        Send req on to the real destination in dt and return the response
366
367        Req is just the requestType object.  This function re-wraps it.  It
368        also rethrows any faults.
369        """
370
371        tf = tracefile or self.tracefile or None
372
373        # If a context is given, use it.  Otherwise construct one from
374        # components.  The construction shouldn't call out for passwords.
375        if context:
376            ctx = context
377        else:
378            try:
379                ctx = fedd_ssl_context(cert_file, trusted_certs, 
380                        password=cert_pwd)
381            except SSL.SSLError:
382                raise service_error(service_error.server_config,
383                        "Certificates misconfigured")
384        loc = self.locator()
385        get_port = getattr(loc, self.port_name, None)
386        if not get_port:
387            raise service_error(service_error.internal, 
388                    "Cannot get port %s from locator" % self.port_name)
389        port = get_port(url,
390                transport=M2Crypto.httpslib.HTTPSConnection, 
391                transdict={ 'ssl_context' : ctx },
392                tracefile=tf)
393        remote_method = getattr(port, self.service_name, None)
394        if not remote_method:
395            raise service_error(service_error.internal,
396                    "Cannot get service from SOAP port")
397
398        # Reconstruct the full request message
399        msg = self.request_message()
400        set_element = getattr(msg, "set_element_%s" % self.request_body_name,
401                None)
402        if not set_element:
403            raise service_error(service_error.internal,
404                    "Cannot get element setting method for %s" % \
405                            self.request_body_name)
406        set_element(self.pack_soap(msg, self.request_body_name, req))
407        try:
408            resp = remote_method(msg)
409        except socket_error, e:
410            raise service_error(service_error.protocol, 
411                    "Cannot connect to %s: %s" % (url, e[1]))
412        except SSLError, e:
413            raise service_error(service_error.protocol,
414                    "SSL error contacting %s: %s" % (url, e.message))
415        except ParseException, e:
416            raise service_error(service_error.protocol,
417                    "Bad format message (XMLRPC??): %s" % e)
418        except FaultException, e:
419            ee = self.unpack_soap(e.fault.detail[0]).get('FeddFaultBody', { })
420            if ee:
421                raise service_error(ee['code'], ee['desc'])
422            else:
423                raise service_error(service_error.internal,
424                        "Unexpected fault body")
425        # Unpack and convert fedids to objects
426        r = self.apply_to_tags(self.unpack_soap(resp), self.fedid_to_object)
427        #  Make sure all strings are unicode
428        r = self.make_unicode(r)
429        return r
430
431    def call_service(self, url, req, cert_file=None, cert_pwd=None, 
432        trusted_certs=None, context=None, tracefile=None):
433        p_fault = None  # Any SOAP failure (sent unless XMLRPC works)
434        resp = None
435        try:
436            # Try the SOAP request
437            resp = self.call_soap_service(url, req, 
438                    cert_file, cert_pwd, trusted_certs, context, tracefile)
439            return resp
440        except service_error, e:
441            if e.code == service_error.protocol: p_fault = None
442            else: raise
443        except FaultException, f:
444            p_fault = f.fault.detail[0]
445               
446
447        # If we could not get a valid SOAP response to the request above,
448        # try the same address using XMLRPC and let any faults flow back
449        # out.
450        if p_fault == None:
451            resp = self.call_xmlrpc_service(url, req, cert_file,
452                    cert_pwd, trusted_certs, context, tracefile)
453            return resp
454        else:
455            # Build the fault
456            ee = unpack_soap(p_fault).get('FeddFaultBody', { })
457            if ee:
458                raise service_error(ee['code'], ee['desc'])
459            else:
460                raise service_error(service_error.internal,
461                        "Unexpected fault body")
Note: See TracBrowser for help on using the repository browser.