2 # -*- coding: utf-8 -*-
4 # proxy.py — helper for Python-based external (xml-rpc) ikiwiki plugins
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>
10 # Redistribution and use in source and binary forms, with or without
11 # modification, are permitted provided that the following conditions
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.
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
33 __description__ = 'helper for Python-based external (xml-rpc) ikiwiki plugins'
35 __author__ = 'martin f. krafft <madduck@madduck.net>'
36 __copyright__ = 'Copyright © ' + __author__
37 __licence__ = 'BSD-2-clause'
41 import xml.parsers.expat
43 import xmlrpc.client as _xmlrpc_client
44 except ImportError: # Python 2
45 import xmlrpclib as _xmlrpc_client
47 import xmlrpc.server as _xmlrpc_server
48 except ImportError: # Python 2
49 import SimpleXMLRPCServer as _xmlrpc_server
52 class ParseError (Exception):
56 class PipeliningDetected (Exception):
60 class GoingDown (Exception):
64 class InvalidReturnValue (Exception):
68 class AlreadyImported (Exception):
72 class _IkiWikiExtPluginXMLRPCDispatcher(_xmlrpc_server.SimpleXMLRPCDispatcher):
74 def __init__(self, allow_none=False, encoding=None):
76 _xmlrpc_server.SimpleXMLRPCDispatcher.__init__(
77 self, allow_none, encoding)
79 # see http://bugs.debian.org/470645
80 # python2.4 and before only took one argument
81 _xmlrpc_server.SimpleXMLRPCDispatcher.__init__(self)
83 def dispatch(self, method, params):
84 return self._dispatch(method, params)
87 class XMLStreamParser(object):
90 self._parser = xml.parsers.expat.ParserCreate()
91 self._parser.StartElementHandler = self._push_tag
92 self._parser.EndElementHandler = self._pop_tag
93 self._parser.XmlDeclHandler = self._check_pipelining
99 self._first_tag_received = False
101 def _push_tag(self, tag, attrs):
102 self._stack.append(tag)
103 self._first_tag_received = True
105 def _pop_tag(self, tag):
106 top = self._stack.pop()
109 'expected {} closing tag, got {}'.format(top, tag))
111 def _request_complete(self):
112 return self._first_tag_received and len(self._stack) == 0
114 def _check_pipelining(self, *args):
115 if self._first_tag_received:
116 raise PipeliningDetected('need a new line between XML documents')
118 def parse(self, data):
119 self._parser.Parse(data, False)
121 if self._request_complete():
127 class _IkiWikiExtPluginXMLRPCHandler(object):
129 def __init__(self, debug_fn):
130 self._dispatcher = _IkiWikiExtPluginXMLRPCDispatcher()
131 self.register_function = self._dispatcher.register_function
132 self._debug_fn = debug_fn
134 def register_function(self, function, name=None):
135 # will be overwritten by __init__
139 def _write(out_fd, data):
140 out_fd.write(str(data))
146 parser = XMLStreamParser()
148 line = in_fd.readline()
150 # ikiwiki exited, EOF received
153 ret = parser.parse(line)
154 # unless this returns non-None, we need to loop again
158 def send_rpc(self, cmd, in_fd, out_fd, *args, **kwargs):
159 xml = _xmlrpc_client.dumps(sum(kwargs.items(), args), cmd)
160 self._debug_fn("calling ikiwiki procedure `{}': [{}]".format(cmd, xml))
161 _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml)
163 self._debug_fn('reading response from ikiwiki...')
165 xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
167 'read response to procedure {} from ikiwiki: [{}]'.format(
170 # ikiwiki is going down
171 self._debug_fn('ikiwiki is going down, and so are we...')
174 data = _xmlrpc_client.loads(xml)[0][0]
176 'parsed data from response to procedure {}: [{}]'.format(
180 def handle_rpc(self, in_fd, out_fd):
181 self._debug_fn('waiting for procedure calls from ikiwiki...')
182 xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
184 # ikiwiki is going down
185 self._debug_fn('ikiwiki is going down, and so are we...')
189 'received procedure call from ikiwiki: [{}]'.format(xml))
190 params, method = _xmlrpc_client.loads(xml)
191 ret = self._dispatcher.dispatch(method, params)
192 xml = _xmlrpc_client.dumps((ret,), methodresponse=True)
194 'sending procedure response to ikiwiki: [{}]'.format(xml))
195 _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml)
199 class IkiWikiProcedureProxy(object):
201 # how to communicate None to ikiwiki
202 _IKIWIKI_NIL_SENTINEL = {'null':''}
204 # sleep during each iteration
207 def __init__(self, id, in_fd=sys.stdin, out_fd=sys.stdout, debug_fn=None):
210 self._out_fd = out_fd
212 self._functions = list()
213 self._imported = False
214 if debug_fn is not None:
215 self._debug_fn = debug_fn
217 self._debug_fn = lambda s: None
218 self._xmlrpc_handler = _IkiWikiExtPluginXMLRPCHandler(self._debug_fn)
219 self._xmlrpc_handler.register_function(self._importme, name='import')
221 def rpc(self, cmd, *args, **kwargs):
225 yield IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
229 args = list(subst_none(args))
230 kwargs = dict(zip(kwargs.keys(), list(subst_none(kwargs.values()))))
231 ret = self._xmlrpc_handler.send_rpc(cmd, self._in_fd, self._out_fd,
233 if ret == IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL:
237 def hook(self, type, function, name=None, id=None, last=False):
239 raise AlreadyImported()
242 name = function.__name__
247 def hook_proxy(*args):
249 # kwargs = dict([args[i:i+2] for i in xrange(1, len(args), 2)])
250 ret = function(self, *args)
252 "{} hook `{}' returned: [{}]".format(type, name, ret))
253 if ret == IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL:
254 raise InvalidReturnValue(
255 'hook functions are not allowed to return {}'.format(
256 IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL))
258 ret = IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
261 self._hooks.append((id, type, name, last))
262 self._xmlrpc_handler.register_function(hook_proxy, name=name)
264 def inject(self, rname, function, name=None, memoize=True):
266 raise AlreadyImported()
269 name = function.__name__
271 self._functions.append((rname, name, memoize))
272 self._xmlrpc_handler.register_function(function, name=name)
275 return self.rpc('getargv')
277 def setargv(self, argv):
278 return self.rpc('setargv', argv)
280 def getvar(self, hash, key):
281 return self.rpc('getvar', hash, key)
283 def setvar(self, hash, key, value):
284 return self.rpc('setvar', hash, key, value)
286 def getstate(self, page, id, key):
287 return self.rpc('getstate', page, id, key)
289 def setstate(self, page, id, key, value):
290 return self.rpc('setstate', page, id, key, value)
292 def pagespec_match(self, spec):
293 return self.rpc('pagespec_match', spec)
295 def error(self, msg):
297 self.rpc('error', msg)
302 sys.exit(posix.EX_SOFTWARE)
307 ret = self._xmlrpc_handler.handle_rpc(
308 self._in_fd, self._out_fd)
309 time.sleep(IkiWikiProcedureProxy._LOOP_DELAY)
313 except Exception as e:
315 tb = traceback.format_exc()
316 self.error('uncaught exception: {}\n{}'.format(e, tb))
320 self._debug_fn('importing...')
321 for id, type, function, last in self._hooks:
322 self._debug_fn('hooking {}/{} into {} chain...'.format(
324 self.rpc('hook', id=id, type=type, call=function, last=last)
325 for rname, function, memoize in self._functions:
326 self._debug_fn('injecting {} as {}...'.format(function, rname))
327 self.rpc('inject', name=rname, call=function, memoize=memoize)
328 self._imported = True
329 return IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL