-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathapp.js
425 lines (377 loc) · 9.61 KB
/
app.js
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
const argv = require('boring')();
const _ = require('lodash');
const fs = require('fs');
const shelljs = require('shelljs');
const shellEscape = require('shell-escape');
let dataFile;
if (argv.data) {
dataFile = argv.data;
delete argv.data;
} else {
dataFile = '/var/lib/misc/mechanic.json';
// The Unix File Hierarchy Standard says that all distros should
// have a /var/lib/misc folder for storage of "state files
// that don't need a directory." But create it if it's
// somehow missing (Mac for instance).
if (!fs.existsSync('/var/lib/misc')) {
fs.mkdirSync('/var/lib/misc', 0o700);
}
}
let data = require('prettiest')({ json: dataFile });
let defaultSettings = {
conf: '/etc/nginx/conf.d',
overrides: '/etc/nginx/mechanic-overrides',
logs: '/var/log/nginx',
restart: 'nginx -s reload',
bind: '*'
};
_.defaults(data, { settings: {} });
_.defaults(data.settings, defaultSettings);
let settings = data.settings;
const nunjucks = require('@apostrophecms/nunjucks');
let command = argv._[0];
if (!command) {
usage();
}
let aliases = {
'backend': 'backends'
};
let options = {
'host': 'string',
'backends': 'addresses',
'aliases': 'strings',
'canonical': 'boolean',
'default': 'boolean',
'static': 'string',
'autoindex': 'boolean',
'https': 'boolean',
'http2': 'boolean',
'redirect-to-https': 'boolean',
'https-upstream': 'boolean',
'websocket': 'boolean', // Included for accidental BC coverage.
'websockets': 'boolean',
'redirect': 'string',
'redirect-full': 'string',
'permanent': 'boolean',
'path': 'string'
};
let parsers = {
string: function(s) {
return s.trim();
},
integer: function(s) {
return parseInt(s, 10);
},
integers: function(s) {
return _.map(parsers.strings(s), function(s) {
return parsers.integer(s);
});
},
addresses: function(s) {
return _.map(parsers.strings(s), function(s) {
let matches = s.match(/^(([^:]+):)?(\d+)(\/.*)?$/);
if (!matches) {
throw 'A list of port numbers and/or address:port combinations with optional paths is expected, separated by commas';
}
let host, port, path;
if (matches[2]) {
host = matches[2];
} else {
host = 'localhost';
}
port = matches[3];
path = matches[4];
const pathString = (path != null) ? path : '';
return `${host}:${port}${pathString}`;
});
},
strings: function(s) {
return s.toString().split(/\s*,\s*/);
},
boolean: function(s) {
// eslint-disable-next-line eqeqeq
return (s === 'true') || (s === 'on') || (s == 1);
},
// Have a feeling we'll use this soon
keyValue: function(s) {
s = parsers.string(s);
let o = {};
_.each(s, function(v) {
let matches = v.match(/^([^:]+):(.*)$/);
if (!matches) {
throw 'Key-value pairs expected, like this: key:value,key:value';
}
o[matches[1]] = matches[2];
});
return o;
}
};
let stringifiers = {
string: function(s) {
return s;
},
integer: function(s) {
return s;
},
strings: function(s) {
return s.join(',');
},
boolean: function(s) {
return s ? 'true' : 'false';
},
keyValue: function(o) {
return _.map(o, function(v, k) {
return k + ':' + v;
}).join(',');
},
addresses: function(s) {
return s.join(',');
}
};
data.sites = data.sites || [];
if (command === 'add') {
update(true);
} else if (command === 'update') {
update(false);
} else if (command === 'remove') {
remove();
} else if (command === 'refresh') {
refresh();
} else if (command === 'list') {
list();
} else if (command === 'set') {
set();
} else if (command === 'reset') {
reset();
} else {
usage();
}
function usage(m) {
if (m) {
console.error(m);
}
console.error('See https://github.com/punkave/mechanic for usage.');
process.exit(1);
}
function set() {
// Top-level settings: nginx conf folder, logs folder,
// and restart command
if (argv._.length !== 3) {
usage("The \"set\" command requires two parameters:\n\nmechanic set key value");
}
data.settings[argv._[1]] = argv._[2];
go();
}
function update(add) {
if (argv._.length !== 2) {
usage('shortname argument is required; also --host');
}
let shortname = argv._[1];
let site;
if (add) {
if (findSite(shortname)) {
usage('Site already exists, use update');
} else {
site = { shortname: shortname };
data.sites.push(site);
}
} else {
site = findSite(shortname);
if (!site) {
usage('Unknown site: ' + shortname);
}
}
_.each(argv, function(val, key) {
if (key === '_') {
return;
}
if (_.has(aliases, key)) {
key = aliases[key];
}
if (!_.has(options, key)) {
usage('Unrecognized option: ' + key);
}
try {
if (key === 'redirect') {
delete site['redirect-full'];
} else if (key === 'redirect-full') {
delete site['redirect'];
}
site[key] = parsers[options[key]](val);
} catch (e) {
console.error(e);
usage('Value for ' + key + ' must be of type: ' + options[key]);
}
});
go();
}
function remove() {
if (argv._.length !== 2) {
usage();
}
let shortname = argv._[1];
let found = false;
data.sites = _.filter(data.sites || [], function(site) {
if (site.shortname === shortname) {
found = true;
return false;
}
return true;
});
if (!found) {
// It's not fatal but it's warning-worthy
console.error('Not found: ' + shortname);
return;
}
go();
}
function refresh() {
go();
}
function validSiteFilter(site) {
if ((!(site.backends && site.backends.length)) && (!site.static) && (!site.redirect) && (!site['redirect-full'])) {
console.warn('WARNING: skipping ' + site.shortname + ' because no backends have been specified (hint: --backends=portnumber)');
return false;
}
return true;
}
function go() {
// Reorder the sites so that default servers come after
// all others. According to the nginx documentation this
// shouldn't matter because any explicit server_name matches
// should win, but we've seen exceptions, and this is
// aesthetically pleasing anyway. -Tom
_.each(data.sites, function(site, i) {
site._index = i;
});
data.sites.sort(function(a, b) {
if (a.default === b.default) {
if (a._index < b._index) {
return -1;
} else if (b._index > a._index) {
return 1;
} else {
return 0;
}
} else {
if (a.default) {
return 1;
} else if (b.default) {
return -1;
}
}
});
_.each(data.sites, function(site) {
delete site._index;
});
let sites = _.filter(data.sites, validSiteFilter);
sites = sites.map(site => {
site.backends = site.backends || [];
site.backends.sort((b1, b2) => {
const p1 = pathOf(b1);
const p2 = pathOf(b2);
if (p1 < p2) {
return -1;
} else if (p2 > p1) {
return 1;
} else {
return 0;
}
});
site.backendGroups = [];
let lastPath = null;
let group;
for (const backend of site.backends) {
if (pathOf(backend) !== lastPath) {
group = {
path: pathOf(backend),
backends: [ withoutPath(backend) ]
};
lastPath = pathOf(backend);
} else {
group.backends.push(withoutPath(backend));
}
if (group.backends.length === 1) {
site.backendGroups.push(group);
}
}
return site;
});
let template = fs.readFileSync(settings.template || (__dirname + '/template.conf'), 'utf8');
let output = nunjucks.renderString(template, {
sites: sites,
settings: settings
});
// Set up include-able files to allow
// easy customizations
_.each(sites, function(site) {
let folder = settings.overrides;
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder);
}
folder += '/' + site.shortname;
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder);
}
let files = [ 'location', 'proxy', 'server', 'top' ];
_.each(files, function(file) {
let filename = folder + '/' + file;
if (!fs.existsSync(filename)) {
fs.writeFileSync(filename, '# Your custom nginx directives go here\n');
}
});
});
fs.writeFileSync(settings.conf + '/mechanic.conf', output);
if (settings.restart !== false) {
let restart = settings.restart || 'service nginx reload';
if (shelljs.exec(restart).code !== 0) {
console.error('ERROR: unable to reload nginx configuration!');
process.exit(3);
}
}
// Under 0.12 (?) this doesn't want to terminate on its own,
// not sure who the culprit is
process.exit(0);
}
function findSite(shortname) {
return _.find(data.sites, function(site) {
return site.shortname === shortname;
});
}
function list() {
_.each(data.settings, function(val, key) {
if (val !== defaultSettings[key]) {
console.info(shellEscape([ 'mechanic', 'set', key, val ]), '\n');
}
});
_.each(data.sites, function(site) {
let words = [ 'mechanic', 'add', site.shortname ];
_.each(site, function(val, key) {
if (_.has(stringifiers, options[key])) {
words.push('--' + key + '=' + stringifiers[options[key]](val));
}
});
console.info(shellEscape(words), '\n');
});
}
function reset() {
data.settings = defaultSettings;
data.sites = [];
go();
}
function pathOf(backend) {
const slashAt = backend.indexOf('/');
if (slashAt !== -1) {
return backend.substring(slashAt);
} else {
return '/';
}
}
function withoutPath(backend) {
const slashAt = backend.indexOf('/');
if (slashAt !== -1) {
return backend.substring(0, slashAt);
} else {
return backend;
}
}