UNPKG

10 kBJavaScriptView Raw
1"use strict";
2var path = require('path')
3 , basename = path.basename(__filename, '.js')
4 , debug = require('debug')('castor:' + basename)
5 , util = require('util')
6 , minimist = require('minimist')
7 , portfinder = require('portfinder')
8 , kuler = require('kuler')
9 , os = require('os')
10 , fs = require('fs')
11 , app = require('./app')
12 ;
13
14module.exports = function(warmup) {
15
16 var argv = minimist(process.argv.slice(2), {
17 alias: {
18 n: 'dry-run',
19 h: 'help',
20 V: 'version',
21 v: 'verbose',
22 d: 'debug'
23 },
24 boolean: ['help', 'version', 'verbose', 'debug', 'dry-run']
25 });
26
27 var appname = path.basename(process.argv[1])
28 var usage = [
29 "Usage: " + appname + " [options...] <path>",
30 "",
31 "Options:",
32 "\t -h, --help Show usage and exit",
33 "\t -n, --dry-run Show config and exit",
34 "\t -v, --verbose Make the operation more talkative",
35 "\t -V, --version Show version number and quit",
36 "",
37 "It will look in all the obvious places to set the configuration:",
38 " - command line arguments",
39 " - environment variables prefixed with " + appname + "_",
40 " - if you passed an option --config file then from that file",
41 " - a local ." + appname + "rc or the first found looking in ./ ../ ../../ ../../../ etc.",
42 " - $HOME/." + appname + "rc",
43 " - $HOME/." + appname + "/config",
44 " - $HOME/.config/" + appname + "",
45 " - $HOME/.config/" + appname + "/config",
46 " - /etc/" + appname + "rc",
47 " - /etc/" + appname + "/config",
48 " - " + process.cwd() + "/config.local.json",
49 " - " + process.cwd() + "/config.local.js",
50 " - {dataPath}.json",
51 " - {dataPath}.js",
52 ].join("\n");
53
54
55 if (argv.help) {
56 console.info(usage)
57 process.exit(0);
58 }
59
60 if (argv.version) {
61 console.info(require('./package.json').version);
62 process.exit(0);
63 }
64
65 // if (!argv.verbose) {
66 // console.log = require('debug')('console:log');
67 // }
68
69 //
70 // Environement vars
71 //
72 // Docker and/or ezmaster
73 //
74 var mongoHostPort;
75
76 mongoHostPort = process.env.MONGODB_PORT
77 ? process.env.MONGODB_PORT.replace('tcp://', '')
78 : 'localhost:27017'
79 ;
80
81 mongoHostPort = process.env.EZMASTER_MONGODB_HOST_PORT
82 ? process.env.EZMASTER_MONGODB_HOST_PORT.replace('tcp://', '')
83 : mongoHostPort
84 ;
85
86
87 appname = process.env.EZMASTER_TECHNICAL_NAME
88 ? process.env.EZMASTER_TECHNICAL_NAME
89 : appname;
90
91
92
93 //
94 // Default config parameters
95 //
96 var Configurator = require('./configurator.js')
97 var config = new Configurator();
98 config.fix('databaseHost', mongoHostPort);
99 config.fix('databaseName', appname);
100 config.fix('collectionNameIndex', 'index');
101 config.fix('collectionNameHotFields', 'hotfields');
102 config.fix('collectionNameHotFolder', 'hotfolder');
103 config.fix('defaultRootCollection', 'index');
104 config.fix('debug', false);
105 config.fix('trustProxy', false);
106 config.fix('defaultEngine', 'html');
107 config.fix('port', '3000');
108 config.fix('timeout', 120000);
109 config.fix('delay', 250);
110 config.fix('logFormat', 'combined');
111 config.fix('title', 'Change title');
112 config.fix('description', 'Change description');
113 config.fix('itemsPerPage', 30);
114 config.fix('maxAge', '1 day');
115 config.fix('concurrency', os.cpus().length);
116 config.fix('writeConcern', 1);
117 config.fix('rootURL', '/index.html');
118 config.fix('loginURL', '/login.html');
119 config.fix('prefixURL', ''); // ex: /server1
120 config.fix('prefixKEY', '=');
121 config.fix('rootKEY', 'corpus');
122 config.fix('maxFileSize', 10485760); // 10 Mo
123 config.fix('acceptFileTypes', []);
124 config.fix('allowedAltValues', ['tsv', 'raw', 'min', 'dry']);
125 config.fix('mimeTypes', {
126 "application/json" : ['json', 'raw', 'jbj', 'min', 'dry']
127 });
128 config.fix('heartrate', 5000);
129 config.fix('filesToIgnore', [ "**/.*", "~*", "*~", "*.sw?", "*.old", "*.bak", "**/node_modules", "Thumbs.db" ]);
130 config.fix('tempPath', os.tmpdir());
131 config.fix('dataPath', path.normalize(path.resolve(process.cwd(), path.normalize(argv._.pop() || "./data"))));
132 config.fix('viewPath', path.resolve(__dirname, './app/views/'));
133 config.fix('middlewares', {});
134 config.fix('authorizations', []);
135 config.fix('strategies', []);
136 config.fix('models', {});
137 config.fix('filters', []);
138 config.fix('protocols', []);
139 config.fix('engines', []);
140 config.fix('routes', []);
141 config.fix('loaders', {});
142 config.fix('downloaders', {});
143 config.fix('heartbeats', {});
144 config.fix('middlewares', []);
145 config.fix('resources', {}); // for apiv1
146 config.fix('operators', {});
147 config.fix('computedFields', {}); // JBJ stylesheet to compute fields
148 // List of allowed values for 'typ=' parameter
149 config.fix('allowedTypValues', ['uri', 'form', 'file', 'fork']);
150 config.fix('datasetFields', {});
151 config.fix('documentFields', {});
152 config.fix('collectionFields', {
153 "id": {
154 "title" : "ID",
155 "stylesheet" : {
156 "content<" : {
157 "get": "_wid"
158 }
159 }
160 },
161 "title": {
162 "title" : "Title",
163 "stylesheet": {
164 "content<" : {
165 "get": ["_content.json.title", "title", "_text", "basename"],
166 "deduplicate" : true,
167 "cast" : "array",
168 "first": true,
169 "default" : "n/a"
170 }
171 }
172 }
173 });
174 config.fix('uniqueValueWith', {
175 "get": ["value", "_content.json.title", "title", "_label", "_text", "basename"],
176 "deduplicate" : true,
177 "cast" : "array",
178 "first": true,
179 "default" : "n/a"
180 });
181
182
183 config.load(appname, argv);
184
185 if (!fs.existsSync(config.get('dataPath'))) {
186 console.info(kuler('Hotfolder is disabled.', 'olive'), kuler("No dataPath specified.", "orange"));
187 config.unset('dataPath');
188 }
189
190 // Le chargement de la config local pourrait se faire après le chargement du castor.config.js (cf. app/helpers/view.js)
191 // mais le fichier local ne peut pas venir casser la configuration de castor.config.js
192 // il est plutot la pour ajouter de nouveaux paramètres propre à l'application
193 var localconfigs = [
194 path.normalize(path.join(process.cwd(), 'config.local.js')),
195 path.normalize(path.join(process.cwd(), 'config.local.json'))
196 ];
197 localconfigs.forEach(function(localfile) {
198 debug('localfile', localfile);
199 if (config.local(localfile)) {
200 console.info(kuler('Load local configuration file.', 'olive'), kuler(localfile, 'limegreen'));
201 }
202 });
203
204 portfinder.basePort = config.get('port');
205 portfinder.getPort(function (err, newport) {
206 if (err instanceof Error) {
207 console.error(kuler("Unable to get a free port. Try to stop some services.", "red"));
208 process.exit(2);
209 }
210 else {
211 config.set('port', newport);
212 warmup(config, function(online) {
213 //
214 // Load conf file attached to dataPath
215 //
216 if (config.has('dataPath')) {
217 var dataconfigs = [
218 path.normalize(config.get('dataPath')) + '.json',
219 path.normalize(config.get('dataPath')) + '.js'
220 ];
221 dataconfigs.forEach(function(datafile) {
222 if (config.local(datafile)) {
223 console.info(kuler('Load local configuration file.', 'olive'), kuler(datafile, 'limegreen'));
224 }
225 });
226 }
227 if (!config.has('baseURL')) {
228 config.set('baseURL', 'http://127.0.0.1:' + config.get('port'));
229 }
230
231 //
232 // Default errors tracing
233 //
234 if (online === undefined || typeof online !== 'function') {
235 online = function(err, core) {
236 if (err instanceof Error) {
237 console.error(kuler("Unable to init the server.", "red"), kuler(err.toString(), 'orangered'));
238 process.exit(3);
239 return;
240 }
241 var pack = config.get('package');
242 if (pack) {
243 console.info(kuler('App detected.', 'olive'), kuler(pack.name + ' ' + pack.version, 'limegreen'));
244 }
245 if (argv['dry-run']) {
246 console.info(String(' ').concat(util.inspect(config.config, { showHidden: false, depth: null, colors: true }).slice(1, -1).replace(/,\n/g, "\n").replace(/(\s\s\w+:) /g, "$1\t")));
247 core.server.close(function() {
248 console.info(kuler('Server is not started.', 'olive'), kuler(config.get('baseURL') + "/", "limegreen"));
249 process.exit(0);
250 });
251 }
252 else {
253 console.info(kuler('Server is listening.', 'olive'), kuler(config.get('baseURL') + "/", "limegreen"));
254 }
255 }
256 }
257
258 var srv = app(config, online);
259
260 process.on('SIGINT', function() {
261 console.info(kuler('Server is killed.', 'olive'), kuler('Caught SIGINT exiting', "limegreen"));
262 process.exit(1);
263 });
264
265 process.on('SIGTERM', function() {
266 srv.close(function() {
267 console.info(kuler('Server is stopped .', 'olive'), kuler('Caught SIGTERM exiting', "limegreen"));
268 process.exit(1);
269 });
270 });
271 })
272 }
273 });
274 }
275