source: fedd/federation/remote_service.py @ f585453

compt_changesinfo-ops
Last change on this file since f585453 was ca5cda7, checked in by Ted Faber <faber@…>, 13 years ago

Allow override of fedd_translations

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