forked from gisce/mongodb_backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongodb2.py
231 lines (196 loc) · 8.88 KB
/
mongodb2.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
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP - MongoDB backend
# Copyright (C) 2011 Joan M. Grande
# Thanks to Sharoon Thomas for the operator mapping code
#
# 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 tools
from pymongo import MongoClient
from pymongo.errors import AutoReconnect
from pymongo.read_preferences import ReadPreference
import re
import netsvc
from osv.orm import except_orm
from time import sleep
logger = netsvc.Logger()
class MDBConn(object):
OPERATOR_MAPPING = {
'=': lambda l1, l3: {l1: {'$eq': l3}},
'!=': lambda l1, l3: {l1: {'$ne': l3}},
'<=': lambda l1, l3: {l1: {'$lte': l3}},
'>=': lambda l1, l3: {l1: {'$gte': l3}},
'<': lambda l1, l3: {l1: {'$lt': l3}},
'>': lambda l1, l3: {l1: {'$gt': l3}},
'in': lambda l1, l3: {l1: {'$in': l3}},
'not in': lambda l1, l3: {l1: {'$nin': l3}},
'like': lambda l1, l3: {l1: {
'$regex': re.compile(l3.replace('%', '.*'))}},
'not like': lambda l1, l3: {l1: {
'$not': re.compile('%s' % l3.replace('%', '.*'))}},
'ilike': lambda l1, l3: {l1: re.compile(l3.replace('%', '.*'), re.I)},
'not ilike': lambda l1, l3: {l1: {
'$not': re.compile(l3.replace('%', '.*'), re.I)}},
}
def translate_domain(self, domain):
"""Translate an OpenERP domain object to a corresponding
MongoDB domain
"""
new_domain = {}
for field, operator, value in domain:
clause = self.OPERATOR_MAPPING[operator](field, value)
if field in new_domain.keys():
new_domain[field].update(clause[field])
else:
new_domain.update(clause)
return new_domain
@property
def uri(self):
""" Mongo uri calculation with backward compatibility prior to 0.4v
"""
def_db = tools.config.get('db_name', 'openerp')
tools.config['mongodb_force_uri'] = tools.config.get('mongodb_force_uri', '')
tools.config['mongodb_force_uri_readonly'] = tools.config.get('mongodb_force_uri_readonly', '')
tools.config['db_readonly'] = tools.config.get('db_readonly', False)
tools.config['mongodb_user_readonly'] = tools.config.get('mongodb_user_readonly', '')
tools.config['mongodb_user_readonly_pass'] = tools.config.get('mongodb_user_readonly_pass', '')
tools.config['mongodb_user'] = tools.config.get('mongodb_user', '')
tools.config['mongodb_pass'] = tools.config.get('mongodb_pass', '')
if tools.config['db_readonly']:
if not tools.config['mongodb_user_readonly'] and not tools.config['mongodb_force_uri_readonly']:
logger.notifyChannel(
'MongoDB', netsvc.LOG_WARNING,
(
"No se ha configurado ningun usuario de solo lectura "
"ni tampoco una URI especificada para readonly "
"las operacions de escritura no estan protegidas"
)
)
elif not tools.config['mongodb_force_uri_readonly']:
tools.config['mongodb_user'] = tools.config['mongodb_user_readonly']
tools.config['mongodb_pass'] = tools.config['mongodb_user_readonly_pass']
if tools.config['mongodb_force_uri']:
uri = tools.config['mongodb_force_uri']
else:
tools.config['mongodb_ssl'] = tools.config.get('mongodb_ssl', False)
tools.config['mongodb_name'] = tools.config.get('mongodb_name', def_db)
tools.config['mongodb_port'] = tools.config.get('mongodb_port', '27017')
tools.config['mongodb_host'] = tools.config.get('mongodb_host', '')
tools.config['mongodb_uri'] = tools.config.get( # Default
'mongodb_uri',
(
'mongodb://localhost:27017/'
if not tools.config['mongodb_ssl']
else 'mongodb://localhost:27017/?ssl=true'
)
)
"""
MONGODB-CR - mongo 2.4, 2.6 - defecto para mantener compatibilidad
SCRAM-SHA-1 - mongo 3.x
"""
tools.config['mongodb_auth'] = tools.config.get('mongodb_auth',
'MONGODB-CR')
uri = tools.config['mongodb_uri'] # with replicaset must use uri
if not tools.config.get('mongodb_replicaset', False):
if tools.config['mongodb_user']:
# Auth
if tools.config['mongodb_ssl']:
uri_tmpl = 'mongodb://%s:%s@%s:%s/%s?ssl=true&authMechanism=%s'
else:
uri_tmpl = 'mongodb://%s:%s@%s:%s/%s?authMechanism=%s'
uri = uri_tmpl % (tools.config['mongodb_user'],
tools.config['mongodb_pass'],
tools.config['mongodb_host'],
tools.config['mongodb_port'],
tools.config['mongodb_name'],
tools.config['mongodb_auth'])
elif tools.config['mongodb_host']:
# No auth
if tools.config['mongodb_ssl']:
uri_tmpl = 'mongodb://%s:%s/?ssl=true'
else:
uri_tmpl = 'mongodb://%s:%s/'
uri = uri_tmpl % (tools.config['mongodb_host'],
int(tools.config['mongodb_port']))
return uri
def mongo_connect(self):
'''Connects to mongo'''
try:
tools.config['mongodb_replicaset'] = tools.config.get(
'mongodb_replicaset', False
)
mongo_client = MongoClient
kwargs = {}
if tools.config['mongodb_replicaset']:
kwargs.update({'replicaSet': tools.config['mongodb_replicaset'],
'read_preference': ReadPreference.SECONDARY_PREFERRED})
connection = mongo_client(self.uri, **kwargs)
except Exception as e:
raise except_orm('MongoDB connection error', e)
return connection
def __init__(self):
self._connection = None
@property
def connection(self):
if self._connection is None:
self._connection = self.mongo_connect()
return self._connection
def get_collection(self, collection):
try:
db = self.connection[tools.config['mongodb_name']]
collection = db[collection]
except AutoReconnect as ar_e:
max_tries = 5
count = 0
while count < max_tries:
try:
logger.notifyChannel('MongoDB', netsvc.LOG_WARNING,
'trying to reconnect...')
con = self.mongo_connect()
db = con[tools.config['mongodb_name']]
collection = db[collection]
break
except AutoReconnect:
count += 1
sleep(0.5)
if count == 4:
raise except_orm('MongoDB connection error', ar_e)
except Exception as e:
raise except_orm('MongoDB connection error', e)
return collection
def get_db(self):
try:
db = self.connection[tools.config['mongodb_name']]
except AutoReconnect:
max_tries = 5
count = 0
while count < max_tries:
try:
logger.notifyChannel('MongoDB', netsvc.LOG_WARNING,
'WARNING: MongoDB trying to reconnect...')
con = self.mongo_connect()
db = con[tools.config['mongodb_name']]
break
except AutoReconnect:
count += 1
sleep(0.5)
except Exception as e:
raise except_orm('MongoDB connection error', e)
return db
def end_request(self):
return self.connection.end_request()
mdbpool = MDBConn()