-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
414 lines (383 loc) · 11.9 KB
/
index.js
File metadata and controls
414 lines (383 loc) · 11.9 KB
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
var _ = require("lodash"),
Promise = require("bluebird"),
path = require("path"),
fs = require("fs-extra"),
os = require('os'),
http = require('https'),
getos = Promise.promisify(require('getos')),
url = require('url'),
findPort = Promise.promisify(require("find-free-port")),
Decompress = Promise.promisifyAll(require("decompress")),
readline = require('readline'),
EventEmitter = require('events').EventEmitter,
util = require('util'),
spawn = require('child_process').spawn,
DOWNLOAD_URI = "https://fastdl.mongodb.org";
function RapidMango(options) {
options = options || {};
options.installPath = options.installPath ||
path.resolve(path.dirname(module.parent.filename), "mongo");
options.version = options.version ||
"3.2.0"
options.dbpath = options.dbpath || path.resolve(options.installPath, "data");
options.startPort = options.startPort || 6000;
options.endPort = options.endPort || 6999;
options.args = options.args || {};
options.deleteTemporaryFiles = options.deleteTemporaryFiles === undefined ?
false : options.deleteTemporaryFiles;
options.args["--dbpath"] = options.args["--dbpath"] != undefined ?
options.args["--dbpath"] : options.dbpath;
options.mongodBin = path.resolve(options.installPath, "bin", "mongod" +
(process.platform === "win32" ? ".exe" : ""));
this.options = options;
this.child = null;
return this;
}
util.inherits(RapidMango, EventEmitter);
RapidMango.prototype.download = function download() {
var self = this,
dl_uri = DOWNLOAD_URI;
return new Promise((resolve, reject) => {
var platform = self.options.platform || os.platform(),
mongo_platform = "";
switch(platform) {
case "darwin":
mongo_platform = "osx";
break;
case "win32":
mongo_platform = "win32";
break;
case "linux":
mongo_platform = "linux";
break;
case "elementary OS": //os.platform() doesn't return linux for elementary OS.
mongo_platform = "linux";
break;
case "sunos":
mongo_platform = "sunos5";
break;
default:
self.emit("debug", "unsupported platform %s by MongoDB", platform);
throw new Error("unsupported OS");
}
self.emit("debug", "selected platform %s", mongo_platform);
dl_uri += "/" + mongo_platform;
var arch = self.options.arch || os.arch();
if ( arch === "ia32" ) {
if ( platform === "linux" ) {
mongo_arch = "i686";
} else if ( platform === "win32" ) {
mongo_arch = "i386";
} else {
self.emit("debug", "unsupported platform and os combination");
throw new Error("unsupported architecture");
}
} else if ( arch === "x64" ) {
mongo_arch = "x86_64";
} else {
self.emit("debug", "unsupported architecture");
throw new Error("unsupported architecture, ia32 and x64 are the only valid options");
}
self.emit("debug", "selected architecture %s", mongo_arch);
var mongo_version = self.options.version || undefined;
if (! mongo_version )
throw new Error("missing version");
self.emit("debug", "selected version: %s", mongo_version);
var name = "mongodb-" + mongo_platform + "-" + mongo_arch;
if ( mongo_platform === "linux" && mongo_arch !== "i686" ) {
return getos().then((os) => {
self.emit("debug", "os dump", os);
if ( /ubuntu/i.test(os.dist) ) {
name += "-ubuntu";
var ubuntu_version = os.release.split('.'),
major_version = ubuntu_version[0],
minor_version = ubuntu_version[1];
if ( os.release == "14.04" || major_version > 14) {
name += "1404";
} else if ( os.release == "12.04" ) {
name += "1204";
} else if ( os.release == "14.10" ) {
name += "1410-clang";
} else {
self.emit("debug", "using legacy release");
}
} else if ( /elementary OS/i.test(os.dist) ) {
//use ubuntu version since Elementary OS Freya is based on Ubuntu 14.04
//unfortunately os didn't seem to contain release field for Elementary OS.
name += "-ubuntu";
name += "1404";
} else if ( /suse/i.test(os.dist) ) {
name += "-suse";
if ( /^11/.test(os.release) ) {
name += "11";
} else {
self.emit("debug", "using legacy release");
}
} else if ( /rhel/i.test(os.dist) || /centos/i.test(os.dist) || /scientific/i.test(os.dist) ) {
name += "-rhel";
if ( /^7/.test(os.release) ) {
name += "70";
} else if ( /^6/.test(os.release) ) {
name += "62";
} else if ( /^5/.test(os.release) ) {
name += "55";
} else {
self.emit("debug", "using legacy release");
}
} else if ( /fedora/i.test(os.dist) ) {
// based on https://fedoraproject.org/wiki/Red_Hat_Enterprise_Linux?rd=RHEL#History
name += "-rhel";
var fedora_version = Number(os.release);
if ( fedora_version > 18 ) {
name += "70";
} else if ( fedora_version < 19 && fedora_version >= 12 ) {
name += "62";
} else if ( fedora_version < 12 && fedora_version >= 6 ) {
name += "55";
} else {
self.emit("debug", "using legacy release");
}
} else if ( /debian/i.test(os.dist) ) {
name += "-debian";
if ( /^(7|8)/.test(os.release) ) {
name += "71";
} else {
//throw new Error("unsupported release of Debian " + os.release);
self.emit("debug", "using legacy release");
}
} else {
self.emit("debug", "using legacy release");
}
name += "-" + mongo_version;
return resolve([name, mongo_platform]);
});
} else {
name += "-" + mongo_version;
return resolve([name, mongo_platform]);
}
}).then((results) => {
var mongo_archive = "",
name = results[0],
mongo_platform = results[1];
if ( mongo_platform === "win32" ) {
mongo_archive = "zip";
} else {
mongo_archive = "tgz";
}
self.emit("debug", "selected archive %s", mongo_archive);
name += "." + mongo_archive;
self.emit("debug", "final name: %s", name);
dl_uri += "/" + name;
self.emit("verbose", "Downloading: %s", dl_uri);
var temp_dir = self.options.downloadDir || path.resolve(os.tmpdir(), 'mongodb-download'),
downloadDir = path.resolve(temp_dir);
return fs.mkdirp(downloadDir).then(() => {
return new Promise((resolve, reject) => {
self.emit("debug", "download directory: %s", temp_dir);
var download_location = path.resolve(downloadDir, name);
var temp_download_location = path.resolve(downloadDir, name + ".in_progress");
self.emit("debug", "download complete path: %s", download_location);
try {
var stats = fs.lstatSync(download_location);
self.emit("debug", "sending file from cache");
return resolve(download_location);
} catch (e) {
if ( e.code !== "ENOENT" ) throw e;
}
var file = fs.createWriteStream(temp_download_location),
httpOpts = self.options.httpOpts || {},
download_url = url.parse(dl_uri);
httpOpts.protocol = download_url.protocol;
httpOpts.hostname = download_url.hostname;
httpOpts.path = download_url.path;
self.emit("debug", "http self.options:", httpOpts);
var request = http.get(httpOpts, (response) => {
var cur = 0,
len = parseInt(response.headers['content-length'], 10),
total = len / 1048576;
response.pipe(file);
file.on('finish', () => {
file.close(() => {
fs.rename(temp_download_location, download_location).then(() => {
resolve(download_location);
}).catch(() => {
reject("Failed to rename temp file");
});
});
});
var last_percent = 0;
response.on("data", (chunk) => {
cur += chunk.length;
var percent_complete = (100.0 * cur / len).toFixed(1);
var mb_complete = (cur / 1048576).toFixed(1);
if (percent_complete != last_percent)
self.emit("progress", percent_complete, mb_complete);
last_percent = percent_complete;
});
request.on("error", (e) => {
self.emit("debug", "request error:", e);
reject(e);
});
});
});
});
});
};
RapidMango.prototype.install = function install() {
var self = this,
fileExists;
self.emit("verbose", "Checking for mongod binary: " +
self.options.mongodBin);
if (fs.access) {
self.emit("debug", "using fs.access");
fileExists = fs.access(self.options.mongodBin, fs.F_OK);
} else if (fs.stat) {
self.emit("debug", "using fs.stat");
fileExists = fs.stat(self.options.mongodBin).then((stat) => {
self.emit("debug", stat);
});
} else if (fs.exists) {
self.emit("debug", "using fs.exists");
fileExists = new Promise((resolve, reject) => {
fs.exists((exists) => {
if (exists) {
resolve();
} else {
reject(new Error("File does not exist"));
}
});
});
} else {
return Promise.reject(new Error("Can't find file exists type method, downloading anyway..."));
}
return fileExists.catch((err) => {
self.emit("debug", err);
return Promise.all([
self.download(),
fs.mkdirp(path.resolve(self.options.installPath))
]).then((results) => {
var archiveFilename = results[0],
archiveType;
self.emit("verbose", "Decompressing archive...");
if (/\.tgz$/.test(archiveFilename))
archiveType = "targz";
if (/\.zip/.test(archiveFilename))
archiveType = "zip";
var decomp = Decompress({})
.src(archiveFilename)
.dest(self.options.installPath)
.use(Decompress[archiveType]({
strip: 1
}));
Promise.promisifyAll(decomp);
return decomp.runAsync().then(() => {
if(self.options.deleteTemporaryFiles)
return fs.unlink(archiveFilename);
});
});
});
};
RapidMango.prototype.start = function start() {
var self = this;
return self.install().then(() => {
return fs.mkdirp(path.resolve(self.options.args["--dbpath"]))
})
.then(() => {
return self.options.port ||
findPort(self.options.startPort, self.options.endPort);
})
.then((port) => {
self.emit("verbose", "Starting mongod...");
var args = [];
self.options.args["--port"] =
self.options.args["--port"] !== undefined ?
self.options.args["--port"] : port;
_.map(self.options.args, (val, key) => {
if (val === true) {
args.push(key);
} else if (val !== false) {
args.push(key);
args.push(val);
}
});
var promise = new Promise((resolve, reject) => {
self.emit("debug", "spawning: ", self.options.mongodBin, args);
self.child = spawn(self.options.mongodBin, args, {
stdio: 'pipe'
});
self.child.on('error', (code, signal) => {
if (promise.isPending)
reject(new Error("Failed to start mongo, child exited with code " + code));
delete self.child;
self.emit('exit', code, signal);
});
self.child.on('exit', (code, signal) => {
if (promise.isPending)
reject(new Error("Mongo child exited with code " + code));
delete self.child;
self.emit('exit', code, signal);
});
readline.createInterface({
input: self.child.stdout,
terminal: false
}).on("line", (line) => {
if (promise.isPending) {
if (/waiting for connections/.test(line))
resolve(self.options.args["--port"]);
}
self.emit("stdout", line);
});
readline.createInterface({
input: self.child.stderr,
terminal: false
}).on("line", (line) => {
self.emit("stderr", line);
});
// tie process, if parent dies, kill child.
// I hate this hack
spawn(process.execPath, [
path.resolve(__dirname, "tie-process.js"),
process.pid,
self.child.pid
], {
stdio: 'ignore'
});
});
return promise;
});
};
RapidMango.prototype.stop = function stop() {
var self = this;
return new Promise((resolve, reject) => {
if (self.child === undefined) {
resolve(0);
return;
}
self.child.on('close', (code) => {
resolve(code);
});
self.child.on('error', (err) => {
reject(err);
});
try {
self.child.kill();
delete self.child;
} catch (err) {
reject(err);
}
});
};
RapidMango.prototype.status = function status() {
var result = {
status: 'stopped',
pid: null,
}
if(this.child && this.child.pid) {
result.status = 'started'
result.pid = this.child.pid
}
return new Promise((resolve) => {
resolve(result)
});
};
module.exports = RapidMango;