2 # -*- coding: utf-8 -*-
4 # proxy.py — helper for Python-based external (xml-rpc) ikiwiki plugins
6 # Copyright © martin f. krafft <madduck@madduck.net>
7 # Released under the terms of the GNU GPL version 2
10 __description__ = 'helper for Python-based external (xml-rpc) ikiwiki plugins'
12 __author__ = 'martin f. krafft <madduck@madduck.net>'
13 __copyright__ = 'Copyright © ' + __author__
19 import xml.parsers.expat
20 from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
22 class _IkiWikiExtPluginXMLRPCDispatcher(SimpleXMLRPCDispatcher):
24 def __init__(self, allow_none=False, encoding=None):
26 SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
28 # see http://bugs.debian.org/470645
29 # python2.4 and before only took one argument
30 SimpleXMLRPCDispatcher.__init__(self)
32 def dispatch(self, method, params):
33 return self._dispatch(method, params)
35 class _XMLStreamParser(object):
38 self._parser = xml.parsers.expat.ParserCreate()
39 self._parser.StartElementHandler = self._push_tag
40 self._parser.EndElementHandler = self._pop_tag
41 self._parser.XmlDeclHandler = self._check_pipelining
47 self._first_tag_received = False
49 def _push_tag(self, tag, attrs):
50 self._stack.append(tag)
51 self._first_tag_received = True
53 def _pop_tag(self, tag):
54 top = self._stack.pop()
56 raise ParseError, 'expected %s closing tag, got %s' % (top, tag)
58 def _request_complete(self):
59 return self._first_tag_received and len(self._stack) == 0
61 def _check_pipelining(self, *args):
62 if self._first_tag_received:
63 raise PipeliningDetected, 'need a new line between XML documents'
65 def parse(self, data):
66 self._parser.Parse(data, False)
68 if self._request_complete():
73 class ParseError(Exception):
76 class PipeliningDetected(Exception):
79 class _IkiWikiExtPluginXMLRPCHandler(object):
81 def __init__(self, debug_fn):
82 self._dispatcher = _IkiWikiExtPluginXMLRPCDispatcher()
83 self.register_function = self._dispatcher.register_function
84 self._debug_fn = debug_fn
86 def register_function(self, function, name=None):
87 # will be overwritten by __init__
91 def _write(out_fd, data):
92 out_fd.write(str(data))
98 parser = _XMLStreamParser()
100 line = in_fd.readline()
102 # ikiwiki exited, EOF received
105 ret = parser.parse(line)
106 # unless this returns non-None, we need to loop again
110 def send_rpc(self, cmd, in_fd, out_fd, **kwargs):
111 xml = xmlrpclib.dumps(sum(kwargs.iteritems(), ()), cmd)
112 self._debug_fn("calling ikiwiki procedure `%s': [%s]" % (cmd, xml))
113 _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml)
115 self._debug_fn('reading response from ikiwiki...')
117 xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
118 self._debug_fn('read response to procedure %s from ikiwiki: [%s]' % (cmd, xml))
120 # ikiwiki is going down
123 data = xmlrpclib.loads(xml)[0]
124 self._debug_fn('parsed data from response to procedure %s: [%s]' % (cmd, data))
127 def handle_rpc(self, in_fd, out_fd):
128 self._debug_fn('waiting for procedure calls from ikiwiki...')
129 xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
131 # ikiwiki is going down
132 self._debug_fn('ikiwiki is going down, and so are we...')
135 self._debug_fn('received procedure call from ikiwiki: [%s]' % xml)
136 params, method = xmlrpclib.loads(xml)
137 ret = self._dispatcher.dispatch(method, params)
138 xml = xmlrpclib.dumps((ret,), methodresponse=True)
139 self._debug_fn('sending procedure response to ikiwiki: [%s]' % xml)
140 _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml)
143 class IkiWikiProcedureProxy(object):
145 # how to communicate None to ikiwiki
146 _IKIWIKI_NIL_SENTINEL = {'null':''}
148 # sleep during each iteration
151 def __init__(self, id, in_fd=sys.stdin, out_fd=sys.stdout, debug_fn=None):
154 self._out_fd = out_fd
156 if debug_fn is not None:
157 self._debug_fn = debug_fn
159 self._debug_fn = lambda s: None
160 self._xmlrpc_handler = _IkiWikiExtPluginXMLRPCHandler(self._debug_fn)
161 self._xmlrpc_handler.register_function(self._importme, name='import')
163 def hook(self, type, function, name=None):
165 name = function.__name__
166 self._hooks.append((type, name))
168 def hook_proxy(*args):
170 # kwargs = dict([args[i:i+2] for i in xrange(1, len(args), 2)])
171 ret = function(*args)
172 self._debug_fn("%s hook `%s' returned: [%s]" % (type, name, ret))
173 if ret == IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL:
174 raise IkiWikiProcedureProxy.InvalidReturnValue, \
175 'hook functions are not allowed to return %s' \
176 % IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
178 ret = IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
181 self._xmlrpc_handler.register_function(hook_proxy, name=name)
184 self._debug_fn('importing...')
185 for type, function in self._hooks:
186 self._debug_fn('hooking %s into %s chain...' % (function, type))
187 self._xmlrpc_handler.send_rpc('hook', self._in_fd, self._out_fd,
188 id=self._id, type=type, call=function)
189 return IkiWikiProcedureProxy._IKIWIKI_NIL_SENTINEL
194 ret = self._xmlrpc_handler.handle_rpc(self._in_fd, self._out_fd)
197 time.sleep(IkiWikiProcedureProxy._LOOP_DELAY)
199 print >>sys.stderr, 'uncaught exception: %s' % e
201 print >>sys.stderr, traceback.format_exc(sys.exc_info()[2])
203 sys.exit(posix.EX_SOFTWARE)
205 class InvalidReturnValue(Exception):