-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcompiler.ts
411 lines (337 loc) · 13.3 KB
/
compiler.ts
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
"use strict";
import * as async from "async";
import * as child_process from "child_process";
import * as program from "commander";
import * as fse from "fs-extra";
import * as http from "http";
import * as mongodb from "mongodb";
import * as os from "os";
import * as path from "path";
import * as request from "request";
import { BuilderError } from "./builder_error";
import { ICompilation } from "./compilation";
import * as globals from "./globals";
import { INotificationData } from "./notifier";
import * as service from "./service";
import mongoDbQueue = require("mongodb-queue");
export interface IErrorResponse {
status: string;
description: string;
code: number;
}
export interface IConfigJson {
code: string;
platforms: Array<{
name: string,
icon?: {
url: string,
},
splash?: {
url: string,
},
}>;
config: string;
source: string;
libVersion: string;
}
interface ICompilerPostData {
platforms: string[];
}
interface ICompilerOptions extends service.IGlobalOptions {
path: string;
}
const CONFIG_JSON: string = "config.json";
export const ID: string = "cocoon-compiler";
export class Compiler extends service.CocoonService {
private static COMPILER_LOOP_INTERVAL: number = 5000;
private static COMPILER_WATCHDOG_INTERVAL: number = 2700000;
private _queue: any;
private _watchdogTimer: NodeJS.Timer;
private get path(): string {
const tools: string = path.join(this.androidHome, "tools");
const platformTools: string = path.join(this.androidHome, "platform-tools");
return process.env.PATH + path.delimiter + tools + path.delimiter + platformTools;
}
private get androidHome(): string {
return path.join(globals.SDKS_PATH(this._env), "android-sdks-" + os.platform());
}
public constructor(options?: service.IGlobalOptions) {
super(ID, Compiler.COMPILER_LOOP_INTERVAL, options);
this._watchdogTimer = null;
}
protected onStart(): void {
const connection = "mongodb://localhost:27017/" + globals.getMongoDBName(this._env);
mongodb.MongoClient.connect(connection, {})
.then((mongoClient: mongodb.MongoClient) => {
mongoClient.db().on("close", (error: Error) => {
this._logger.fatal("connection to mongodb closed, stopping...", error);
this.stop();
return;
});
this._queue = mongoDbQueue(mongoClient.db(), globals.NOTIFICATIONS_QUEUE);
})
.catch((err: mongodb.MongoError) => {
this._logger.fatal("cannot connect to the notifications queue, stopping...", err);
this.stop();
return;
});
}
protected onStop(): void {
return;
}
protected loop(): void {
// Check if the updater data folder has been initialized
const ready = path.join(globals.COMPILER_DATA_PATH(this._env), "ready.lock");
if (!fse.existsSync(ready)) {
this._logger.info("skipping compilation, products not ready yet");
return;
}
if (this._working) {
return;
}
this.working(true);
async.waterfall([
this.init.bind(this),
this.fetch.bind(this),
this.build.bind(this),
], (err: BuilderError, data?: ICompilation) => {
if (err) {
this._logger.error("compilation finished: " + err.message);
} else {
this._logger.info("compilation finished: " + data.code);
}
if (data) {
const notification: INotificationData = {
code: data.code,
platform: data.platform.name,
starttime: data.starttime,
};
if (err) {
notification.msg_internal = err.message;
notification.msg_public = err.msgPublic;
}
if (this._options.service) {
this.notify(notification, (error: Error) => {
if (error) {
this._logger.error(error.message);
}
});
}
}
this.working(false);
if (!this._options.service) {
if (err) {
process.exit(-1);
} else {
process.exit(0);
}
}
});
}
protected init(cb: (error?: Error) => void): void {
this._logger.info("init");
fse.ensureDir(globals.PROJECTS_PATH(this._env), (err: any) => {
if (err) {
this._logger.fatal("cannot create workspace folder");
cb(new Error(err));
return;
}
cb();
});
}
private fetch(cb: (error?: Error, result?: any) => void): void {
this._logger.info("fetch");
const processData = (configJson: string) => {
const json: IConfigJson = JSON.parse(configJson);
if (!json.code || !json.platforms || !json.config || !json.source || !json.libVersion) {
cb(new Error("Malformed config.json"));
return;
}
if (json) {
const timestamp: number = new Date().getTime();
const data: ICompilation = {
code: json.code,
config: json.config,
libVersion: json.libVersion,
platform: json.platforms[0],
source: json.source,
starttime: timestamp,
};
try {
fse.outputFileSync(globals.getConfigJsonPath(this._env, data.code, data.starttime),
JSON.stringify(json, null, " "));
this._logger.debug(CONFIG_JSON, JSON.stringify(json, null, " "));
cb(null, data);
return;
} catch (ex) {
cb(new Error(ex.message));
return;
}
}
};
const options: ICompilerOptions = this._options as ICompilerOptions;
if (!options.service) {
const configJson: string = path.join(options.path, CONFIG_JSON);
processData(fse.readFileSync(configJson, "UTF8"));
} else {
const postData: ICompilerPostData = {
platforms: globals.getLocalPlatforms(),
};
request({
body: JSON.stringify(postData),
headers: {
"Authorization": "Basic YWRtaW46ZS8zN2l+ZSVJQUJPMUIqXw==",
"Content-Type": "application/json",
"Host": globals.envToHost(this._env),
},
method: "POST",
timeout: 10000,
uri: "https://" + globals.envToHost(this._env) + "/api/v1/compilation",
}, (error: any, response: http.IncomingMessage, body: any): void => {
if (error) {
cb(error);
return;
}
if (response.statusCode >= 200 && response.statusCode < 400) {
processData(body);
} else {
if (body) {
const errorResponse: IErrorResponse = JSON.parse(body);
cb(new Error(errorResponse.description));
} else {
cb(new Error("Cannot read response from server"));
}
}
});
}
}
private build(data: ICompilation, cb: (error?: Error, result?: any) => void): void {
this._logger.info("compile");
const workspace = path.join(globals.PROJECTS_PATH(this._env), data.code + "_" + data.starttime);
const environment: { [key: string]: string } = {};
environment.HOME = globals.getHome();
environment.PATH = this.path;
if (data.platform.name === "android") {
environment.ANDROID_HOME = this.androidHome;
environment.JAVA_HOME = globals.getJavaHome();
}
const regex = new RegExp(workspace.replace(/\\/g, "\\\\")
+ "|" + globals.getHome().replace(/\\/g, "\\\\"), "g");
const stdout = fse.createWriteStream(path.join(workspace, "stdout.log"));
const builder: child_process.ChildProcess = child_process.fork(
path.join(path.dirname(require.main.filename), "builder_launcher.js"),
[
"-l", this._options.logLevel,
"-j", JSON.stringify(data),
"-p", globals.getConfigJsonPath(this._env, data.code, data.starttime),
"-e", globals.envToString(this._env),
],
{
cwd: process.cwd(),
env: environment,
execArgv: [],
silent: true,
},
);
let cbCalled = false;
const finishBuild = (error?: Error, result?: any) => {
stdout.close();
clearInterval(this._watchdogTimer);
this._watchdogTimer = null;
if (!cbCalled) {
cbCalled = true;
cb(error, result);
}
};
builder.stdout.on("data", (buffer: Buffer) => {
stdout.write(buffer.toString("UTF8").replace(regex, ""));
console.log(buffer.toString("UTF8").trim());
});
builder.stderr.on("data", (buffer: Buffer) => {
stdout.write(buffer.toString("UTF8").replace(regex, ""));
console.error(buffer.toString("UTF8").trim());
});
builder.on("message", (error: BuilderError) => {
if (error) {
let log: string = "No log available";
if (fse.existsSync(path.join(workspace, "cordova.log"))) {
log = fse.readFileSync(path.join(workspace, "cordova.log")).toString().replace(regex, "");
}
if (error.msgPublic) {
error.msgPublic = "COMPILER ERROR: \n\n" + error.msgPublic.replace(regex, "")
+ "\n\nCORDOVA LOG: \n\n" + log.slice(-10000);
} else {
error.msgPublic = "CORDOVA LOG: \n\n" + log;
}
if (!error.message) {
error.message = fse.readFileSync(path.join(workspace, "stdout.log")).toString();
}
finishBuild(error, data);
return;
}
finishBuild(null, data);
return;
});
builder.on("exit", (code: number, signal: string) => {
if (code !== 0) {
stdout.write("Process exited abnormally (" + signal + "): " + code);
finishBuild(new Error("Process exited abnormally (" + signal + "): " + code), data);
return;
}
// If the process finishes without error it should be because we have received a finish message.
// This is here only for the case were something weird happens and we don't get a message but the process
// exits without a signal and the return code is 0.
this._logger.info("Process exited. (signal: " + signal + ") (code: " + code + ")");
try {
finishBuild(null, data);
return;
} catch (e) {
this._logger.debug(e);
}
});
builder.on("error", (err: Error) => {
this._logger.error("Process exited with error(" + err.name + "): " + err.message + "\n" + err.stack);
finishBuild(err, data);
return;
});
clearInterval(this._watchdogTimer);
this._watchdogTimer = setInterval(() => {
builder.kill("SIGKILL");
finishBuild(new BuilderError(
"Compilation took too long, killing...",
"The compilation exceed the designated time."),
data);
return;
}, Compiler.COMPILER_WATCHDOG_INTERVAL);
}
private notify(notification: INotificationData, cb: (error: Error) => void): void {
this._logger.info("notify", notification.code);
this._queue.add(notification, (err: Error, id: string) => {
if (err) {
this._logger.error("cannot add notification to queue", err);
cb(err);
return;
}
this._logger.info("notification added", id);
cb(null);
});
}
}
program
.version(globals.getVersion())
.option("-c, --console", "Console mode")
.option("-e, --env <env>", "Environment", /^(develop|testing|production)$/i, "develop")
.option("-l, --logLevel <level>", "Log level", /^(all|trace|debug|info|warn|error|fatal|mark|off)$/i, "info")
.option("-p, --path <path>", "Cloud project path containing the config.json")
.parse(process.argv);
if (program.console) {
const options: ICompilerOptions = {
env: program.env,
logLevel: program.logLevel,
path: program.path,
service: false,
};
new Compiler(options).start();
} else {
new Compiler().start();
}