1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
|
###########################################################################
# Joshua R. Boverhof, LBNL
# See Copyright for copyright notice!
# $Id: WSresource.py 1287 2006-10-30 23:04:17Z feanor420 $
###########################################################################
import sys, warnings
# twisted & related imports
from zope.interface import classProvides, implements, Interface
from twisted.python import log, failure
from twisted.web.error import NoResource
from twisted.web.server import NOT_DONE_YET
import twisted.web.http
import twisted.web.resource
# ZSI imports
from ZSI import _get_element_nsuri_name, EvaluateException, ParseException
from ZSI.parse import ParsedSoap
from ZSI.writer import SoapWriter
from ZSI import fault
# WS-Address related imports
from ZSI.address import Address
from ZSI.ServiceContainer import WSActionException
#
# Stability: Unstable
#
class HandlerChainInterface(Interface):
def processRequest(self, input, **kw):
"""returns a representation of the request, the
last link in the chain must return a response
pyobj with a typecode attribute.
Parameters:
input --
Keyword Parameters:
request -- HTTPRequest instance
resource -- Resource instance
"""
def processResponse(self, output, **kw):
"""returns a string representing the soap response.
Parameters
output --
Keyword Parameters:
request -- HTTPRequest instance
resource -- Resource instance
"""
class CallbackChainInterface(Interface):
def processRequest(self, input, **kw):
"""returns a response pyobj with a typecode
attribute.
Parameters:
input --
Keyword Parameters:
request -- HTTPRequest instance
resource -- Resource instance
"""
class DataHandler:
"""
class variables:
readerClass -- factory class to create reader for ParsedSoap instances.
writerClass -- ElementProxy implementation to use for SoapWriter instances.
"""
classProvides(HandlerChainInterface)
readerClass = None
writerClass = None
@classmethod
def processRequest(cls, input, **kw):
return ParsedSoap(input, readerclass=cls.readerClass)
@classmethod
def processResponse(cls, output, **kw):
sw = SoapWriter(outputclass=cls.writerClass)
sw.serialize(output)
return sw
class DefaultCallbackHandler:
classProvides(CallbackChainInterface)
@classmethod
def processRequest(cls, ps, **kw):
"""invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request
"""
resource = kw['resource']
request = kw['request']
method = getattr(resource, 'soap_%s' %
_get_element_nsuri_name(ps.body_root)[-1])
try:
req_pyobj,rsp_pyobj = method(ps, request=request)
except TypeError, ex:
log.err(
'ERROR: service %s is broken, method MUST return request, response'\
% cls.__name__
)
raise
except Exception, ex:
log.err('failure when calling bound method')
raise
return rsp_pyobj
class WSAddressHandler:
"""General WS-Address handler. This implementation depends on a
'wsAction' dictionary in the service stub which contains keys to
WS-Action values.
Implementation saves state on request response flow, so using this
handle is not reliable if execution is deferred between proceesRequest
and processResponse.
TODO: sink this up with wsdl2dispatch
TODO: reduce coupling with WSAddressCallbackHandler.
"""
implements(HandlerChainInterface)
def processRequest(self, ps, **kw):
# TODO: Clean this up
resource = kw['resource']
d = getattr(resource, 'root', None)
key = _get_element_nsuri_name(ps.body_root)
if d is None or d.has_key(key) is False:
raise RuntimeError,\
'Error looking for key(%s) in root dictionary(%s)' %(key, str(d))
self.op_name = d[key]
self.address = address = Address()
address.parse(ps)
action = address.getAction()
if not action:
raise WSActionException('No WS-Action specified in Request')
request = kw['request']
http_headers = request.getAllHeaders()
soap_action = http_headers.get('soapaction')
if soap_action and soap_action.strip('\'"') != action:
raise WSActionException(\
'SOAP Action("%s") must match WS-Action("%s") if specified.'\
%(soap_action,action)
)
# Save WS-Address in ParsedSoap instance.
ps.address = address
return ps
def processResponse(self, sw, **kw):
if sw is None:
self.address = None
return
request, resource = kw['request'], kw['resource']
if isinstance(request, twisted.web.http.Request) is False:
raise TypeError, '%s instance expected' %http.Request
d = getattr(resource, 'wsAction', None)
key = self.op_name
if d is None or d.has_key(key) is False:
raise WSActionNotSpecified,\
'Error looking for key(%s) in wsAction dictionary(%s)' %(key, str(d))
addressRsp = Address(action=d[key])
if request.transport.TLS == 0:
addressRsp.setResponseFromWSAddress(\
self.address, 'http://%s:%d%s' %(
request.host.host, request.host.port, request.path)
)
else:
addressRsp.setResponseFromWSAddress(\
self.address, 'https://%s:%d%s' %(
request.host.host, request.host.port, request.path)
)
addressRsp.serialize(sw, typed=False)
self.address = None
return sw
class WSAddressCallbackHandler:
classProvides(CallbackChainInterface)
@classmethod
def processRequest(cls, ps, **kw):
"""invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request
"""
resource = kw['resource']
request = kw['request']
method = getattr(resource, 'wsa_%s' %
_get_element_nsuri_name(ps.body_root)[-1])
# TODO: grab ps.address, clean this up.
try:
req_pyobj,rsp_pyobj = method(ps, ps.address, request=request)
except TypeError, ex:
log.err(
'ERROR: service %s is broken, method MUST return request, response'\
%self.__class__.__name__
)
raise
except Exception, ex:
log.err('failure when calling bound method')
raise
return rsp_pyobj
def CheckInputArgs(*interfaces):
"""Must provide at least one interface, the last one may be repeated.
"""
l = len(interfaces)
def wrapper(func):
def check_args(self, *args, **kw):
for i in range(len(args)):
if (l > i and interfaces[i].providedBy(args[i])) or interfaces[-1].providedBy(args[i]):
continue
if l > i: raise TypeError, 'arg %s does not implement %s' %(args[i], interfaces[i])
raise TypeError, 'arg %s does not implement %s' %(args[i], interfaces[-1])
func(self, *args, **kw)
return check_args
return wrapper
class DefaultHandlerChain:
@CheckInputArgs(CallbackChainInterface, HandlerChainInterface)
def __init__(self, cb, *handlers):
self.handlercb = cb
self.handlers = handlers
self.debug = len(log.theLogPublisher.observers) > 0
def processRequest(self, arg, **kw):
if self.debug:
log.msg('--->PROCESS REQUEST\n%s' %arg, debug=1)
for h in self.handlers:
arg = h.processRequest(arg, **kw)
return self.handlercb.processRequest(arg, **kw)
def processResponse(self, arg, **kw):
if self.debug:
log.msg('===>PROCESS RESPONSE: %s' %str(arg), debug=1)
if arg is None:
return
for h in self.handlers:
arg = h.processResponse(arg, **kw)
s = str(arg)
if self.debug:
log.msg(s, debug=1)
return s
class DefaultHandlerChainFactory:
protocol = DefaultHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(DefaultCallbackHandler, DataHandler)
class WSAddressHandlerChainFactory:
protocol = DefaultHandlerChain
@classmethod
def newInstance(cls):
return cls.protocol(WSAddressCallbackHandler, DataHandler,
WSAddressHandler())
class WSResource(twisted.web.resource.Resource, object):
"""
class variables:
encoding --
factory -- hander chain, which has a factory method "newInstance"
that returns a
"""
encoding = "UTF-8"
factory = DefaultHandlerChainFactory
def __init__(self):
"""
"""
twisted.web.resource.Resource.__init__(self)
def _writeResponse(self, request, response, status=200):
"""
request -- request message
response --- response message
status -- HTTP Status
"""
request.setResponseCode(status)
if self.encoding is not None:
mimeType = 'text/xml; charset="%s"' % self.encoding
else:
mimeType = "text/xml"
request.setHeader("Content-Type", mimeType)
request.setHeader("Content-Length", str(len(response)))
request.write(response)
request.finish()
return NOT_DONE_YET
def _writeFault(self, request, ex):
"""
request -- request message
ex -- Exception
"""
response = None
response = fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()
log.err('SOAP FAULT: %s' % response)
return self._writeResponse(request, response, status=500)
def render_POST(self, request):
"""Dispatch Method called by twisted render, creates a
request/response handler chain.
request -- twisted.web.server.Request
"""
chain = self.factory.newInstance()
data = request.content.read()
try:
pyobj = chain.processRequest(data, request=request, resource=self)
except Exception, ex:
return self._writeFault(request, ex)
try:
soap = chain.processResponse(pyobj, request=request, resource=self)
except Exception, ex:
return self._writeFault(request, ex)
if soap is not None:
return self._writeResponse(request, soap)
request.finish()
return NOT_DONE_YET
|