-
Notifications
You must be signed in to change notification settings - Fork 2
/
rpc.py
442 lines (384 loc) · 15.9 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# $Id$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import gtk
import xmlrpclib
import logging
import socket
import tiny_socket
import service
import common
import options
import os
import re
import pytz
import msgpack
import urllib2
import release
import sys
CONCURRENCY_CHECK_FIELD = '__last_update'
try:
# Due: https://www.python.org/dev/peps/pep-0476
import ssl
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
# Legacy Python that doesn't verify HTTPS certificates by default
pass
else:
# Handle target environment that doesn't support HTTPS verification
ssl._create_default_https_context = _create_unverified_https_context
except ImportError:
pass
class rpc_exception(Exception):
def __init__(self, code, backtrace):
self.code = code
self.args = backtrace
if hasattr(code, 'split'):
lines = code.split('\n')
self.type = lines[0].split(' -- ')[0]
self.message = ''
if len(lines[0].split(' -- ')) > 1:
self.message = lines[0].split(' -- ')[1]
self.data = '\n'.join(lines[2:])
else:
self.type = 'error'
self.message = backtrace
self.data = backtrace
self.backtrace = backtrace
log = logging.getLogger('rpc.exception')
log.warning('CODE %s: %s' % (str(code), self.message))
class gw_inter(object):
__slots__ = ('_url', '_db', '_uid', '_passwd', '_sock', '_obj')
def __init__(self, url, db, uid, passwd, obj='/object'):
self._url = url
self._db = db
self._uid = uid
self._obj = obj
self._passwd = passwd
def exec_auth(method, *args):
pass
def execute(method, *args):
pass
class xmlrpc_gw(gw_inter):
__slots__ = ('_url', '_db', '_uid', '_passwd', '_sock', '_obj')
def __init__(self, url, db, uid, passwd, obj='/object'):
gw_inter.__init__(self, url, db, uid, passwd, obj)
self._sock = xmlrpclib.ServerProxy(url+obj)
t = self._sock._ServerProxy__transport
t.user_agent = '%s %s/%s (Python %s)' % (
release.description, release.name, release.version, sys.version.split()[0]
)
def exec_auth(self, method, *args):
logging.getLogger('rpc.request').debug_rpc(str((method, self._db, self._uid, self._passwd, args)))
res = self.execute(method, self._uid, self._passwd, *args)
logging.getLogger('rpc.result').debug_rpc_answer(str(res))
return res
def __convert(self, result):
if type(result)==type(u''):
return result.encode('utf-8')
elif type(result)==type([]):
return map(self.__convert, result)
elif type(result)==type({}):
newres = {}
for i in result.keys():
newres[i] = self.__convert(result[i])
return newres
else:
return result
def execute(self, method, *args):
result = getattr(self._sock,method)(self._db, *args)
return self.__convert(result)
class tinySocket_gw(gw_inter):
__slots__ = ('_url', '_db', '_uid', '_passwd', '_sock', '_obj')
def __init__(self, url, db, uid, passwd, obj='/object'):
gw_inter.__init__(self, url, db, uid, passwd, obj)
self._sock = tiny_socket.mysocket()
self._obj = obj[1:]
def exec_auth(self, method, *args):
logging.getLogger('rpc.request').debug_rpc(str((method, self._db, self._uid, self._passwd, args)))
res = self.execute(method, self._uid, self._passwd, *args)
logging.getLogger('rpc.result').debug_rpc_answer(str(res))
return res
def execute(self, method, *args):
self._sock.connect(self._url)
self._sock.mysend((self._obj, method, self._db)+args)
res = self._sock.myreceive()
self._sock.disconnect()
return res
class msgpack_gw(gw_inter):
__slots__ = ('_url', '_db', '_uid', '_passwd', '_sock', '_obj')
def __init__(self, url, db, uid, passwd, obj='/object'):
super(msgpack_gw, self).__init__(url, db, uid, passwd, obj)
def exec_auth(self, method, *args):
res = self.execute(method, self._uid, self._passwd, *args)
return res
def execute(self, method, *args):
endpoint = '%s%s' % (self._url, self._obj)
m = msgpack.packb([method, self._db] + list(args))
u = urllib2.urlopen(endpoint, m)
s = u.read()
u.close()
res = msgpack.unpackb(s)
if u.code == 210:
raise xmlrpclib.Fault(
res['exception'],
res['traceback']
)
return self.__convert(res)
def __convert(self, result):
if isinstance(result, tuple):
result = list(result)
return map(self.__convert, result)
if type(result)==type(u''):
return result.encode('utf-8')
elif type(result)==type([]):
return map(self.__convert, result)
elif type(result)==type({}):
newres = {}
for i in result.keys():
newres[i] = self.__convert(result[i])
return newres
else:
return result
class rpc_session(object):
__slots__ = ('_open', '_url', 'uid', 'uname', '_passwd', '_gw', 'db', 'context', 'timezone')
def __init__(self):
self._open = False
self._url = None
self._passwd = None
self.uid = None
self.context = {}
self.uname = None
self._gw = xmlrpc_gw
self.db = None
self.timezone = 'utc'
def rpc_exec(self, obj, method, *args):
try:
sock = self._gw(self._url, self.db, self.uid, self._passwd, obj)
return sock.execute(method, *args)
except socket.error, e:
common.message(str(e), title=_('Connection refused !'), type=gtk.MESSAGE_ERROR)
raise rpc_exception(69, _('Connection refused!'))
except xmlrpclib.Fault, err:
raise rpc_exception(err.faultCode, err.faultString)
def rpc_exec_auth_try(self, obj, method, *args):
if self._open:
sock = self._gw(self._url, self.db, self.uid, self._passwd, obj)
return sock.exec_auth(method, *args)
else:
raise rpc_exception(1, 'not logged')
def rpc_exec_auth_wo(self, obj, method, *args):
try:
sock = self._gw(self._url, self.db, self.uid, self._passwd, obj)
return sock.exec_auth(method, *args)
except xmlrpclib.Fault, err:
a = rpc_exception(err.faultCode, err.faultString)
except tiny_socket.Myexception, err:
a = rpc_exception(err.faultCode, err.faultString)
if a.code in ('warning', 'UserError'):
common.warning(a.data, a.message)
return None
raise a
def rpc_exec_auth(self, obj, method, *args):
if self._open:
try:
sock = self._gw(self._url, self.db, self.uid, self._passwd, obj)
return sock.exec_auth(method, *args)
except socket.error, e:
common.message(_('Unable to reach to OpenERP server !\nYou should check your connection to the network and the OpenERP server.'), _('Connection Error'), type=gtk.MESSAGE_ERROR)
raise rpc_exception(69, 'Connection refused!')
except Exception, e:
if isinstance(e, (xmlrpclib.Fault, tiny_socket.Myexception)):
a = rpc_exception(e.faultCode, e.faultString)
if a.type in ('warning','UserError'):
if a.message in ('ConcurrencyException') and len(args) > 4:
if common.concurrency(args[0], args[2][0], args[4]):
if CONCURRENCY_CHECK_FIELD in args[4]:
del args[4][CONCURRENCY_CHECK_FIELD]
return self.rpc_exec_auth(obj, method, *args)
else:
common.warning(a.data, a.message)
else:
common.error(_('Application Error'), e.faultCode, e.faultString)
else:
common.error(_('Application Error'), _('View details'), str(e))
#TODO Must propagate the exception?
raise
else:
raise rpc_exception(1, 'not logged')
def login(self, uname, passwd, url, port, protocol, db):
_protocol = protocol
if _protocol == 'http://' or _protocol == 'https://':
_url = _protocol + url+':'+str(port)+'/xmlrpc'
_sock = xmlrpclib.ServerProxy(_url+'/common')
self._gw = xmlrpc_gw
try:
res = _sock.login(db or '', uname or '', passwd or '')
except socket.error,e:
return -1
if not res:
self._open=False
self.uid=False
return -2
elif _protocol.endswith('+msgpack://'):
_url = '%s://%s:%s' % (_protocol.split('+')[0], url, port)
self._gw = msgpack_gw
try:
m = msgpack.packb(['login', db or '', uname or '', passwd or ''])
u = urllib2.urlopen('%s/common' % _url, m)
s = u.read()
u.close()
res = msgpack.unpackb(s)
except socket.error,e:
return -1
if not res:
self._open=False
self.uid=False
return -2
else:
_url = _protocol+url+':'+str(port)
_sock = tiny_socket.mysocket()
self._gw = tinySocket_gw
try:
_sock.connect(url, int(port))
_sock.mysend(('common', 'login', db or '', uname or '', passwd or ''))
res = _sock.myreceive()
_sock.disconnect()
except socket.error,e:
return -1
if not res:
self._open=False
self.uid=False
return -2
self._url = _url
self._open = True
self.uid = res
self.uname = uname
self._passwd = passwd
self.db = db
#CHECKME: is this useful? maybe it's used to see if there is no
# exception raised?
sock = self._gw(self._url, self.db, self.uid, self._passwd)
self.context_reload()
return 1
def migrate_databases(self, url, password, databases):
return self.exec_no_except(url, 'db', 'migrate_databases', password, databases)
def get_available_updates(self, url, password, contract_id, contract_password):
return self.exec_no_except(url, 'common', 'get_available_updates', password, contract_id, contract_password)
def get_migration_scripts(self, url, password, contract_id, contract_password):
return self.exec_no_except(url, 'common', 'get_migration_scripts', password, contract_id, contract_password)
def about(self, url):
return self.exec_no_except(url, 'common', 'about')
def login_message(self, url):
try:
return self.exec_no_except(url, 'common', 'login_message')
except:
return False
def list_db(self, url):
try:
return self.db_exec_no_except(url, 'list')
except (xmlrpclib.Fault, tiny_socket.Myexception), e:
if e.faultCode == 'AccessDenied':
return None
raise
def db_exec_no_except(self, url, method, *args):
return self.exec_no_except(url, 'db', method, *args)
def exec_no_except(self, url, resource, method, *args):
m = re.match('^(http[s]?://|http[s]?\+msgpack://|socket://)([\w.-]+):(\d{1,5})$', url or '')
if m.group(1) == 'http://' or m.group(1) == 'https://':
sock = xmlrpclib.ServerProxy(url + '/xmlrpc/' + resource)
return getattr(sock, method)(*args)
elif m.group(1).endswith('+msgpack://'):
endpoint = '%s/%s' % (url.replace('+msgpack', ''), resource)
m = msgpack.packb([method] + list(args))
u = urllib2.urlopen(endpoint, m)
s = u.read()
u.close()
res = msgpack.unpackb(s)
return res
else:
sock = tiny_socket.mysocket()
sock.connect(m.group(2), int(m.group(3)))
sock.mysend((resource, method)+args)
res = sock.myreceive()
sock.disconnect()
return res
def db_exec(self, url, method, *args):
res = False
try:
res = self.db_exec_no_except(url, method, *args)
except socket.error, msg:
common.warning('Could not contact server!')
return res
def context_reload(self):
self.context = {}
self.timezone = 'utc'
self.context = self.rpc_exec_auth('/object', 'execute', 'res.users', 'context_get') or {}
if 'lang' in self.context:
import translate
translate.setlang(self.context['lang'])
options.options['client.lang']=self.context['lang']
ids = self.rpc_exec_auth('/object', 'execute', 'res.lang', 'search', [('code', '=', self.context['lang'])])
if ids:
l = self.rpc_exec_auth('/object', 'execute', 'res.lang', 'read', ids, ['direction'])
if l and 'direction' in l[0]:
common.DIRECTION = l[0]['direction']
import gtk
if common.DIRECTION == 'rtl':
gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
else:
gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)
if self.context.get('tz'):
# FIXME: Timezone handling
# rpc_session.timezone contains the server's idea of its timezone (from time.tzname[0]),
# which is quite quite unreliable in some cases. We'll fix this in trunk.
self.timezone = self.rpc_exec_auth('/common', 'timezone_get')
try:
pytz.timezone(self.timezone)
except pytz.UnknownTimeZoneError:
# Server timezone is not recognized!
# Time values will be displayed as if located in the server timezone. (nothing we can do)
pass
def logged(self):
return self._open
def logout(self):
if self._open :
self._open = False
self.uname = None
self.uid = None
self._passwd = None
session = rpc_session()
class RPCProxy(object):
def __init__(self, resource):
self.resource = resource
self.__attrs = {}
def __getattr__(self, name):
if not name in self.__attrs:
self.__attrs[name] = RPCFunction(self.resource, name)
return self.__attrs[name]
class RPCFunction(object):
def __init__(self, object, func_name):
self.object = object
self.func = func_name
def __call__(self, *args):
return session.rpc_exec_auth('/object', 'execute', self.object, self.func, *args)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: