-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathbuildArtifacts.js
More file actions
305 lines (282 loc) · 11 KB
/
buildArtifacts.js
File metadata and controls
305 lines (282 loc) · 11 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
'use strict';
const fs = require('fs'),
path = require('path');
const logger = require('./logger').winstonLogger,
utils = require("./utils"),
Constants = require("./constants"),
config = require("./config");
const { default: axios } = require('axios');
const { HttpsProxyAgent = require('https-proxy-agent') } = require('https-proxy-agent');
const FormData = require('form-data');
const decompress = require('decompress');
const unzipper = require("unzipper");
const { setAxiosProxy } = require('./helper');
let BUILD_ARTIFACTS_TOTAL_COUNT = 0;
let BUILD_ARTIFACTS_FAIL_COUNT = 0;
const parseAndDownloadArtifacts = async (buildId, data, bsConfig, args, rawArgs, buildReportData) => {
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) => {
if (error === Constants.userMessages.DOWNLOAD_BUILD_ARTIFACTS_NOT_FOUND) {
// Don't consider build artifact 404 error as a failure
let warningMessage = Constants.userMessages.DOWNLOAD_BUILD_ARTIFACTS_NOT_FOUND.replace('<session-id>', sessionId);
logger.warn(warningMessage);
utils.sendUsageReport(bsConfig, args, warningMessage, Constants.messageTypes.ERROR, 'build_artifacts_not_found', buildReportData, rawArgs);
} else {
BUILD_ARTIFACTS_FAIL_COUNT += 1;
const errorMsg = `Error downloading build artifacts for ${sessionId} with error: ${error}`;
logger.debug(errorMsg);
utils.sendUsageReport(bsConfig, args, errorMsg, Constants.messageTypes.ERROR, 'build_artifacts_parse_error', buildReportData, rawArgs);
}
// 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);
logger.debug(`Downloading build artifact for: ${filePath}`)
return new Promise(async (resolve, reject) => {
try {
const axiosConfig = {
responseType: 'stream',
validateStatus: status => (status >= 200 && status < 300) || status === 404
};
setAxiosProxy(axiosConfig);
const response = await axios.get(url, axiosConfig);
if(response.status != 200) {
if (response.status === 404) {
reject(Constants.userMessages.DOWNLOAD_BUILD_ARTIFACTS_NOT_FOUND);
}
const errorMsg = `Non 200 status code, got status code: ${response.status}`;
reject(errorMsg);
} else {
//ensure that the user can call `then()` only when the file has
//been downloaded entirely.
response.data.pipe(writer);
let error = null;
writer.on('error', err => {
error = err;
writer.close();
reject(err);
});
writer.on('close', async () => {
try {
if (!error) {
await unzipFile(filePath, fileName);
fs.unlinkSync(tmpFilePath);
}
} catch (error) {
reject(error);
}
resolve(true);
});
}
} catch (error) {
reject(error);
}
});
}
const unzipFile = async (filePath, fileName) => {
return new Promise( async (resolve, reject) => {
try {
await decompress(path.join(filePath, fileName), filePath);
resolve();
} catch (error) {
logger.debug(`Error unzipping with decompress, trying with unzipper. Stacktrace: ${error}.`);
try {
fs.createReadStream(path.join(filePath, fileName))
.pipe(unzipper.Extract({ path: filePath }))
.on("close", () => {
resolve();
})
.on("error", (err) => {
reject(err);
});
} catch (unzipperError) {
logger.debug(`Unzipper package error: ${unzipperError}`);
reject(Constants.userMessages.BUILD_ARTIFACTS_UNZIP_FAILURE);
}
}
});
}
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();
const axiosConfig = {
auth: {
username: options.auth.username,
password: options.auth.password
},
headers: options.headers
};
setAxiosProxy(axiosConfig);
let responseData = null;
return new Promise (async (resolve, reject) => {
try {
const response = await axios.post(options.url, data, axiosConfig);
try {
responseData = response.data;
} catch(e) {
responseData = {};
}
if (response.status != 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();
} catch (error) {
if(error.response) {
utils.sendUsageReport(bsConfig, args, error.response, Constants.messageTypes.ERROR, 'api_failed_build_artifacts_status_update', buildReportData, rawArgs);
logger.error(utils.formatRequest(error.response.statusText, error.response, error.response.data));
reject(errror.response.data.message);
}
}
});
}
exports.downloadBuildArtifacts = async (bsConfig, buildId, args, rawArgs, buildReportData = null, isTurboScaleSession = false) => {
return new Promise ( async (resolve, reject) => {
BUILD_ARTIFACTS_FAIL_COUNT = 0;
BUILD_ARTIFACTS_TOTAL_COUNT = 0;
let options = {
url: isTurboScaleSession
? `${config.turboScaleBuildsUrl}/${buildId}/build_artifacts`
: `${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;
options.config = {
auth: options.auth,
headers: options.headers
}
setAxiosProxy(options.config);
let response;
try {
response = await axios.get(options.url, options.config);
buildDetails = response.data;
await createDirectories(buildId, buildDetails);
await parseAndDownloadArtifacts(buildId, buildDetails, bsConfig, args, rawArgs, buildReportData);
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(err.response && err.response.status !== 200) {
logger.error('Downloading the build artifacts failed.');
logger.error(`Error: Request failed with status code ${err.response.status}`)
logger.error(utils.formatRequest(err.response.statusText, err.response, err.response.data));
utils.sendUsageReport(bsConfig, args, JSON.stringify(buildDetails), Constants.messageTypes.ERROR, 'api_failed_build_artifacts', buildReportData, rawArgs);
} else {
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.status}`)
logger.error(utils.formatRequest(err, resp, body));
}
process.exitCode = Constants.ERROR_EXIT_CODE;
}
resolve();
});
};