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