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'
42 import xml.parsers.expat
43 from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
45 class _IkiWikiExtPluginXMLRPCDispatcher(SimpleXMLRPCDispatcher):
47 def __init__(self, allow_none=False, encoding=None):
49 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
51 # see http://bugs.debian.org/470645
52 # python2.4 and before only took one argument
53 SimpleXMLRPCDispatcher.__init__(self)
55 def dispatch(self, method, params):
56 return self._dispatch(method, params)
58 class XMLStreamParser(object):
61 self._parser = xml.parsers.expat.ParserCreate()
62 self._parser.StartElementHandler = self._push_tag
63 self._parser.EndElementHandler = self._pop_tag
64 self._parser.XmlDeclHandler = self._check_pipelining
70 self._first_tag_received = False
72 def _push_tag(self, tag, attrs):
73 self._stack.append(tag)
74 self._first_tag_received = True
76 def _pop_tag(self, tag):
77 top = self._stack.pop()
79 raise ParseError, 'expected %s closing tag, got %s' % (top, tag)
81 def _request_complete(self):
82 return self._first_tag_received and len(self._stack) == 0
84 def _check_pipelining(self, *args):
85 if self._first_tag_received:
86 raise PipeliningDetected, 'need a new line between XML documents'
88 def parse(self, data):
89 self._parser.Parse(data, False)
91 if self._request_complete():
96 class ParseError(Exception):
99 class PipeliningDetected(Exception):
102 class _IkiWikiExtPluginXMLRPCHandler(object):
104 def __init__(self, debug_fn):
105 self._dispatcher = _IkiWikiExtPluginXMLRPCDispatcher()
106 self.register_function = self._dispatcher.register_function
107 self._debug_fn = debug_fn
109 def register_function(self, function, name=None):
110 # will be overwritten by __init__
114 def _write(out_fd, data):
115 out_fd.write(str(data))
121 parser = XMLStreamParser()
123 line = in_fd.readline()
125 # ikiwiki exited, EOF received
128 ret = parser.parse(line)
129 # unless this returns non-None, we need to loop again
133 def send_rpc(self, cmd, in_fd, out_fd, *args, **kwargs):
134 xml = xmlrpclib.dumps(sum(kwargs.iteritems(), args), cmd)
135 self._debug_fn("calling ikiwiki procedure `%s': [%s]" % (cmd, xml))
136 _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml)
138 self._debug_fn('reading response from ikiwiki...')
140 xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
141 self._debug_fn('read response to procedure %s from ikiwiki: [%s]' % (cmd, xml))
143 # ikiwiki is going down
144 self._debug_fn('ikiwiki is going down, and so are we...')
145 raise _IkiWikiExtPluginXMLRPCHandler._GoingDown
147 data = xmlrpclib.loads(xml)[0][0]
148 self._debug_fn('parsed data from response to procedure %s: [%s]' % (cmd, data))
151 def handle_rpc(self, in_fd, out_fd):
152 self._debug_fn('waiting for procedure calls from ikiwiki...')
153 xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
155 # ikiwiki is going down
156 self._debug_fn('ikiwiki is going down, and so are we...')
157 raise _IkiWikiExtPluginXMLRPCHandler._GoingDown
159 self._debug_fn('received procedure call from ikiwiki: [%s]' % xml)
160 params, method = xmlrpclib.loads(xml)
161 ret = self._dispatcher.dispatch(method, params)
162 xml = xmlrpclib.dumps((ret,), methodresponse=True)
163 self._debug_fn('sending procedure response to ikiwiki: [%s]' % xml)
164 _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml)
170 class IkiWikiProcedureProxy(object):
172 # how to communicate None to ikiwiki
173 _IKIWIKI_NIL_SENTINEL = {'null':''}
175 # sleep during each iteration
178 def __init__(self, id, in_fd=sys.stdin, out_fd=sys.stdout, debug_fn=None):
181 self._out_fd = out_fd
183 self._functions = list()
184 self._imported = False
185 if debug_fn is not None:
186 self._debug_fn = debug_fn
188 self._debug_fn = lambda s: None
189 self._xmlrpc_handler = _IkiWikiExtPluginXMLRPCHandler(self._debug_fn)
190 self._xmlrpc_handler.register_function(self._importme, name='import')
192 def rpc(self, cmd, *args, **kwargs):
196 yield IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
200 args = list(subst_none(args))
201 kwargs = dict(zip(kwargs.keys(), list(subst_none(kwargs.itervalues()))))
202 ret = self._xmlrpc_handler.send_rpc(cmd, self._in_fd, self._out_fd,
204 if ret == IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL:
208 def hook(self, type, function, name=None, id=None, last=False):
210 raise IkiWikiProcedureProxy.AlreadyImported
213 name = function.__name__
218 def hook_proxy(*args):
220 # kwargs = dict([args[i:i+2] for i in xrange(1, len(args), 2)])
221 ret = function(self, *args)
222 self._debug_fn("%s hook `%s' returned: [%s]" % (type, name, ret))
223 if ret == IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL:
224 raise IkiWikiProcedureProxy.InvalidReturnValue, \
225 'hook functions are not allowed to return %s' \
226 % IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
228 ret = IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
231 self._hooks.append((id, type, name, last))
232 self._xmlrpc_handler.register_function(hook_proxy, name=name)
234 def inject(self, rname, function, name=None, memoize=True):
236 raise IkiWikiProcedureProxy.AlreadyImported
239 name = function.__name__
241 self._functions.append((rname, name, memoize))
242 self._xmlrpc_handler.register_function(function, name=name)
245 return self.rpc('getargv')
247 def setargv(self, argv):
248 return self.rpc('setargv', argv)
250 def getvar(self, hash, key):
251 return self.rpc('getvar', hash, key)
253 def setvar(self, hash, key, value):
254 return self.rpc('setvar', hash, key, value)
256 def getstate(self, page, id, key):
257 return self.rpc('getstate', page, id, key)
259 def setstate(self, page, id, key, value):
260 return self.rpc('setstate', page, id, key, value)
262 def pagespec_match(self, spec):
263 return self.rpc('pagespec_match', spec)
265 def error(self, msg):
267 self.rpc('error', msg)
272 sys.exit(posix.EX_SOFTWARE)
277 ret = self._xmlrpc_handler.handle_rpc(self._in_fd, self._out_fd)
278 time.sleep(IkiWikiProcedureProxy._LOOP_DELAY)
279 except _IkiWikiExtPluginXMLRPCHandler._GoingDown:
284 self.error('uncaught exception: %s\n%s' \
285 % (e, traceback.format_exc(sys.exc_info()[2])))
289 self._debug_fn('importing...')
290 for id, type, function, last in self._hooks:
291 self._debug_fn('hooking %s/%s into %s chain...' % (id, function, type))
292 self.rpc('hook', id=id, type=type, call=function, last=last)
293 for rname, function, memoize in self._functions:
294 self._debug_fn('injecting %s as %s...' % (function, rname))
295 self.rpc('inject', name=rname, call=function, memoize=memoize)
296 self._imported = True
297 return IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
299 class InvalidReturnValue(Exception):
302 class AlreadyImported(Exception):