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
46 from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
49 class ParseError (Exception):
53 class PipeliningDetected (Exception):
57 class GoingDown (Exception):
61 class InvalidReturnValue (Exception):
65 class AlreadyImported (Exception):
69 class _IkiWikiExtPluginXMLRPCDispatcher(SimpleXMLRPCDispatcher):
71 def __init__(self, allow_none=False, encoding=None):
73 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
75 # see http://bugs.debian.org/470645
76 # python2.4 and before only took one argument
77 SimpleXMLRPCDispatcher.__init__(self)
79 def dispatch(self, method, params):
80 return self._dispatch(method, params)
83 class XMLStreamParser(object):
86 self._parser = xml.parsers.expat.ParserCreate()
87 self._parser.StartElementHandler = self._push_tag
88 self._parser.EndElementHandler = self._pop_tag
89 self._parser.XmlDeclHandler = self._check_pipelining
95 self._first_tag_received = False
97 def _push_tag(self, tag, attrs):
98 self._stack.append(tag)
99 self._first_tag_received = True
101 def _pop_tag(self, tag):
102 top = self._stack.pop()
105 'expected {} closing tag, got {}'.format(top, tag))
107 def _request_complete(self):
108 return self._first_tag_received and len(self._stack) == 0
110 def _check_pipelining(self, *args):
111 if self._first_tag_received:
112 raise PipeliningDetected('need a new line between XML documents')
114 def parse(self, data):
115 self._parser.Parse(data, False)
117 if self._request_complete():
123 class _IkiWikiExtPluginXMLRPCHandler(object):
125 def __init__(self, debug_fn):
126 self._dispatcher = _IkiWikiExtPluginXMLRPCDispatcher()
127 self.register_function = self._dispatcher.register_function
128 self._debug_fn = debug_fn
130 def register_function(self, function, name=None):
131 # will be overwritten by __init__
135 def _write(out_fd, data):
136 out_fd.write(str(data))
142 parser = XMLStreamParser()
144 line = in_fd.readline()
146 # ikiwiki exited, EOF received
149 ret = parser.parse(line)
150 # unless this returns non-None, we need to loop again
154 def send_rpc(self, cmd, in_fd, out_fd, *args, **kwargs):
155 xml = _xmlrpc_client.dumps(sum(kwargs.iteritems(), args), cmd)
156 self._debug_fn("calling ikiwiki procedure `{}': [{}]".format(cmd, xml))
157 _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml)
159 self._debug_fn('reading response from ikiwiki...')
161 xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
163 'read response to procedure {} from ikiwiki: [{}]'.format(
166 # ikiwiki is going down
167 self._debug_fn('ikiwiki is going down, and so are we...')
170 data = _xmlrpc_client.loads(xml)[0][0]
172 'parsed data from response to procedure {}: [{}]'.format(
176 def handle_rpc(self, in_fd, out_fd):
177 self._debug_fn('waiting for procedure calls from ikiwiki...')
178 xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
180 # ikiwiki is going down
181 self._debug_fn('ikiwiki is going down, and so are we...')
185 'received procedure call from ikiwiki: [{}]'.format(xml))
186 params, method = _xmlrpc_client.loads(xml)
187 ret = self._dispatcher.dispatch(method, params)
188 xml = _xmlrpc_client.dumps((ret,), methodresponse=True)
190 'sending procedure response to ikiwiki: [{}]'.format(xml))
191 _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml)
195 class IkiWikiProcedureProxy(object):
197 # how to communicate None to ikiwiki
198 _IKIWIKI_NIL_SENTINEL = {'null':''}
200 # sleep during each iteration
203 def __init__(self, id, in_fd=sys.stdin, out_fd=sys.stdout, debug_fn=None):
206 self._out_fd = out_fd
208 self._functions = list()
209 self._imported = False
210 if debug_fn is not None:
211 self._debug_fn = debug_fn
213 self._debug_fn = lambda s: None
214 self._xmlrpc_handler = _IkiWikiExtPluginXMLRPCHandler(self._debug_fn)
215 self._xmlrpc_handler.register_function(self._importme, name='import')
217 def rpc(self, cmd, *args, **kwargs):
221 yield IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
225 args = list(subst_none(args))
226 kwargs = dict(zip(kwargs.keys(), list(subst_none(kwargs.itervalues()))))
227 ret = self._xmlrpc_handler.send_rpc(cmd, self._in_fd, self._out_fd,
229 if ret == IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL:
233 def hook(self, type, function, name=None, id=None, last=False):
235 raise AlreadyImported()
238 name = function.__name__
243 def hook_proxy(*args):
245 # kwargs = dict([args[i:i+2] for i in xrange(1, len(args), 2)])
246 ret = function(self, *args)
248 "{} hook `{}' returned: [{}]".format(type, name, ret))
249 if ret == IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL:
250 raise InvalidReturnValue(
251 'hook functions are not allowed to return {}'.format(
252 IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL))
254 ret = IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
257 self._hooks.append((id, type, name, last))
258 self._xmlrpc_handler.register_function(hook_proxy, name=name)
260 def inject(self, rname, function, name=None, memoize=True):
262 raise AlreadyImported()
265 name = function.__name__
267 self._functions.append((rname, name, memoize))
268 self._xmlrpc_handler.register_function(function, name=name)
271 return self.rpc('getargv')
273 def setargv(self, argv):
274 return self.rpc('setargv', argv)
276 def getvar(self, hash, key):
277 return self.rpc('getvar', hash, key)
279 def setvar(self, hash, key, value):
280 return self.rpc('setvar', hash, key, value)
282 def getstate(self, page, id, key):
283 return self.rpc('getstate', page, id, key)
285 def setstate(self, page, id, key, value):
286 return self.rpc('setstate', page, id, key, value)
288 def pagespec_match(self, spec):
289 return self.rpc('pagespec_match', spec)
291 def error(self, msg):
293 self.rpc('error', msg)
298 sys.exit(posix.EX_SOFTWARE)
303 ret = self._xmlrpc_handler.handle_rpc(
304 self._in_fd, self._out_fd)
305 time.sleep(IkiWikiProcedureProxy._LOOP_DELAY)
309 except Exception as e:
311 self.error('uncaught exception: {}\n{}'.format(
312 e, traceback.format_exc(sys.exc_info()[2])))
316 self._debug_fn('importing...')
317 for id, type, function, last in self._hooks:
318 self._debug_fn('hooking {}/{} into {} chain...'.format(
320 self.rpc('hook', id=id, type=type, call=function, last=last)
321 for rname, function, memoize in self._functions:
322 self._debug_fn('injecting {} as {}...'.format(function, rname))
323 self.rpc('inject', name=rname, call=function, memoize=memoize)
324 self._imported = True
325 return IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL