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
|
"""
Basic utilities to start and stop mongo processes on the local machine.
Encapsulates all the nitty-gritty parameter conversion, database path setup, and custom arguments.
"""
import json
import os
import shutil
import time
from external_programs import *
from mongodb_network import *
#
# Callback functions defined for special kwargs to MongoD/MongoShell/DBTests
#
def apply_buildlogger_args(process, field, value):
def hookup_bl(python_executable="python",
buildlogger_script="buildlogger.py",
buildlogger_global=False,
**kwargs):
buildlogger_arguments = [buildlogger_script]
if buildlogger_global:
buildlogger_arguments.append("-g")
buildlogger_arguments.append(process.executable)
process.executable = python_executable
process.arguments = buildlogger_arguments + process.arguments
for field in kwargs:
process.env_vars[field.upper()] = kwargs[field]
hookup_bl(**value)
# The "buildlogger" argument is a special command-line parameter, does crazy stuff
BUILDLOGGER_CUSTOM_KWARGS = \
{"buildlogger": (None, KWARG_TYPE_CALLBACK, apply_buildlogger_args)}
def apply_verbose_arg(process, field, value):
verbose_arg = "v" * value
if verbose_arg:
process.arguments.append("-" + verbose_arg)
# The "verbose" argument is a special command-line parameter, converts to "v"s
VERBOSE_CUSTOM_KWARGS = \
{"verbose": (None, KWARG_TYPE_CALLBACK, apply_verbose_arg)}
def apply_setparam_args(process, field, value):
for param_name, param_value in value.iteritems():
process.arguments.append("--setParameter")
process.arguments.append("%s=%s" % (param_name, json.dumps(param_value)))
# The "set_parameters" arg is a special command line parameter, converts to "field=value"
SETPARAM_CUSTOM_KWARGS = \
{"set_parameters": (None, KWARG_TYPE_CALLBACK, apply_setparam_args)}
#
# Default MongoD options
#
MONGOD_DEFAULT_EXEC = "./mongod"
MONGOD_DEFAULT_DATA_PATH = "/data/db"
MONGOD_KWARGS = dict(
BUILDLOGGER_CUSTOM_KWARGS.items() +
VERBOSE_CUSTOM_KWARGS.items() +
SETPARAM_CUSTOM_KWARGS.items())
class MongoD(ExternalProgram):
"""A locally-running MongoD process."""
def __init__(self,
executable=MONGOD_DEFAULT_EXEC,
default_data_path=MONGOD_DEFAULT_DATA_PATH,
preserve_dbpath=False,
custom_kwargs=MONGOD_KWARGS,
**kwargs):
mongod_kwargs = dict(kwargs.items())
self.host = "localhost"
if "port" in mongod_kwargs:
self.unused_port = UnusedPort(mongod_kwargs["port"])
else:
self.unused_port = UnusedPort()
mongod_kwargs["port"] = self.unused_port.port
self.port = mongod_kwargs["port"]
if "dbpath" not in mongod_kwargs:
mongod_kwargs["dbpath"] = \
os.path.join(default_data_path, "%s-%s" % (self.host, self.port))
self.dbpath = mongod_kwargs["dbpath"]
self.preserve_dbpath = preserve_dbpath
ExternalProgram.__init__(self, executable, custom_kwargs=custom_kwargs, **mongod_kwargs)
def _cleanup(self):
if not self.preserve_dbpath and os.path.exists(self.dbpath):
self.logger().info("Removing data in dbpath %s" % self.dbpath)
shutil.rmtree(self.dbpath)
def start(self):
try:
self._cleanup()
if not os.path.exists(self.dbpath):
self.logger().info("Creating dbpath at \"%s\"" % self.dbpath)
os.makedirs(self.dbpath)
except:
self.logger().error("Failed to setup dbpath at \"%s\"" % self.dbpath, exc_info=True)
raise
# Slightly racy - fixing is tricky
self.unused_port.release()
self.unused_port = None
ExternalProgram.start(self)
def wait_for_client(self, timeout_secs=30.0):
timer = Timer()
while True:
if self.poll() is not None:
# MongoD exited for some reason
raise Exception(
"Could not connect to MongoD server at %s:%s, process ended unexpectedly." %
(self.host, self.port))
try:
# Try to connect to the mongod with a pymongo client - 30s default socket timeout
self.client().admin.command("ismaster")
break
except Exception as ex:
if timer.elapsed_secs() > timeout_secs:
raise Exception(
"Failed to connect to MongoD server at %s:%s." %
(self.host, self.port), ex)
else:
self.logger().info("Waiting to connect to MongoD server at %s:%s..." %
(self.host, self.port))
time.sleep(0.5)
self.logger().info("Connected to MongoD server at %s:%s." % (self.host, self.port))
def client(self, **client_args):
# Import pymongo here, only when needed
import pymongo
return pymongo.MongoClient(self.host, self.port, **client_args)
def _wait_for_port(self, timeout_secs=10):
timer = Timer()
while True:
try:
self.unused_port = UnusedPort(self.port)
break
except Exception as ex:
if timer.elapsed_secs() > timeout_secs:
raise Exception("Failed to cleanup port from MongoD server at %s:%s" %
(self.host, self.port), ex)
self.logger().info("Waiting for MongoD server at %s:%s to relinquish port..." %
(self.host, self.port))
time.sleep(0.5)
def wait(self):
ExternalProgram.wait(self)
# Slightly racy - fixing is tricky
self._wait_for_port()
self._cleanup()
def stop(self):
ExternalProgram.stop(self)
# Slightly racy - fixing is tricky
self._wait_for_port()
self._cleanup()
#
# Default MongoShell options
#
MONGOSHELL_DEFAULT_EXEC = "./mongo"
MONGOSHELL_KWARGS = dict(BUILDLOGGER_CUSTOM_KWARGS.items())
class MongoShellContext(object):
"""The context for a mongo shell execution.
Tests using the shell can only have APIs provided by injecting them into the shell when it
starts - generally as global variables.
Shell options and global variables are specified using this structure.
"""
def __init__(self):
self.db_address = None
self.global_context = {}
class MongoShell(ExternalProgram):
"""A locally-running MongoDB shell process.
Makes it easy to start with custom global variables, pointed at a custom database, etc.
"""
def __init__(self,
executable=MONGOSHELL_DEFAULT_EXEC,
shell_context=None,
db_address=None,
global_context={},
js_filenames=[],
custom_kwargs=MONGOSHELL_KWARGS,
**kwargs):
ExternalProgram.__init__(self, executable, custom_kwargs=custom_kwargs, **kwargs)
self.shell_context = shell_context
if not shell_context:
self.shell_context = MongoShellContext()
self.shell_context.db_address = db_address
self.shell_context.global_context.update(global_context)
self.js_filenames = js_filenames
def build_eval_context(self):
eval_strs = []
for variable, variable_json in self.shell_context.global_context.iteritems():
eval_strs.append("%s=%s;" % (variable, json.dumps(variable_json)))
return "".join(eval_strs)
def build_process(self):
process_context = self.context.clone()
if self.shell_context.global_context:
eval_context_str = self.build_eval_context()
if "eval" in process_context.kwargs:
process_context.kwargs["eval"] = process_context.kwargs["eval"] + ";" + \
eval_context_str
else:
process_context.kwargs["eval"] = eval_context_str
process = ExternalProgram.build_process(self, process_context)
if self.shell_context.db_address:
process.arguments.append(self.shell_context.db_address)
else:
process.arguments.append("--nodb")
if self.js_filenames:
for js_filename in self.js_filenames:
process.arguments.append(js_filename)
return process
#
# Default DBTest options
#
DBTEST_DEFAULT_EXEC = "./dbtest"
DBTEST_KWARGS = dict(BUILDLOGGER_CUSTOM_KWARGS.items() + VERBOSE_CUSTOM_KWARGS.items())
class DBTest(ExternalProgram):
"""A locally running MongoDB dbtest process.
Makes it easy to start with custom named dbtests.
"""
def __init__(self,
executable=DBTEST_DEFAULT_EXEC,
dbtest_names=[],
custom_kwargs=DBTEST_KWARGS,
**kwargs):
ExternalProgram.__init__(self, executable, custom_kwargs=custom_kwargs, **kwargs)
self.dbtest_names = dbtest_names
def build_process(self):
process = ExternalProgram.build_process(self)
for dbtest_name in self.dbtest_names:
process.arguments.append(dbtest_name)
return process
|