forked from NativeScript/nativescript-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathandroid-virtual-device-service.ts
521 lines (454 loc) · 14.4 KB
/
android-virtual-device-service.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
import * as net from "net";
import * as path from "path";
import { EOL } from "os";
import * as _ from "lodash";
import * as osenv from "osenv";
import {
AndroidVirtualDevice,
DeviceTypes,
NOT_RUNNING_EMULATOR_STATUS,
} from "../../constants";
import { cache } from "../../decorators";
import { settlePromises } from "../../helpers";
import { DeviceConnectionType } from "../../../constants";
import {
IStringDictionary,
IChildProcess,
IFileSystem,
IHostInfo,
ISysInfo,
ISpawnResult,
} from "../../declarations";
import { injector } from "../../yok";
export class AndroidVirtualDeviceService
implements Mobile.IAndroidVirtualDeviceService {
private androidHome: string;
private mapEmulatorIdToImageIdentifier: IStringDictionary = {};
constructor(
private $androidIniFileParser: Mobile.IAndroidIniFileParser,
private $childProcess: IChildProcess,
private $devicePlatformsConstants: Mobile.IDevicePlatformsConstants,
private $emulatorHelper: Mobile.IEmulatorHelper,
private $fs: IFileSystem,
private $hostInfo: IHostInfo,
private $sysInfo: ISysInfo,
private $logger: ILogger
) {
this.androidHome = process.env.ANDROID_HOME;
}
public async getEmulatorImages(
adbDevicesOutput: string[]
): Promise<Mobile.IEmulatorImagesOutput> {
const availableEmulatorsOutput = await this.getEmulatorImagesCore();
const avds = availableEmulatorsOutput.devices;
const runningEmulatorIds = await this.getRunningEmulatorIds(
adbDevicesOutput
);
const runningEmulators = await settlePromises(
_.map(runningEmulatorIds, (emulatorId) =>
this.getRunningEmulatorData(emulatorId, avds)
)
);
const devices = availableEmulatorsOutput.devices.map(
(emulator) =>
this.$emulatorHelper.getEmulatorByImageIdentifier(
emulator.imageIdentifier,
runningEmulators
) || emulator
);
return {
devices,
errors: availableEmulatorsOutput.errors,
};
}
public async getRunningEmulatorIds(
adbDevicesOutput: string[]
): Promise<string[]> {
const emulatorIds = _.reduce(
adbDevicesOutput,
(result: string[], device: string) => {
const rx = device.match(
AndroidVirtualDevice.RUNNING_AVD_EMULATOR_REGEX
);
if (rx && rx[1]) {
result.push(rx[1]);
}
return result;
},
[]
);
return emulatorIds;
}
public async getRunningEmulatorName(emulatorId: string): Promise<string> {
const imageIdentifier = await this.getRunningEmulatorImageIdentifier(
emulatorId
);
const iniFilePath = path.join(
this.pathToAvdHomeDir,
`${imageIdentifier}.ini`
);
const iniFileInfo = this.$androidIniFileParser.parseIniFile(iniFilePath);
let result = imageIdentifier;
if (iniFileInfo && iniFileInfo.path) {
const configIniFileInfo = this.$androidIniFileParser.parseIniFile(
path.join(iniFileInfo.path, AndroidVirtualDevice.CONFIG_INI_FILE_NAME)
);
result =
(configIniFileInfo && configIniFileInfo.displayName) || imageIdentifier;
}
return result;
}
public startEmulatorArgs(imageIdentifier: string): string[] {
return ["-avd", imageIdentifier];
}
@cache()
public get pathToEmulatorExecutable(): string {
const emulatorExecutableName = "emulator";
if (this.androidHome) {
// Check https://developer.android.com/studio/releases/sdk-tools.html (25.3.0)
// Since this version of SDK tools, the emulator is a separate package.
// However the emulator executable still exists in the "tools" dir.
const pathToEmulatorFromAndroidStudio = path.join(
this.androidHome,
emulatorExecutableName,
emulatorExecutableName
);
const realFilePath = this.$hostInfo.isWindows
? `${pathToEmulatorFromAndroidStudio}.exe`
: pathToEmulatorFromAndroidStudio;
if (this.$fs.exists(realFilePath)) {
return pathToEmulatorFromAndroidStudio;
}
return path.join(this.androidHome, "tools", emulatorExecutableName);
}
return emulatorExecutableName;
}
public getRunningEmulatorImageIdentifier(
emulatorId: string
): Promise<string> {
if (this.mapEmulatorIdToImageIdentifier[emulatorId]) {
return Promise.resolve(this.mapEmulatorIdToImageIdentifier[emulatorId]);
}
const match = emulatorId.match(/^emulator-(\d+)/);
const portNumber = match && match[1];
if (!portNumber) {
return Promise.resolve(null);
}
return new Promise<string>((resolveBase) => {
let isResolved = false;
let output: string = "";
const resolve = (result: string) => {
if (!isResolved) {
isResolved = true;
resolveBase(result);
}
};
const client = net.connect(portNumber, () => {
client.write(`avd name${EOL}`);
});
const timer = setTimeout(() => {
this.clearNetConnection(client, timer);
resolve(null);
}, 5000);
client.on("data", (data) => {
output += data.toString();
const imageIdentifier = this.getImageIdentifierFromClientOutput(output);
// old output should look like:
// Android Console: type 'help' for a list of commands
// OK
// <Name of image>
// OK
// new output should look like:
// Android Console: type 'help' for a list of commands
// OK
// a\u001b[K\u001b[Dav\u001b[K\u001b[D\u001b[Davd\u001b...
// <Name of image>
// OK
if (imageIdentifier && !isResolved) {
this.mapEmulatorIdToImageIdentifier[emulatorId] = imageIdentifier;
this.clearNetConnection(client, timer);
resolve(imageIdentifier);
}
});
client.on("error", (error) => {
this.$logger.trace(
`Error while checking emulator identifier for ${emulatorId}. More info: ${error}.`
);
resolve(null);
});
});
}
public detach(deviceInfo: Mobile.IDeviceInfo) {
if (this.mapEmulatorIdToImageIdentifier[deviceInfo.identifier]) {
delete this.mapEmulatorIdToImageIdentifier[deviceInfo.identifier];
}
}
private async getEmulatorImagesCore(): Promise<Mobile.IEmulatorImagesOutput> {
let result: ISpawnResult = null;
let devices: Mobile.IDeviceInfo[] = [];
let errors: string[] = [];
const canExecuteAvdManagerCommand = await this.canExecuteAvdManagerCommand();
if (!canExecuteAvdManagerCommand) {
errors = [
"Unable to execute avdmanager, ensure JAVA_HOME is set and points to correct directory",
];
}
if (canExecuteAvdManagerCommand) {
result = await this.$childProcess.trySpawnFromCloseEvent(
this.pathToAvdManagerExecutable,
["list", "avds"]
);
} else if (
this.pathToAndroidExecutable &&
this.$fs.exists(this.pathToAndroidExecutable)
) {
result = await this.$childProcess.trySpawnFromCloseEvent(
this.pathToAndroidExecutable,
["list", "avd"]
);
}
if (result && result.stdout) {
devices = this.parseListAvdsOutput(result.stdout);
errors = result && result.stderr ? [result.stderr] : [];
} else {
devices = this.listAvdsFromDirectory();
}
return { devices, errors };
}
@cache()
private async canExecuteAvdManagerCommand(): Promise<boolean> {
let canExecute = false;
if (
this.pathToAvdManagerExecutable &&
this.$fs.exists(this.pathToAvdManagerExecutable)
) {
if (process.env.JAVA_HOME) {
// In case JAVA_HOME is set, but it points to incorrect directory (i.e. there's no java in $JAVA_HOME/bin/java), avdmanager will fail
// no matter if you have correct java in PATH.
canExecute = !!(await this.$sysInfo.getJavaVersionFromJavaHome());
} else {
canExecute = !!(await this.$sysInfo.getJavaVersionFromPath());
}
}
return canExecute;
}
private async getRunningEmulatorData(
runningEmulatorId: string,
availableEmulators: Mobile.IDeviceInfo[]
): Promise<Mobile.IDeviceInfo> {
const imageIdentifier = await this.getRunningEmulatorImageIdentifier(
runningEmulatorId
);
const runningEmulator = this.$emulatorHelper.getEmulatorByImageIdentifier(
imageIdentifier,
availableEmulators
);
if (!runningEmulator) {
return null;
}
this.$emulatorHelper.setRunningAndroidEmulatorProperties(
runningEmulatorId,
runningEmulator
);
return runningEmulator;
}
@cache()
private get pathToAvdManagerExecutable(): string {
let avdManagerPath = null;
if (this.androidHome) {
avdManagerPath = path.join(
this.androidHome,
"tools",
"bin",
this.getExecutableName("avdmanager")
);
}
return avdManagerPath;
}
@cache()
private get pathToAndroidExecutable(): string {
let androidPath = null;
if (this.androidHome) {
androidPath = path.join(
this.androidHome,
"tools",
this.getExecutableName("android")
);
}
return androidPath;
}
@cache()
private get pathToAvdHomeDir(): string {
const searchPaths = [
process.env.ANDROID_AVD_HOME,
path.join(
osenv.home(),
AndroidVirtualDevice.ANDROID_DIR_NAME,
AndroidVirtualDevice.AVD_DIR_NAME
),
];
return searchPaths.find((p) => p && this.$fs.exists(p));
}
@cache()
private getConfigurationError(): string {
const pathToEmulatorExecutable = this.$hostInfo.isWindows
? `${this.pathToEmulatorExecutable}.exe`
: this.pathToEmulatorExecutable;
if (!this.$fs.exists(pathToEmulatorExecutable)) {
return "Unable to find the path to emulator executable and will not be able to start the emulator. Searched paths: [$ANDROID_HOME/tools/emulator, $ANDROID_HOME/emulator/emulator]";
}
return null;
}
private getExecutableName(executable: string): string {
if (this.$hostInfo.isWindows) {
return `${executable}.bat`;
}
return executable;
}
private listAvdsFromDirectory(): Mobile.IDeviceInfo[] {
let devices: Mobile.IDeviceInfo[] = [];
if (this.pathToAvdHomeDir && this.$fs.exists(this.pathToAvdHomeDir)) {
const entries = this.$fs.readDirectory(this.pathToAvdHomeDir);
devices = _.filter(
entries,
(e: string) => e.match(AndroidVirtualDevice.AVD_FILES_MASK) !== null
)
.map((e) => e.match(AndroidVirtualDevice.AVD_FILES_MASK)[1])
.map((avdName) => path.join(this.pathToAvdHomeDir, `${avdName}.avd`))
.map((avdPath) => this.getInfoFromAvd(avdPath))
.filter((avdInfo) => !!avdInfo)
.map((avdInfo) => this.convertAvdToDeviceInfo(avdInfo));
}
return devices;
}
private parseListAvdsOutput(output: string): Mobile.IDeviceInfo[] {
let devices: Mobile.IDeviceInfo[] = [];
const avdOutput = output.split(AndroidVirtualDevice.AVAILABLE_AVDS_MESSAGE);
const availableDevices = avdOutput && avdOutput[1] && avdOutput[1].trim();
if (availableDevices) {
// In some cases `avdmanager list avds` command prints:
// `The following Android Virtual Devices could not be loaded:
// Name: Pixel_2_XL_API_28
// Path: /Users/<username>/.android/avd/Pixel_2_XL_API_28.avd
// Error: Google pixel_2_xl no longer exists as a device`
// These devices sometimes are valid so try to parse them.
// Also these devices are printed at the end of the output and are separated with 2 new lines from the valid devices output.
const parts = availableDevices.split(/(?:\r?\n){2}/);
const items = [parts[0], parts[1]].filter((item) => !!item);
for (const item of items) {
const result = item
.split(AndroidVirtualDevice.AVD_LIST_DELIMITER)
.map((singleDeviceOutput) =>
this.getAvdManagerDeviceInfo(singleDeviceOutput.trim())
)
.map((avdManagerDeviceInfo) =>
this.getInfoFromAvd(avdManagerDeviceInfo.path)
)
.filter((avdInfo) => !!avdInfo)
.map((avdInfo) => this.convertAvdToDeviceInfo(avdInfo));
devices = devices.concat(result);
}
}
return devices;
}
private getAvdManagerDeviceInfo(
output: string
): Mobile.IAvdManagerDeviceInfo {
const avdManagerDeviceInfo: Mobile.IAvdManagerDeviceInfo = Object.create(
null
);
// Split by `\n`, not EOL as the avdmanager and android executables print results with `\n` only even on Windows
_.reduce(
output.split("\n"),
(result: Mobile.IAvdManagerDeviceInfo, row: string) => {
const [key, value] = row.split(": ").map((part) => part.trim());
switch (key) {
case "Name":
case "Device":
case "Path":
case "Target":
case "Skin":
case "Sdcard":
result[key.toLowerCase()] = value;
break;
}
return result;
},
avdManagerDeviceInfo || {}
);
return avdManagerDeviceInfo;
}
private getInfoFromAvd(avdFilePath: string): Mobile.IAvdInfo {
const configIniFilePath = path.join(
avdFilePath,
AndroidVirtualDevice.CONFIG_INI_FILE_NAME
);
const configIniFileInfo = this.$androidIniFileParser.parseIniFile(
configIniFilePath
);
const iniFilePath = this.getIniFilePath(configIniFileInfo, avdFilePath);
const iniFileInfo = this.$androidIniFileParser.parseIniFile(iniFilePath);
_.extend(configIniFileInfo, iniFileInfo);
if (configIniFileInfo && !configIniFileInfo.avdId) {
configIniFileInfo.avdId = path
.basename(avdFilePath)
.replace(AndroidVirtualDevice.AVD_FILE_EXTENSION, "");
}
return configIniFileInfo;
}
private convertAvdToDeviceInfo(avdInfo: Mobile.IAvdInfo): Mobile.IDeviceInfo {
return {
identifier: null,
imageIdentifier: avdInfo.avdId || avdInfo.displayName,
displayName: avdInfo.displayName || avdInfo.avdId || avdInfo.device,
model: avdInfo.device,
version: this.$emulatorHelper.mapAndroidApiLevelToVersion[avdInfo.target],
vendor: AndroidVirtualDevice.AVD_VENDOR_NAME,
status: NOT_RUNNING_EMULATOR_STATUS,
errorHelp: this.getConfigurationError(),
isTablet: false,
type: DeviceTypes.Emulator,
connectionTypes: [DeviceConnectionType.Local],
platform: this.$devicePlatformsConstants.Android,
};
}
private getImageIdentifierFromClientOutput(output: string): string {
// The lines should be trimmed after the split because the output has \r\n and when using split(EOL) on mac each line ends with \r.
const lines = _.map(output.split(EOL), (line) => line.trim());
const firstIndexOfOk = _.indexOf(lines, "OK");
if (firstIndexOfOk < 0) {
return null;
}
const secondIndexOfOk = _.indexOf(lines, "OK", firstIndexOfOk + 1);
if (secondIndexOfOk < 0) {
return null;
}
return lines[secondIndexOfOk - 1].trim();
}
private getIniFilePath(
configIniFileInfo: Mobile.IAvdInfo,
avdFilePath: string
): string {
let result = avdFilePath.replace(
AndroidVirtualDevice.AVD_FILE_EXTENSION,
AndroidVirtualDevice.INI_FILE_EXTENSION
);
if (configIniFileInfo && configIniFileInfo.avdId) {
result = path.join(
path.dirname(avdFilePath),
`${configIniFileInfo.avdId}${AndroidVirtualDevice.INI_FILE_EXTENSION}`
);
}
return result;
}
private clearNetConnection(client: net.Socket, timer: NodeJS.Timer) {
if (client) {
client.removeAllListeners();
client.destroy();
}
if (timer) {
clearTimeout(timer);
}
}
}
injector.register("androidVirtualDeviceService", AndroidVirtualDeviceService);