source: fedd/federation/server.py @ 1d91791f

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

Wholesale change of IOError to EnvironmentError? for file operations. Lots of
uncaught EnvironmentErrors? were causing spurious error conditions, e.g. on disk
full.

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