-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathtunnel_binary.js
348 lines (333 loc) · 11.7 KB
/
tunnel_binary.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
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
var localTunnelConfig_ = require('./cfg/node-tunnel-config-v3-latest.json'),
logger,
https = require('https'),
urlParse = require('url'),
HttpsProxyAgent = require('https-proxy-agent'),
util = require('./util'),
AdmZip = require('adm-zip'),
fs = require('fs'),
path = require('path'),
os = require('os'),
executableName = 'LT';
/**
* TunnelBinary is a function based Class.
*/
function TunnelBinary(httpTunnelConfig, options) {
/**
* Try to find out binary based on platform arch.
*/
this.binaryVersion = 'v3';
// if (options['legacy']) {
// this.binaryVersion = 'v2';
// executableName = 'ltcomponent';
// }
this.httpTunnelConfig = httpTunnelConfig;
this.hostOS = process.platform;
this.bits = process.arch === 'x64' || process.arch === 'arm64' ? '64bit' : '32bit';
if (this.hostOS.match(/darwin|mac os/i)) {
this.platform = 'mac';
} else if (this.hostOS.match(/mswin|msys|mingw|cygwin|bccwin|wince|emc|win32/i)) {
this.platform = 'win';
this.windows = true;
} else if (this.hostOS.match(/freebsd/i)) {
this.platform = 'freebsd';
} else {
this.platform = 'linux';
}
this.httpPath = this.httpTunnelConfig.jsonResponse.binaryLinks[this.platform][this.binaryVersion][
this.bits
].httpPath;
this.binaryName = this.httpTunnelConfig.jsonResponse.binaryLinks[this.platform][
this.binaryVersion
][this.bits].binaryName;
this.httpHashContents = this.httpTunnelConfig.jsonResponse.binaryLinks[this.platform][
this.binaryVersion
][this.bits].hash;
this.localHashContents =
localTunnelConfig_.binaryLinks[this.platform][this.binaryVersion][this.bits].hash;
logger = this.httpTunnelConfig.logger;
/**
* retryBinaryDownload_ is used to download binary while getting Error duing
* download.
* @param {!Setting} conf is command line argumants passed during Initialize
* the Tunnel
* @param {Object} destParentDir is home Dir for Downloaded binary e.g.
* `.lambdatest`.
* @param {number} retries max tries for download.
* @param {number} binaryPath path of downloaded binary.
* @param {Function} fnCallback is a Callable function.
* @return {Method<download_>|Error} Return download_ method or Error of max
* count Exceeded.
*/
this.retryBinaryDownload_ = function(conf, destParentDir, retries, binaryPath, fnCallback) {
var self = this;
if (retries > 0) {
console.log('Retrying Download. Retries left', retries);
fs.stat(binaryPath, function(e) {
if (!e) {
fs.unlinkSync(binaryPath);
}
self.download_(conf, destParentDir, retries - 1, fnCallback);
});
} else {
console.error('Number of retries to download exceeded.');
}
};
/**
* download_ is used to download binary as zip File.
* @param {!Setting} conf is command line argumants passed during Initialize
* the Tunnel
* @param {Object} destParentDir is home Dir for Downloaded binary e.g.
* `.lambdatest`.
* @param {number} retries max tries for download.
* @param {Function} fnCallback is a Callable function.
* @return {string|Error} Return BinaryPath or Error while Extraction Failed.
*/
this.download_ = function(conf, destParentDir, retries, fnCallback) {
try {
console.log(`Downloading latest binary`);
// make Dir if not there.
if (!this.checkPath_(destParentDir)) {
fs.mkdirSync(destParentDir, { recursive: true });
}
// Generate binary path.
var binaryPath = path.join(destParentDir, this.binaryName);
var fileStream = fs.createWriteStream(binaryPath);
var self = this;
// Set Proxy If User passed this to in arguments.
var options = urlParse.parse(this.httpPath);
var proxyOpts = util.getProxyOpts_(conf);
if (Object.keys(proxyOpts).length) {
options.agent = new HttpsProxyAgent(proxyOpts);
}
// Get binary as zip File from https Server and put this to local folder.
// After fully download, unzip and change mode to excutable.
https
.get(options, function(response) {
response.pipe(fileStream);
response.on('error', function(e) {
logger.log(
conf['user'],
conf['key'],
{ filename: __filename },
conf,
'Got Error while unzip downloading binary' + e
);
self.retryBinaryDownload_(conf, destParentDir, retries, binaryPath, fnCallback);
});
fileStream.on('error', function(e) {
logger.log(
conf['user'],
conf['key'],
{ filename: __filename },
conf,
'Got Error while unzip downloading binary' + e
);
self.retryBinaryDownload_(conf, destParentDir, retries, binaryPath, fnCallback);
});
fileStream.on('close', function() {
if (self.checkPath_(binaryPath)) {
var unzipBinaryPath = path.join(destParentDir, executableName);
var destBinaryName = executableName;
if (self.windows) {
destBinaryName += '.exe';
}
var destBinaryPath = path.join(destParentDir, destBinaryName);
// Reading and Unzipping binary zip File
console.log(`Extracting binary`);
try {
var zip = new AdmZip(binaryPath);
zip.extractAllTo(destParentDir, false);
fs.chmod(destBinaryPath, '0755', function() {
return fnCallback(destBinaryPath)
});
} catch (e) {
console.log("Error log ------> ", e);
logger.log(
conf['user'],
conf['key'],
{ filename: __filename },
conf,
'Got Error while unzip downloading binary' + e
);
self.retryBinaryDownload_(conf, destParentDir, retries, binaryPath, fnCallback);
}
} else {
console.error('Got Error while downloading binary zip');
logger.log(
conf['user'],
conf['key'],
{ filename: __filename },
conf,
'Got Error while downloading binary zip'
);
self.retryBinaryDownload_(conf, destParentDir, retries, binaryPath, fnCallback);
}
});
})
.on('error', function(e) {
logger.log(
conf['user'],
conf['key'],
{ filename: __filename },
conf,
'Got Error while unzip downloading binary' + e
);
self.retryBinaryDownload_(conf, destParentDir, retries, binaryPath, fnCallback);
});
} catch (e) {
console.error('Got Error while downloading binary zip', e);
logger.log(conf['user'], conf['key'], { filename: __filename }, conf, {
message: 'Got Error while Extracting binary zip',
e: e
});
}
};
/**
* binaryPath_ is used to find Executable binary File Path.
* @param {!Setting} conf is command line argumants passed during Initialize
* the Tunnel
* @param {Function} fnCallback is a Callable function.
* @return {string|Error} Return BinaryPath or Error.
*/
this.binaryPath_ = function(conf, fnCallback) {
try {
var destParentDir = this.availableDirs_();
var destBinaryName = executableName;
if (this.windows) {
destBinaryName += '.exe';
}
var binaryPath = path.join(destParentDir, destBinaryName);
// Check whether executable binary File is exist or need to Downlaod.
if (this.checkPath_(binaryPath, fs.X_OK) && !process.env.LT_FORCE_DOWNLOAD) {
var that = this;
console.log(`Checking for updates`);
// Comparing with local hash to find out binary changes.
if (this.httpHashContents === this.localHashContents) {
console.log(`Binary already at latest version`);
return fnCallback(binaryPath);
} else {
console.log(`Binary is deprecated`);
try {
fs.writeFileSync(
__dirname + '/cfg/node-tunnel-config-v3-latest.json',
JSON.stringify(this.httpTunnelConfig.jsonResponse)
);
} catch (e) {
console.log(
'Permission denied! Please execute the command using sudo or provide the required read & write permissions to file : ',
__dirname + '/cfg/node-tunnel-config-v3-latest.json'
);
throw e;
}
localTunnelConfig_ = this.httpTunnelConfig.jsonResponse;
that.download_(conf, destParentDir, 5, fnCallback);
}
} else {
delete process.env.LT_FORCE_DOWNLOAD;
this.download_(conf, destParentDir, 5, fnCallback);
}
} catch (e) {
logger.log(conf['user'], conf['key'], { filename: __filename }, conf, e);
}
};
/**
* binaryPath_ is used for verifying exist of File.
* @param {!string} path is File path
* @param {!string} mode is File mode
* @return {boolean}
*/
this.checkPath_ = function(path, mode) {
try {
mode = mode || fs.R_OK | fs.W_OK;
fs.accessSync(path, mode);
return true;
} catch (e) {
// console.log('Error checkPath ----->', e);
if (typeof fs.accessSync !== 'undefined') {
return false;
}
try {
fs.statSync(path);
return true;
} catch (e) {
return false;
}
}
};
/**
* availableDirs_ Check whether ordered Dir is priviledged for creation.
* @return {string} Dir that has Required priviledge for creation of Dir.
*/
this.availableDirs_ = function() {
var orderedPathLength = this.orderedPaths.length;
var _path,
iCounter = 0;
for (var i = 0; i < orderedPathLength; i++) {
iCounter++;
_path = this.orderedPaths[i];
if (this.makePath_(_path)) {
break;
}
}
if (iCounter < orderedPathLength) {
return _path;
}
throw Error('Error trying to download LambdaTest Tunnel binary');
};
/**
* makePath_ Make Dir if not there.
* @return {boolean} Dir is Created or not.
*/
this.makePath_ = function(path) {
try {
if (!this.checkPath_(path)) {
fs.mkdirSync(path, { recursive: true });
}
return true;
} catch (e) {
return false;
}
};
/**
* homeDir_ Find out home Dir of Platform.
* @return {string|null} home Dir or null.
*/
this.homeDir_ = function() {
if (typeof process.cwd === 'function') return process.cwd();
if (typeof os.homedir === 'function') return os.homedir();
var env = process.env;
var home = env.HOME;
var user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME;
if (process.platform === 'win32') {
return env.USERPROFILE || env.HOMEDRIVE + env.HOMEPATH || home || null;
}
if (process.platform === 'darwin') {
return home || (user ? '/Users/' + user : null);
}
if (process.platform === 'linux') {
return home || (process.getuid() === 0 ? '/root' : user ? '/home/' + user : null);
}
return home || null;
};
/**
* rmDir remove directory and sub-directory.
*/
this.rmDir = function(dir) {
var self = arguments.callee;
if (fs.existsSync(dir)) {
fs.readdirSync(dir).forEach(function(file) {
var C = dir + '/' + file;
if (fs.statSync(C).isDirectory()) self(C);
else fs.unlinkSync(C);
});
fs.rmdirSync(dir);
}
};
this.orderedPaths = [
path.join(this.homeDir_(), '.lambdatest', this.binaryVersion),
path.join(process.cwd(), this.binaryVersion),
path.join(os.tmpdir(), this.binaryVersion)
];
}
module.exports = TunnelBinary;