]> sipb.mit.edu Git - ikiwiki.git/blob - plugins/proxy.py
5e783ba2e6a4e44e01c23fba860d74bc98634562
[ikiwiki.git] / plugins / proxy.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # proxy.py — helper for Python-based external (xml-rpc) ikiwiki plugins
5 #
6 # Copyright © 2008      martin f. krafft <madduck@madduck.net>
7 #             2008-2011 Joey Hess <joey@kitenet.net>
8 #             2012      W. Trevor King <wking@tremily.us>
9 #
10 #  Redistribution and use in source and binary forms, with or without
11 # modification, are permitted provided that the following conditions
12 # are met:
13 # 1. Redistributions of source code must retain the above copyright
14 #    notice, this list of conditions and the following disclaimer.
15 # 2. Redistributions in binary form must reproduce the above copyright
16 #    notice, this list of conditions and the following disclaimer in the
17 #    documentation and/or other materials provided with the distribution.
18 # .
19 # THIS SOFTWARE IS PROVIDED BY IKIWIKI AND CONTRIBUTORS ``AS IS''
20 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
22 # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION
23 # OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
26 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28 # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
29 # OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 # SUCH DAMAGE.
31 #
32 __name__ = 'proxy.py'
33 __description__ = 'helper for Python-based external (xml-rpc) ikiwiki plugins'
34 __version__ = '0.2'
35 __author__ = 'martin f. krafft <madduck@madduck.net>'
36 __copyright__ = 'Copyright © ' + __author__
37 __licence__ = 'BSD-2-clause'
38
39 import sys
40 import time
41 import xmlrpclib
42 import xml.parsers.expat
43 from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
44
45
46 class ParseError (Exception):
47     pass
48
49
50 class PipeliningDetected (Exception):
51     pass
52
53
54 class GoingDown (Exception):
55     pass
56
57
58 class InvalidReturnValue (Exception):
59     pass
60
61
62 class AlreadyImported (Exception):
63     pass
64
65
66 class _IkiWikiExtPluginXMLRPCDispatcher(SimpleXMLRPCDispatcher):
67
68     def __init__(self, allow_none=False, encoding=None):
69         try:
70             SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
71         except TypeError:
72             # see http://bugs.debian.org/470645
73             # python2.4 and before only took one argument
74             SimpleXMLRPCDispatcher.__init__(self)
75
76     def dispatch(self, method, params):
77         return self._dispatch(method, params)
78
79
80 class XMLStreamParser(object):
81
82     def __init__(self):
83         self._parser = xml.parsers.expat.ParserCreate()
84         self._parser.StartElementHandler = self._push_tag
85         self._parser.EndElementHandler = self._pop_tag
86         self._parser.XmlDeclHandler = self._check_pipelining
87         self._reset()
88
89     def _reset(self):
90         self._stack = list()
91         self._acc = r''
92         self._first_tag_received = False
93
94     def _push_tag(self, tag, attrs):
95         self._stack.append(tag)
96         self._first_tag_received = True
97
98     def _pop_tag(self, tag):
99         top = self._stack.pop()
100         if top != tag:
101             raise ParseError(
102                 'expected {} closing tag, got {}'.format(top, tag))
103
104     def _request_complete(self):
105         return self._first_tag_received and len(self._stack) == 0
106
107     def _check_pipelining(self, *args):
108         if self._first_tag_received:
109             raise PipeliningDetected('need a new line between XML documents')
110
111     def parse(self, data):
112         self._parser.Parse(data, False)
113         self._acc += data
114         if self._request_complete():
115             ret = self._acc
116             self._reset()
117             return ret
118
119
120 class _IkiWikiExtPluginXMLRPCHandler(object):
121
122     def __init__(self, debug_fn):
123         self._dispatcher = _IkiWikiExtPluginXMLRPCDispatcher()
124         self.register_function = self._dispatcher.register_function
125         self._debug_fn = debug_fn
126
127     def register_function(self, function, name=None):
128         # will be overwritten by __init__
129         pass
130
131     @staticmethod
132     def _write(out_fd, data):
133         out_fd.write(str(data))
134         out_fd.flush()
135
136     @staticmethod
137     def _read(in_fd):
138         ret = None
139         parser = XMLStreamParser()
140         while True:
141             line = in_fd.readline()
142             if len(line) == 0:
143                 # ikiwiki exited, EOF received
144                 return None
145
146             ret = parser.parse(line)
147             # unless this returns non-None, we need to loop again
148             if ret is not None:
149                 return ret
150
151     def send_rpc(self, cmd, in_fd, out_fd, *args, **kwargs):
152         xml = xmlrpclib.dumps(sum(kwargs.iteritems(), args), cmd)
153         self._debug_fn("calling ikiwiki procedure `{}': [{}]".format(cmd, xml))
154         _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml)
155
156         self._debug_fn('reading response from ikiwiki...')
157
158         xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
159         self._debug_fn(
160             'read response to procedure {} from ikiwiki: [{}]'.format(
161                 cmd, xml))
162         if xml is None:
163             # ikiwiki is going down
164             self._debug_fn('ikiwiki is going down, and so are we...')
165             raise GoingDown()
166
167         data = xmlrpclib.loads(xml)[0][0]
168         self._debug_fn(
169             'parsed data from response to procedure {}: [{}]'.format(
170                 cmd, data))
171         return data
172
173     def handle_rpc(self, in_fd, out_fd):
174         self._debug_fn('waiting for procedure calls from ikiwiki...')
175         xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
176         if xml is None:
177             # ikiwiki is going down
178             self._debug_fn('ikiwiki is going down, and so are we...')
179             raise GoingDown()
180
181         self._debug_fn(
182             'received procedure call from ikiwiki: [{}]'.format(xml))
183         params, method = xmlrpclib.loads(xml)
184         ret = self._dispatcher.dispatch(method, params)
185         xml = xmlrpclib.dumps((ret,), methodresponse=True)
186         self._debug_fn(
187                 'sending procedure response to ikiwiki: [{}]'.format(xml))
188         _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml)
189         return ret
190
191
192 class IkiWikiProcedureProxy(object):
193
194     # how to communicate None to ikiwiki
195     _IKIWIKI_NIL_SENTINEL = {'null':''}
196
197     # sleep during each iteration
198     _LOOP_DELAY = 0.1
199
200     def __init__(self, id, in_fd=sys.stdin, out_fd=sys.stdout, debug_fn=None):
201         self._id = id
202         self._in_fd = in_fd
203         self._out_fd = out_fd
204         self._hooks = list()
205         self._functions = list()
206         self._imported = False
207         if debug_fn is not None:
208             self._debug_fn = debug_fn
209         else:
210             self._debug_fn = lambda s: None
211         self._xmlrpc_handler = _IkiWikiExtPluginXMLRPCHandler(self._debug_fn)
212         self._xmlrpc_handler.register_function(self._importme, name='import')
213
214     def rpc(self, cmd, *args, **kwargs):
215         def subst_none(seq):
216             for i in seq:
217                 if i is None:
218                     yield IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
219                 else:
220                     yield i
221
222         args = list(subst_none(args))
223         kwargs = dict(zip(kwargs.keys(), list(subst_none(kwargs.itervalues()))))
224         ret = self._xmlrpc_handler.send_rpc(cmd, self._in_fd, self._out_fd,
225                                             *args, **kwargs)
226         if ret == IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL:
227             ret = None
228         return ret
229
230     def hook(self, type, function, name=None, id=None, last=False):
231         if self._imported:
232             raise AlreadyImported()
233
234         if name is None:
235             name = function.__name__
236
237         if id is None:
238             id = self._id
239
240         def hook_proxy(*args):
241 #            curpage = args[0]
242 #            kwargs = dict([args[i:i+2] for i in xrange(1, len(args), 2)])
243             ret = function(self, *args)
244             self._debug_fn(
245                     "{} hook `{}' returned: [{}]".format(type, name, ret))
246             if ret == IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL:
247                 raise InvalidReturnValue(
248                     'hook functions are not allowed to return {}'.format(
249                         IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL))
250             if ret is None:
251                 ret = IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
252             return ret
253
254         self._hooks.append((id, type, name, last))
255         self._xmlrpc_handler.register_function(hook_proxy, name=name)
256
257     def inject(self, rname, function, name=None, memoize=True):
258         if self._imported:
259             raise AlreadyImported()
260
261         if name is None:
262             name = function.__name__
263
264         self._functions.append((rname, name, memoize))
265         self._xmlrpc_handler.register_function(function, name=name)
266
267     def getargv(self):
268         return self.rpc('getargv')
269
270     def setargv(self, argv):
271         return self.rpc('setargv', argv)
272
273     def getvar(self, hash, key):
274         return self.rpc('getvar', hash, key)
275
276     def setvar(self, hash, key, value):
277         return self.rpc('setvar', hash, key, value)
278
279     def getstate(self, page, id, key):
280         return self.rpc('getstate', page, id, key)
281
282     def setstate(self, page, id, key, value):
283         return self.rpc('setstate', page, id, key, value)
284
285     def pagespec_match(self, spec):
286         return self.rpc('pagespec_match', spec)
287
288     def error(self, msg):
289         try:
290             self.rpc('error', msg)
291         except IOError as e:
292             if e.errno != 32:
293                 raise
294         import posix
295         sys.exit(posix.EX_SOFTWARE)
296
297     def run(self):
298         try:
299             while True:
300                 ret = self._xmlrpc_handler.handle_rpc(
301                     self._in_fd, self._out_fd)
302                 time.sleep(IkiWikiProcedureProxy._LOOP_DELAY)
303         except GoingDown:
304             return
305
306         except Exception as e:
307             import traceback
308             self.error('uncaught exception: {}\n{}'.format(
309                         e, traceback.format_exc(sys.exc_info()[2])))
310             return
311
312     def _importme(self):
313         self._debug_fn('importing...')
314         for id, type, function, last in self._hooks:
315             self._debug_fn('hooking {}/{} into {} chain...'.format(
316                     id, function, type))
317             self.rpc('hook', id=id, type=type, call=function, last=last)
318         for rname, function, memoize in self._functions:
319             self._debug_fn('injecting {} as {}...'.format(function, rname))
320             self.rpc('inject', name=rname, call=function, memoize=memoize)
321         self._imported = True
322         return IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL