-
Notifications
You must be signed in to change notification settings - Fork 217
/
rpc.py
287 lines (254 loc) · 10.4 KB
/
rpc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
# Copyright (c) 2015, Battelle Memorial Institute
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation
# are those of the authors and should not be interpreted as representing
# official policies, either expressed or implied, of the FreeBSD
# Project.
#
# This material was prepared as an account of work sponsored by an
# agency of the United States Government. Neither the United States
# Government nor the United States Department of Energy, nor Battelle,
# nor any of their employees, nor any jurisdiction or organization that
# has cooperated in the development of these materials, makes any
# warranty, express or implied, or assumes any legal liability or
# responsibility for the accuracy, completeness, or usefulness or any
# information, apparatus, product, software, or process disclosed, or
# represents that its use would not infringe privately owned rights.
#
# Reference herein to any specific commercial product, process, or
# service by trade name, trademark, manufacturer, or otherwise does not
# necessarily constitute or imply its endorsement, recommendation, or
# favoring by the United States Government or any agency thereof, or
# Battelle Memorial Institute. The views and opinions of authors
# expressed herein do not necessarily state or reflect those of the
# United States Government or any agency thereof.
#
# PACIFIC NORTHWEST NATIONAL LABORATORY
# operated by BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY
# under Contract DE-AC05-76RL01830
#}}}
from __future__ import absolute_import
import inspect
import logging
import os
import sys
import traceback
import weakref
import gevent.local
from gevent.event import AsyncResult
from zmq.utils import jsonapi
from .base import SubsystemBase
from ..errors import VIPError
from ..results import counter, ResultsDictionary
from ..decorators import annotate, annotations, dualmethod, spawn
from .... import jsonrpc
__all__ = ['RPC']
_ROOT_PACKAGE_PATH = os.path.dirname(
__import__(__name__.split('.', 1)[0]).__path__[-1]) + os.sep
_log = logging.getLogger(__name__)
class Dispatcher(jsonrpc.Dispatcher):
def __init__(self, methods, local):
super(Dispatcher, self).__init__()
self.methods = methods
self.local = local
self._results = ResultsDictionary()
def serialize(self, json_obj):
return jsonapi.dumps(json_obj)
def deserialize(self, json_string):
return jsonapi.loads(json_string)
def batch_call(self, requests):
methods = []
results = []
for notify, method, args, kwargs in requests:
if notify:
ident = None
else:
result = next(self._results)
ident = result.ident
results.append(result)
methods.append((ident, method, args, kwargs))
return super(Dispatcher, self).batch_call(methods), results
def call(self, method, args=None, kwargs=None):
# pylint: disable=arguments-differ
result = next(self._results)
return super(Dispatcher, self).call(
result.ident, method, args, kwargs), result
def result(self, response, ident, value, context=None):
try:
result = self._results.pop(ident)
except KeyError:
return
result.set(value)
def error(self, response, ident, code, message, data=None, context=None):
try:
result = self._results.pop(ident)
except KeyError:
return
result.set_exception(jsonrpc.exception_from_json(code, message, data))
def exception(self, response, ident, message, context=None):
# XXX: Should probably wrap exception in RPC specific error
# rather than re-raising.
exc_type, exc, exc_tb = sys.exc_info() # pylint: disable=unused-variable
try:
result = self._results.pop(ident)
except KeyError:
return
result.set_exception(exc)
def method(self, request, ident, name, args, kwargs,
batch=None, context=None):
if kwargs:
try:
args, kwargs = kwargs['*args'], kwargs['**kwargs']
except KeyError:
pass
try:
method = self.methods[name]
except KeyError:
if name == 'inspect':
return {'methods': self.methods.keys()}
elif name.endswith('.inspect'):
try:
method = self.methods[name[:-8]]
except KeyError:
pass
else:
return self._inspect(method)
raise NotImplementedError(name)
local = self.local
local.vip_message = context
local.request = request
local.batch = batch
try:
return method(*args, **kwargs)
except Exception as exc: # pylint: disable=broad-except
exc_tb = traceback.format_exc()
print("RPC ERROR",exc_tb)
_log.error('unhandled exception in JSON-RPC method %r: \n%s',
name, exc_tb)
if getattr(method, 'traceback', True):
exc.exc_info = {'exc_tb': exc_tb}
raise
finally:
del local.vip_message
del local.request
del local.batch
def _inspect(self, method):
params = inspect.getargspec(method)
if hasattr(method, 'im_self'):
params.args.pop(0)
response = {'params': params}
doc = inspect.getdoc(method)
if doc:
response['doc'] = doc
try:
source = inspect.getsourcefile(method)
cut = len(os.path.commonprefix([_ROOT_PACKAGE_PATH, source]))
source = source[cut:]
lineno = inspect.getsourcelines(method)[1]
except IOError:
pass
else:
response['source'] = source, lineno
try:
# pylint: disable=protected-access
response['return'] = method._returns
except AttributeError:
pass
return response
class RPC(SubsystemBase):
def __init__(self, core, owner):
self.core = weakref.ref(core)
self.context = None
self._exports = {}
self._dispatcher = None
self._counter = counter()
self._outstanding = weakref.WeakValueDictionary()
core.register('RPC', self._handle_subsystem, self._handle_error)
def export(member): # pylint: disable=redefined-outer-name
for name in annotations(member, set, 'rpc.exports'):
self._exports[name] = member
inspect.getmembers(owner, export)
def setup(sender, **kwargs):
# pylint: disable=unused-argument
self.context = gevent.local.local()
self._dispatcher = Dispatcher(self._exports, self.context)
core.onsetup.connect(setup, self)
@spawn
def _handle_subsystem(self, message):
dispatch = self._dispatcher.dispatch
responses = [response for response in (
dispatch(bytes(msg), message) for msg in message.args) if response]
if responses:
message.user = ''
message.args = responses
self.core().socket.send_vip_object(message, copy=False)
def _handle_error(self, sender, message, error, **kwargs):
result = self._outstanding.pop(bytes(message.id), None)
if isinstance(result, AsyncResult):
result.set_exception(error)
elif result:
for result in result:
result.set_exception(error)
@dualmethod
def export(self, method, name=None):
self._exports[name or method.__name__] = method
return method
@export.classmethod
def export(cls, name=None): # pylint: disable=no-self-argument
if not isinstance(name, basestring):
method, name = name, name.__name__
annotate(method, set, 'rpc.exports', name)
return method
def decorate(method):
annotate(method, set, 'rpc.exports', name)
return method
return decorate
def batch(self, peer, requests):
request, results = self._dispatcher.batch_call(requests)
if results:
items = weakref.WeakSet(results)
ident = '%s.%s' % (next(self._counter), id(items))
for result in results:
result._weak_set = items # pylint: disable=protected-access
self._outstanding[ident] = items
else:
ident = b''
if request:
self.core().socket.send_vip(peer, 'RPC', [request], msg_id=ident)
return results or None
def call(self, peer, method, *args, **kwargs):
request, result = self._dispatcher.call(method, args, kwargs)
ident = '%s.%s' % (next(self._counter), hash(result))
self._outstanding[ident] = result
self.core().socket.send_vip(peer, 'RPC', [request], msg_id=ident)
return result
__call__ = call
def notify(self, peer, method, *args, **kwargs):
request = self._dispatcher.notify(method, args, kwargs)
self.core().socket.send_vip(peer, 'RPC', [request])