-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathbuildArtifacts.js
257 lines (232 loc) · 8.87 KB
/
buildArtifacts.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
'use strict';
const fs = require('fs'),
path = require('path');
const unzipper = require('unzipper');
const logger = require('./logger').winstonLogger,
utils = require("./utils"),
Constants = require("./constants"),
config = require("./config");
const request = require('request');
let BUILD_ARTIFACTS_TOTAL_COUNT = 0;
let BUILD_ARTIFACTS_FAIL_COUNT = 0;
const parseAndDownloadArtifacts = async (buildId, data) => {
return new Promise(async (resolve, reject) => {
let all_promises = [];
let combs = Object.keys(data);
for(let i = 0; i < combs.length; i++) {
let comb = combs[i];
let sessions = Object.keys(data[comb]);
for(let j = 0; j < sessions.length; j++) {
let sessionId = sessions[j];
let filePath = path.join('./', 'build_artifacts', buildId, comb, sessionId);
let fileName = 'build_artifacts.zip';
BUILD_ARTIFACTS_TOTAL_COUNT += 1;
all_promises.push(downloadAndUnzip(filePath, fileName, data[comb][sessionId]).catch((error) => {
BUILD_ARTIFACTS_FAIL_COUNT += 1;
// delete malformed zip if present
let tmpFilePath = path.join(filePath, fileName);
if(fs.existsSync(tmpFilePath)){
fs.unlinkSync(tmpFilePath);
}
}));
}
}
await Promise.all(all_promises);
resolve();
});
}
const createDirIfNotPresent = async (dir) => {
return new Promise((resolve) => {
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
resolve();
});
}
const createDirectories = async (buildId, data) => {
// create dir for build_artifacts if not already present
let artifactsDir = path.join('./', 'build_artifacts');
if (!fs.existsSync(artifactsDir)){
fs.mkdirSync(artifactsDir);
}
// create dir for buildId if not already present
let buildDir = path.join('./', 'build_artifacts', buildId);
if (fs.existsSync(buildDir)){
// remove dir in case already exists
fs.rmdirSync(buildDir, { recursive: true, force: true });
}
fs.mkdirSync(buildDir);
let combDirs = [];
let sessionDirs = [];
let combs = Object.keys(data);
for(let i = 0; i < combs.length; i++) {
let comb = combs[i];
let combDir = path.join('./', 'build_artifacts', buildId, comb);
combDirs.push(createDirIfNotPresent(combDir));
let sessions = Object.keys(data[comb]);
for(let j = 0; j < sessions.length; j++) {
let sessionId = sessions[j];
let sessionDir = path.join('./', 'build_artifacts', buildId, comb, sessionId);
sessionDirs.push(createDirIfNotPresent(sessionDir));
}
}
return new Promise(async (resolve) => {
// create sub dirs for each combination in build
await Promise.all(combDirs);
// create sub dirs for each machine id in combination
await Promise.all(sessionDirs);
resolve();
});
}
const downloadAndUnzip = async (filePath, fileName, url) => {
let tmpFilePath = path.join(filePath, fileName);
const writer = fs.createWriteStream(tmpFilePath);
return new Promise(async (resolve, reject) => {
request.get(url).on('response', function(response) {
if(response.statusCode != 200) {
reject();
} else {
//ensure that the user can call `then()` only when the file has
//been downloaded entirely.
response.pipe(writer);
let error = null;
writer.on('error', err => {
error = err;
writer.close();
reject(err);
});
writer.on('close', async () => {
if (!error) {
await unzipFile(filePath, fileName);
fs.unlinkSync(tmpFilePath);
resolve(true);
}
//no need to call the reject here, as it will have been called in the
//'error' stream;
});
}
});
});
}
const unzipFile = async (filePath, fileName) => {
return new Promise( async (resolve, reject) => {
await decompress(path.join(filePath, fileName), filePath)
.then((files) => {
resolve();
})
.catch((error) => {
reject(error);
});
});
}
const sendUpdatesToBstack = async (bsConfig, buildId, args, options, rawArgs, buildReportData) => {
options.url = `${config.buildUrl}${buildId}/build_artifacts/status`;
let cypressConfigFile = utils.getCypressConfigFile(bsConfig);
let reporter = null;
if(!utils.isUndefined(args.reporter)) {
reporter = args.reporter;
} else if(cypressConfigFile !== undefined){
reporter = cypressConfigFile.reporter;
}
let data = {
feature_usage: {
downloads: {
eligible_download_folders: BUILD_ARTIFACTS_TOTAL_COUNT,
successfully_downloaded_folders: BUILD_ARTIFACTS_TOTAL_COUNT - BUILD_ARTIFACTS_FAIL_COUNT
},
reporter: reporter
}
}
options.formData = data.toString();
let responseData = null;
return new Promise (async (resolve, reject) => {
request.post(options, function (err, resp, data) {
if(err) {
utils.sendUsageReport(bsConfig, args, err, Constants.messageTypes.ERROR, 'api_failed_build_artifacts_status_update', buildReportData, rawArgs);
logger.error(utils.formatRequest(err, resp, data));
reject(err);
} else {
try {
responseData = JSON.parse(data);
} catch(e) {
responseData = {};
}
if (resp.statusCode != 200) {
if (responseData && responseData["error"]) {
utils.sendUsageReport(bsConfig, args, responseData["error"], Constants.messageTypes.ERROR, 'api_failed_build_artifacts_status_update', buildReportData, rawArgs);
reject(responseData["error"])
}
}
}
resolve()
});
});
}
exports.downloadBuildArtifacts = async (bsConfig, buildId, args, rawArgs, buildReportData = null) => {
return new Promise ( async (resolve, reject) => {
BUILD_ARTIFACTS_FAIL_COUNT = 0;
BUILD_ARTIFACTS_TOTAL_COUNT = 0;
let options = {
url: `${config.buildUrl}${buildId}/build_artifacts`,
auth: {
username: bsConfig.auth.username,
password: bsConfig.auth.access_key,
},
headers: {
'User-Agent': utils.getUserAgent(),
},
};
let message = null;
let messageType = null;
let errorCode = null;
let buildDetails = null;
request.get(options, async function (err, resp, body) {
if(err) {
logger.error(utils.formatRequest(err, resp, body));
utils.sendUsageReport(bsConfig, args, err, Constants.messageTypes.ERROR, 'api_failed_build_artifacts', buildReportData, rawArgs);
process.exitCode = Constants.ERROR_EXIT_CODE;
} else {
try {
buildDetails = JSON.parse(body);
if(resp.statusCode != 200) {
logger.error('Downloading the build artifacts failed.');
logger.error(`Error: Request failed with status code ${resp.statusCode}`)
logger.error(utils.formatRequest(err, resp, body));
utils.sendUsageReport(bsConfig, args, buildDetails, Constants.messageTypes.ERROR, 'api_failed_build_artifacts', buildReportData, rawArgs);
process.exitCode = Constants.ERROR_EXIT_CODE;
} else {
await createDirectories(buildId, buildDetails);
await parseAndDownloadArtifacts(buildId, buildDetails);
if (BUILD_ARTIFACTS_FAIL_COUNT > 0) {
messageType = Constants.messageTypes.ERROR;
message = Constants.userMessages.DOWNLOAD_BUILD_ARTIFACTS_FAILED.replace('<build-id>', buildId).replace('<machine-count>', BUILD_ARTIFACTS_FAIL_COUNT);
logger.error(message);
process.exitCode = Constants.ERROR_EXIT_CODE;
} else {
messageType = Constants.messageTypes.SUCCESS;
message = Constants.userMessages.DOWNLOAD_BUILD_ARTIFACTS_SUCCESS.replace('<build-id>', buildId).replace('<user-path>', process.cwd());
logger.info(message);
}
await sendUpdatesToBstack(bsConfig, buildId, args, options, rawArgs, buildReportData)
utils.sendUsageReport(bsConfig, args, message, messageType, null, buildReportData, rawArgs);
}
} catch (err) {
messageType = Constants.messageTypes.ERROR;
errorCode = 'api_failed_build_artifacts';
if (BUILD_ARTIFACTS_FAIL_COUNT > 0) {
messageType = Constants.messageTypes.ERROR;
message = Constants.userMessages.DOWNLOAD_BUILD_ARTIFACTS_FAILED.replace('<build-id>', buildId).replace('<machine-count>', BUILD_ARTIFACTS_FAIL_COUNT);
logger.error(message);
} else {
logger.error('Downloading the build artifacts failed.');
}
utils.sendUsageReport(bsConfig, args, err, messageType, errorCode, buildReportData, rawArgs);
logger.error(`Error: Request failed with status code ${resp.statusCode}`)
logger.error(utils.formatRequest(err, resp, body));
process.exitCode = Constants.ERROR_EXIT_CODE;
}
}
resolve();
});
});
};