-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathbinaryControl.js
More file actions
277 lines (251 loc) · 8.57 KB
/
binaryControl.js
File metadata and controls
277 lines (251 loc) · 8.57 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
const tc = require('@actions/tool-cache');
const io = require('@actions/io');
const exec = require('@actions/exec');
const core = require('@actions/core');
const github = require('@actions/github');
const os = require('os');
const path = require('path');
const fs = require('fs');
const Utils = require('./utils');
const ArtifactsManager = require('./artifactsManager');
const constants = require('../config/constants');
const {
BINARY_LINKS,
LOCAL_BINARY_FOLDER,
PLATFORMS,
LOCAL_BINARY_NAME,
LOCAL_BINARY_ZIP,
LOCAL_LOG_FILE_PREFIX,
LOCAL_BINARY_TRIGGER,
RETRY_DELAY_BINARY,
BINARY_MAX_TRIES,
ALLOWED_INPUT_VALUES: {
LOCAL_TESTING,
},
ENV_VARS: {
BROWSERSTACK_LOCAL_LOGS_FILE,
},
} = constants;
/**
* BinaryControl handles the operations to be performed on the Local Binary.
* It takes care of logs generation and triggering the upload as well.
*/
class BinaryControl {
constructor(stateForBinary) {
this.platform = os.platform();
this.stateForBinary = stateForBinary;
this._decidePlatformAndBinary();
}
/**
* decides the binary link and the folder to store the binary based on the
* platform and the architecture
*/
_decidePlatformAndBinary() {
this.binaryFolder = path.resolve(
process.env.GITHUB_WORKSPACE,
'..', '..', '..',
'_work',
'binary',
LOCAL_BINARY_FOLDER,
this.platform,
);
switch (this.platform) {
case PLATFORMS.DARWIN:
this.binaryLink = BINARY_LINKS.DARWIN;
break;
case PLATFORMS.LINUX:
this.binaryLink = os.arch() === 'x32' ? BINARY_LINKS.LINUX_32 : BINARY_LINKS.LINUX_64;
break;
case PLATFORMS.WIN32:
this.binaryLink = BINARY_LINKS.WINDOWS;
break;
default:
throw Error(`Unsupported Platform: ${this.platform}. No BrowserStackLocal binary found.`);
}
}
/**
* Creates directory recursively for storing Local Binary & its logs.
*/
async _makeDirectory() {
await io.mkdirP(this.binaryFolder);
}
/**
* Generates logging file name and its path for Local Binary
*/
_generateLogFileMetadata() {
this.logFileName = process.env[BROWSERSTACK_LOCAL_LOGS_FILE] || `${LOCAL_LOG_FILE_PREFIX}_${github.context.job}_${Date.now()}.log`;
this.logFilePath = path.resolve(this.binaryFolder, this.logFileName);
core.exportVariable(BROWSERSTACK_LOCAL_LOGS_FILE, this.logFileName);
}
/**
* Generates the args to be provided for the Local Binary based on the operation, i.e.
* start/stop.
* These are generated based on the input state provided to the Binary Control.
*/
_generateArgsForBinary() {
const {
accessKey: key,
localArgs,
localIdentifier,
localLoggingLevel: verbose,
localTesting: binaryAction,
} = this.stateForBinary;
let argsString = `--key ${key} --ci-plugin GitHubAction `;
switch (binaryAction) {
case LOCAL_TESTING.START: {
if (localArgs) argsString += `${localArgs} `;
if (localIdentifier) argsString += `--local-identifier ${localIdentifier} `;
if (verbose) {
this._generateLogFileMetadata();
argsString += `--verbose ${verbose} --log-file ${this.logFilePath} `;
}
break;
}
case LOCAL_TESTING.STOP: {
if (localIdentifier) argsString += `--local-identifier ${localIdentifier} `;
break;
}
default: {
throw Error('Invalid Binary Action');
}
}
this.binaryArgs = argsString;
}
/**
* Triggers the Local Binary. It is used for starting/stopping.
* @param {String} operation start/stop operation
*/
async _triggerBinary(operation) {
let triggerOutput = '';
let triggerError = '';
await exec.exec(
`${LOCAL_BINARY_NAME} ${this.binaryArgs} --daemon ${operation}`,
[],
{
listeners: {
stdout: (data) => {
triggerOutput += data.toString();
},
stderr: (data) => {
triggerError += data.toString();
},
},
},
);
return {
output: triggerOutput,
error: triggerError,
};
}
async _removeAnyStaleBinary() {
const binaryZip = path.resolve(this.binaryFolder, LOCAL_BINARY_ZIP);
const previousLocalBinary = path.resolve(
this.binaryFolder,
`${LOCAL_BINARY_NAME}${this.platform === PLATFORMS.WIN32 ? '.exe' : ''}`,
);
await Promise.all([io.rmRF(binaryZip), io.rmRF(previousLocalBinary)]);
}
/**
* Downloads the Local Binary, extracts it and adds it in the PATH variable
*/
async downloadBinary() {
const cachedBinaryPath = Utils.checkToolInCache(LOCAL_BINARY_NAME, '1.0.0');
if (cachedBinaryPath) {
core.info('BrowserStackLocal binary already exists in cache. Using that instead of downloading again...');
// A cached tool is persisted across runs. But the PATH is reset back to its original
// state between each run. Thus, adding the cached tool path back to PATH again.
core.addPath(cachedBinaryPath);
return;
}
try {
await this._makeDirectory();
core.debug('BrowserStackLocal binary not found in cache. Deleting any stale/existing binary before downloading...');
await this._removeAnyStaleBinary();
core.info('Downloading BrowserStackLocal binary...');
const downloadPath = await tc.downloadTool(
this.binaryLink,
path.resolve(this.binaryFolder, LOCAL_BINARY_ZIP),
);
const extractedPath = await tc.extractZip(downloadPath, this.binaryFolder);
core.info(`BrowserStackLocal binary downloaded & extracted successfuly at: ${extractedPath}`);
const cachedPath = await tc.cacheDir(extractedPath, LOCAL_BINARY_NAME, '1.0.0');
core.addPath(cachedPath);
} catch (e) {
throw Error(`BrowserStackLocal binary could not be downloaded due to ${e.message}`);
}
}
/**
* Starts Local Binary using the args generated for this action
*/
async startBinary() {
this._generateArgsForBinary();
let { localIdentifier } = this.stateForBinary;
localIdentifier = localIdentifier ? `with local-identifier=${localIdentifier}` : '';
core.info(`Starting local tunnel ${localIdentifier} in daemon mode...`);
let triesAvailable = BINARY_MAX_TRIES;
while (triesAvailable--) {
try {
// eslint-disable-next-line no-await-in-loop
const { output, error } = await this._triggerBinary(LOCAL_TESTING.START);
if (!error) {
const outputParsed = JSON.parse(output);
if (outputParsed.state === LOCAL_BINARY_TRIGGER.START.CONNECTED) {
core.info(`Local tunnel status: ${JSON.stringify(outputParsed.message)}`);
return;
}
throw Error(JSON.stringify(outputParsed.message));
} else {
throw Error(JSON.stringify(error));
}
} catch (e) {
if (triesAvailable) {
core.info(`Error in starting local tunnel: ${e.message}. Trying again in 5 seconds...`);
// eslint-disable-next-line no-await-in-loop
await Utils.sleepFor(RETRY_DELAY_BINARY);
} else {
throw Error(`Local tunnel could not be started. Error message from binary: ${e.message}`);
}
}
}
}
/**
* Stops Local Binary using the args generated for this action
*/
async stopBinary() {
this._generateArgsForBinary();
try {
let { localIdentifier } = this.stateForBinary;
localIdentifier = localIdentifier ? `with local-identifier=${localIdentifier}` : '';
core.info(`Stopping local tunnel ${localIdentifier} in daemon mode...`);
const { output, error } = await this._triggerBinary(LOCAL_TESTING.STOP);
if (!error) {
const outputParsed = JSON.parse(output);
if (outputParsed.status === LOCAL_BINARY_TRIGGER.STOP.SUCCESS) {
core.info(`Local tunnel stopping status: ${outputParsed.message}`);
} else {
throw Error(JSON.stringify(outputParsed.message));
}
} else {
throw Error(JSON.stringify(error));
}
} catch (e) {
core.info(`[Warning] Error in stopping local tunnel: ${e.message}. Continuing the workflow without breaking...`);
}
}
/**
* Uploads BrowserStackLocal generated logs (if the file exists for the job)
*/
async uploadLogFilesIfAny() {
this._generateLogFileMetadata();
if (fs.existsSync(this.logFilePath)) {
await ArtifactsManager.uploadArtifacts(
this.logFileName,
[this.logFilePath],
this.binaryFolder,
);
await io.rmRF(this.logFilePath);
}
Utils.clearEnvironmentVariable(BROWSERSTACK_LOCAL_LOGS_FILE);
}
}
module.exports = BinaryControl;