source: fedd/federation/server.py @ 79b6596

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

Try to avoid fedd.py blowing chunks on an error under python 2.4

  • Property mode set to 100755
File size: 6.9 KB
RevLine 
[0a20ef8]1#!/usr/local/bin/python
2
3import sys
4
5from BaseHTTPServer import BaseHTTPRequestHandler
6
7from ZSI import Fault, ParseException, FaultFromNotUnderstood, \
8    FaultFromZSIException, FaultFromException, ParsedSoap, SoapWriter
9
10from M2Crypto import SSL
11from M2Crypto.SSL.SSLServer import ThreadingSSLServer
12import xmlrpclib
13
14from fedid import fedid
15from fedd_services import ns0
16from service_error import *
17
18import logging
[46a0f7a]19import traceback
[0a20ef8]20
21# The SSL server here is based on the implementation described at
22# http://www.xml.com/pub/a/ws/2004/01/20/salz.html
23
24# Turn off the matching of hostname to certificate ID
25SSL.Connection.clientPostConnectionCheck = None
26
[ec4fb42]27class server(ThreadingSSLServer):
[0a20ef8]28    """
29    Interface the fedd services to the XMLRPC and SOAP interfaces
30    """
[46a0f7a]31    def __init__(self, ME, handler, ssl_ctx, impl, debug=False):
[0a20ef8]32        """
33        Create an SSL server that handles the transport in handler using the
34        credentials in ssl_ctx, and interfacing to the implementation of fedd
35        services in fedd.  ME is the host port pair on which to bind.
36        """
37        ThreadingSSLServer.__init__(self, ME, handler, ssl_ctx)
38        self.impl = impl
39        self.soap_methods = impl.soap_services
40        self.xmlrpc_methods = impl.xmlrpc_services
41        self.log = logging.getLogger("fedd")
[46a0f7a]42        if debug: self.handle_error = self.handle_error_debug
43        else: self.handle_error = self.handle_error_standard
[0a20ef8]44
[8072c18]45    def handle_error_debug(self, request=None, client_address=None):
[46a0f7a]46        print '-'*40
47        traceback.print_exc()
48        print '-'*40
49
50
[8072c18]51    def handle_error_standard(self, request=None, address=None):
[0a20ef8]52        """
53        The default SSLServer prints a stack trace here.  This is a little
54        friendlier.
55        """
56        if request or address:
57            self.log.warn("[fedd] Error on incoming connection: %s %s" % \
[8072c18]58                    (request or "", address or ""))
[0a20ef8]59        else:
60            self.log.warn("[fedd] Error on incoming connection " + \
61                    "(Likely SSL error)")
62
[ec4fb42]63class soap_handler(BaseHTTPRequestHandler):
[0a20ef8]64    """
65    Standard connection between SOAP and the fedd services in impl.
66
67    Much of this is boilerplate from
68    http://www.xml.com/pub/a/ws/2004/01/20/salz.html
69    """
70    server_version = "ZSI/2.0 fedd/0.1 " + BaseHTTPRequestHandler.server_version
71
72    def send_xml(self, text, code=200):
73        """Send an XML document as reply"""
74        self.send_response(code)
75        self.send_header('Content-type', 'text/xml; charset="utf-8"')
76        self.send_header('Content-Length', str(len(text)))
77        self.end_headers()
78        self.wfile.write(text)
79        self.wfile.flush()
80        self.request.socket.close()
81
82    def send_fault(self, f, code=500):
83        """Send a SOAP encoded fault as reply"""
84        self.send_xml(f.AsSOAP(processContents="lax"), code)
85
86    def check_headers(self, ps):
87        """Send a fault for any required envelope headers"""
88        for (uri, localname) in ps.WhatMustIUnderstand():
89            self.send_fault(FaultFromNotUnderstood(uri, lname, 'fedd'))
90            return False
91        return  True
92
93    def check_method(self, ps):
94        """Confirm that this class implements the namespace and SOAP method"""
95        root = ps.body_root
96        if root.namespaceURI not in self.server.impl.soap_namespaces:
97            self.send_fault(Fault(Fault.Client, 
98                'Unknown namespace "%s"' % root.namespaceURI))
99            return False
100
101        if getattr(root, 'localName', None) == None:
102            self.send_fault(Fault(Fault.Client, 'No method"'))
103            return False
104        return True
105
106    def do_POST(self):
107        """Treat an HTTP POST request as a SOAP service call"""
108        try:
109            cl = int(self.headers['content-length'])
110            data = self.rfile.read(cl)
111            ps = ParsedSoap(data)
112        except ParseException, e:
113            self.send_fault(Fault(Fault.Client, str(e)))
114            return
115        except Exception, e:
116            self.send_fault(FaultFromException(e, 0, sys.exc_info()[2]))
117            return
118        if not self.check_headers(ps): return
119        if not self.check_method(ps): return
120        try:
121            resp = self.soap_dispatch(ps.body_root.localName, ps,
122                    fedid(cert=self.request.get_peer_cert()))
123        except Fault, f:
124            self.send_fault(f)
125            resp = None
126       
127        if resp != None:
128            sw = SoapWriter()
129            sw.serialize(resp)
130            self.send_xml(str(sw))
131
132    def log_request(self, code=0, size=0):
133        """
134        Log request to the fedd logger
135        """
136        self.server.log.info("Successful SOAP request code %d" % code)
137
138    def soap_dispatch(self, method, req, fid):
139        """
140        The connection to the implementation, using the  method maps
141
142        The implementation provides a mapping from SOAP method name to the
143        method in the implementation that provides the service.
144        """
145        if self.server.soap_methods.has_key(method):
146            try:
147                return self.server.soap_methods[method](req, fid)
148            except service_error, e:
149                de = ns0.faultType_Def(
150                        (ns0.faultType_Def.schema,
151                            "FeddFaultBody")).pyclass()
152                de._code=e.code
153                de._errstr=e.code_string()
154                de._desc=e.desc
155                if  e.is_server_error():
156                    raise Fault(Fault.Server, e.code_string(), detail=de)
157                else:
158                    raise Fault(Fault.Client, e.code_string(), detail=de)
159        else:
160            raise Fault(Fault.Client, "Unknown method: %s" % method)
161
162
[ec4fb42]163class xmlrpc_handler(BaseHTTPRequestHandler):
[0a20ef8]164    """
165    Standard connection between XMLRPC and the fedd services in impl.
166
167    Much of this is boilerplate from
168    http://www.xml.com/pub/a/ws/2004/01/20/salz.html
169    """
170    server_version = "ZSI/2.0 fedd/0.1 " + BaseHTTPRequestHandler.server_version
171
172    def send_xml(self, text, code=200):
173        """Send an XML document as reply"""
174        self.send_response(code)
175        self.send_header('Content-type', 'text/xml; charset="utf-8"')
176        self.send_header('Content-Length', str(len(text)))
177        self.end_headers()
178        self.wfile.write(text)
179        self.wfile.flush()
180        # Make sure to close the socket when we're done
181        self.request.socket.close()
182
183    def do_POST(self):
184        """Treat an HTTP POST request as an XMLRPC service call"""
185        # NB: XMLRPC faults are not HTTP errors, so the code is always 200,
186        # unless an HTTP error occurs, which we don't handle.
187
188        resp = None
189        data = None
190        method = None
191        cl = int(self.headers['content-length'])
192        data = self.rfile.read(cl)
193
194        try:
195            params, method = xmlrpclib.loads(data)
196        except xmlrpclib.ResponseError:
197            data = xmlrpclib.dumps(xmlrpclib.Fault("Client", 
198                "Malformed request"), methodresponse=True)
199
200        if method != None:
201            try:
202                resp = self.xmlrpc_dispatch(method, params,
203                            fedid(cert=self.request.get_peer_cert()))
204                data = xmlrpclib.dumps((resp,), encoding='UTF-8', 
205                        methodresponse=True)
206            except xmlrpclib.Fault, f:
207                data = xmlrpclib.dumps(f, methodresponse=True)
208                resp = None
209
210        self.send_xml(data)
211
212    def log_request(self, code=0, size=0):
213        """
214        Log request to the fedd logger
215        """
216        self.server.log.info("Successful XMLRPC request code %d" % code)
217
218
219    def xmlrpc_dispatch(self, method, req, fid):
220        """
221        The connection to the implementation, using the  method maps
222
223        The implementation provides a mapping from XMLRPC method name to the
224        method in the implementation that provides the service.
225        """
226        if self.server.xmlrpc_methods.has_key(method):
227            try:
228                return self.server.xmlrpc_methods[method](req, fid)
229            except service_error, e:
230                raise xmlrpclib.Fault(e.code_string(), e.desc)
231        else:
232            raise xmlrpclib.Fault(100, "Unknown method: %s" % method)
Note: See TracBrowser for help on using the repository browser.