-
-
Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathplugin.ts
More file actions
823 lines (757 loc) · 30.7 KB
/
plugin.ts
File metadata and controls
823 lines (757 loc) · 30.7 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
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
/* eslint-disable no-prototype-builtins */
import BasePlugin from '@appium/base-plugin';
import AsyncLock from 'async-lock';
import axios, { AxiosError } from 'axios';
import { HttpProxyAgent } from 'http-proxy-agent';
import { HttpsProxyAgent } from 'https-proxy-agent';
import 'reflect-metadata';
import { Container } from 'typedi';
import { createRouter } from './app';
import commands from './commands/index';
import {
getDevice,
unblockDevice,
unblockDeviceMatchingFilter,
updatedAllocatedDevice,
} from './data-service/device-service';
import {
addNewPendingSession,
removePendingSession,
} from './data-service/pending-sessions-service';
import { AndroidDeviceManager, DeviceFarmManager, IOSDeviceManager } from './device-managers';
import ChromeDriverManager from './device-managers/ChromeDriverManager';
import {
allocateDeviceForSession,
initializeStorage,
removeStaleDevices,
setupCronCheckStaleDevices,
setupCronCleanPendingSessions,
setupCronReleaseBlockedDevices,
setupCronUpdateDeviceList,
updateDeviceList,
} from './device-utils';
import { hasCloudArgument, isDeviceFarmRunning, nodeUrl, stripAppiumPrefixes } from './helpers';
import { Dashboard } from './dashboard';
import { IDevice } from './interfaces/IDevice';
import {
CreateSessionResponseInternal,
ISessionCapability,
W3CNewSessionResponse,
W3CNewSessionResponseError,
} from './interfaces/ISessionCapability';
import log from './logger';
import { addProxyHandler, registerProxyMiddlware } from './proxy/wd-command-proxy';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { PluginConfig, ServerArgs } from '@appium/types';
import http from 'http';
import * as https from 'https';
import ip from 'ip';
import _ from 'lodash';
import { DeviceFarmApiClient } from './api-client';
import { getDeviceFarmCapabilities } from './CapabilityManager';
import { config, config as pluginConfig } from './config';
import { ATDRepository } from './data-service/db';
import { NodeService } from './data-service/node-service';
import { addCLIArgs } from './data-service/pluginArgs';
import debugLog from './debugLog';
import NodeDevices from './device-managers/NodeDevices';
import Cloud from './enums/Cloud';
import SessionType from './enums/SessionType';
import { AfterSessionDeletedEvent } from './events/after-session-deleted-event';
import { BeforeSessionCreatedEvent } from './events/before-session-create-event';
import { SessionCreatedEvent } from './events/session-created-event';
import { UnexpectedServerShutdownEvent } from './events/unexpected-server-shutdown-event';
import { getFreePort, releasePorts } from './helpers';
import { IDeviceFilterOptions } from './interfaces/IDeviceFilterOptions';
import { DefaultPluginArgs, IPluginArgs } from './interfaces/IPluginArgs';
import { DEVICE_CONNECTIONS_FACTORY } from './iProxy';
import EventBus from './notifier/event-bus';
import {
generateTokenForNode,
getUserFromCapabilities,
sanitizeSessionCapabilities,
} from './utils/auth';
import { enhancedADBManager } from './utils/enhanced-adb-manager';
import { NodeHealthMonitor } from './utils/node-heath-monitor';
const commandsQueueGuard = new AsyncLock();
const NODE_HEALTH_MONITOR_INTERVAL = 1000 * 30; // 30 seconds
const DEVICE_MANAGER_LOCK_NAME = 'DeviceManager';
let platform: any;
let androidDeviceType: any;
let iosDeviceType: any;
let hasEmulators: any;
let proxy: any;
let dashboard: Dashboard;
class DevicePlugin extends BasePlugin {
static nodeBasePath = '';
private pluginArgs: IPluginArgs = Object.assign({}, DefaultPluginArgs);
public static NODE_ID: string;
public static IS_HUB = false;
private static httpServer: any;
public static adbInstance: any;
public static serverUrl: string;
public static serverArgs: Record<string, any>;
public static apiClient: DeviceFarmApiClient;
constructor(pluginName: string, cliArgs: any) {
super(pluginName, cliArgs);
/* To fix cannot read properties `constructor` of undefined error due to changes in appium log */
this.updateLogPrefix = null;
// here, CLI Args are already pluginArgs. Different case for updateServer
log.debug(`📱 Plugin Args: ${JSON.stringify(cliArgs)}`);
// plugin args will assign undefined value as well for bindHostOrIp
this.pluginArgs = Object.assign({}, DefaultPluginArgs, cliArgs as unknown as IPluginArgs);
// not pretty but will do for now
if (this.pluginArgs.bindHostOrIp === undefined) {
this.pluginArgs.bindHostOrIp = ip.address('ipv4');
}
}
async onUnexpectedShutdown(driver: any, cause: any) {
const deviceFilter = {
session_id: driver.sessionId ? driver.sessionId : undefined,
udid: driver.caps && driver.caps.udid ? driver.caps.udid : undefined,
} as unknown as IDeviceFilterOptions;
if (this.pluginArgs.hub !== undefined) {
// send unblock request to hub. Should we unblock the whole devices from this node?
await new NodeDevices(this.pluginArgs.hub).unblockDevice(deviceFilter);
} else {
await unblockDeviceMatchingFilter(deviceFilter);
}
log.info(
`Unblocking device mapped with filter ${JSON.stringify(
deviceFilter,
)} onUnexpectedShutdown from server`,
);
await EventBus.fire(new UnexpectedServerShutdownEvent({ driver }));
}
public static async updateServer(
expressApp: any,
httpServer: any,
cliArgs: ServerArgs,
): Promise<void> {
config.goIOSTunnelInfoPort = await getFreePort();
DevicePlugin.httpServer = httpServer;
log.debug(`📱 Update server with CLI Args: ${JSON.stringify(cliArgs)}`);
DevicePlugin.serverArgs = cliArgs;
const pluginConfigs = cliArgs.plugin as PluginConfig;
let pluginArgs: IPluginArgs;
if (pluginConfigs['device-farm'] !== undefined) {
pluginArgs = Object.assign(
{},
DefaultPluginArgs,
pluginConfigs['device-farm'] as unknown as IPluginArgs,
);
} else {
pluginArgs = Object.assign({}, DefaultPluginArgs);
}
if (
(pluginArgs.platform.toLowerCase() === 'android' ||
pluginArgs.platform.toLowerCase() == 'both') &&
!pluginArgs.cloud
) {
DevicePlugin.adbInstance = await enhancedADBManager.initializeLocalADB({
adbExecTimeout: 60000,
});
}
dashboard = new Dashboard(EventBus, cliArgs, pluginArgs);
const hubArgument = pluginArgs.hub;
DevicePlugin.NODE_ID = config.serverMetadata.id;
DevicePlugin.IS_HUB = !pluginArgs.hub;
log.info('Cli Args: ' + JSON.stringify(cliArgs));
DevicePlugin.nodeBasePath = cliArgs.basePath;
if (pluginArgs.bindHostOrIp === undefined) {
pluginArgs.bindHostOrIp = ip.address();
}
log.debug(`📱 Update server with Plugin Args: ${JSON.stringify(pluginArgs)}`);
await initializeStorage();
(await ATDRepository.DeviceModel).removeDataOnly();
platform = pluginArgs.platform;
androidDeviceType = pluginArgs.androidDeviceType;
iosDeviceType = pluginArgs.iosDeviceType;
if (pluginArgs.proxy !== undefined) {
log.info(`Adding proxy for axios: ${JSON.stringify(pluginArgs.proxy)}`);
proxy = pluginArgs.proxy;
} else {
log.info('proxy is not required for axios');
}
hasEmulators = pluginArgs.emulators && pluginArgs.emulators.length > 0;
expressApp.use('/device-farm', createRouter(pluginArgs));
registerProxyMiddlware(expressApp, cliArgs, [
dashboard.requestInterceptingMiddleware.bind(dashboard),
]);
dashboard.addRoutes(expressApp);
// Sanitize the status of existing sessions on startup
const { prisma: prismaClient } = await import('./prisma');
await prismaClient.session.updateMany({
data: {
hasLiveVideo: false,
status: 'unmarked',
},
where: {
OR: [{ hasLiveVideo: true }, { status: 'running' }],
},
});
if (
hasEmulators &&
(pluginArgs.platform.toLowerCase() === 'android' ||
pluginArgs.platform.toLowerCase() === 'both')
) {
log.info('Emulators will be booted!!');
const adb = await enhancedADBManager.getLocalADB();
const array = pluginArgs.emulators || [];
const promiseArray = array.map(async (arr: any) => {
await Promise.all([await adb.launchAVD(arr.avdName, arr)]);
});
await Promise.all(promiseArray);
}
const chromeDriverManager =
pluginArgs.skipChromeDownload === false ? await ChromeDriverManager.getInstance() : undefined;
iosDeviceType = DevicePlugin.setIncludeSimulatorState(pluginArgs, iosDeviceType);
const deviceTypes = { androidDeviceType, iosDeviceType };
const deviceManager = new DeviceFarmManager(
platform,
deviceTypes,
cliArgs.port,
pluginArgs,
DevicePlugin.NODE_ID,
);
Container.set(DeviceFarmManager, deviceManager);
if (chromeDriverManager) Container.set(ChromeDriverManager, chromeDriverManager);
await addCLIArgs(cliArgs);
if (hubArgument !== undefined) {
log.info(`📣📣📣 I'm a node and my hub is ${hubArgument}`);
DevicePlugin.apiClient = new DeviceFarmApiClient(
pluginArgs.accessKey!,
pluginArgs.token!,
hubArgument,
);
const isHubRunning = await isDeviceFarmRunning(hubArgument);
if (!isHubRunning) {
throw new Error(
`🛜 Unable to connect with hub in ${hubArgument}. Make the appium server is up and running.`,
);
}
// Only authenticate if authentication is enabled
if (pluginArgs.enableAuthentication) {
try {
await DevicePlugin.apiClient.authenticate();
} catch (err) {
throw new Error(
'🔐 Authentication error. Invalid accessKey or token. Kindly pass accesskey and token using --plugin-device-farm-access-key and --plugin-device-farm-token arguments',
);
}
}
// hub may have been restarted, so let's send device list regularly
await setupCronUpdateDeviceList(
pluginArgs.bindHostOrIp,
hubArgument,
pluginArgs.sendNodeDevicesToHubIntervalMs,
pluginArgs,
cliArgs,
);
} else {
DevicePlugin.serverUrl = `http://${pluginArgs.bindHostOrIp}:${cliArgs.port}`;
await NodeService.register(
true,
pluginArgs.nodeName || '',
DevicePlugin.serverUrl,
DevicePlugin.NODE_ID,
);
await NodeHealthMonitor.getInstance().start(NODE_HEALTH_MONITOR_INTERVAL);
await updateDeviceList(pluginArgs.bindHostOrIp);
log.info(`📣📣📣 I'm a hub and I'm listening on ${pluginArgs.bindHostOrIp}:${cliArgs.port}`);
}
if (pluginArgs.cloud == undefined) {
// runAndroidAdbServer();
// setTimeout(() => {
// console.log('Script completed with sleep.');
// }, 5000);
// check for stale nodes
await setupCronCheckStaleDevices(
pluginArgs.checkStaleDevicesIntervalMs,
pluginArgs.bindHostOrIp,
);
// and release blocked devices
await setupCronReleaseBlockedDevices(
pluginArgs.checkBlockedDevicesIntervalMs,
pluginArgs.newCommandTimeoutSec,
);
// and clean up pending sessions
await setupCronCleanPendingSessions(
pluginArgs.checkBlockedDevicesIntervalMs,
pluginArgs.deviceAvailabilityTimeoutMs + 10000,
);
// unblock all devices on node/hub restart
await unblockDeviceMatchingFilter({});
// remove stale devices
await removeStaleDevices(pluginArgs.bindHostOrIp);
} else {
log.info('📣📣📣 Cloud runner sessions dont require constant device checks');
}
log.info(
`📣📣📣 Device Farm Plugin will be served at 🔗 http://${pluginArgs.bindHostOrIp}:${cliArgs.port}/device-farm with id ${DevicePlugin.NODE_ID}`,
);
}
private static setIncludeSimulatorState(pluginArgs: IPluginArgs, deviceTypes: string) {
if (hasCloudArgument(pluginArgs)) {
deviceTypes = 'real';
log.info('ℹ️ Skipping Simulators as per the configuration ℹ️');
}
return deviceTypes;
}
getLockName(caps: Record<string, any>) {
const keys = ['platformName', 'appium:platformVersion', 'appium:udids'];
return keys
.filter((key) => !!caps[key])
.reduce((acc, key) => acc + caps[key], DEVICE_MANAGER_LOCK_NAME)
.toLowerCase()
.split('')
.sort()
.join('');
}
async createSession(
next: () => any,
driver: any,
jwpDesCaps: any,
jwpReqCaps: any,
caps: ISessionCapability,
) {
log.debug(`📱 pluginArgs: ${JSON.stringify(this.pluginArgs)}`);
log.debug(`Receiving session request at host: ${this.pluginArgs.bindHostOrIp}`);
const {
alwaysMatch: requiredCaps = {}, // If 'requiredCaps' is undefined, set it to an empty JSON object (#2.1)
firstMatch: allFirstMatchCaps = [{}], // If 'firstMatch' is undefined set it to a singleton list with one empty object (#3.1)
} = caps;
const pendingSessionId = requiredCaps['appium:requestId'];
delete requiredCaps['appium:requestId'];
log.debug(`📱 Creating temporary session capability_id: ${pendingSessionId}`);
stripAppiumPrefixes(requiredCaps);
stripAppiumPrefixes(allFirstMatchCaps);
const mergedCapabilites = Object.assign({}, caps.firstMatch[0], caps.alwaysMatch);
log.info(`Merged Capabilities: ${JSON.stringify(mergedCapabilites, null, 2)}`);
await addNewPendingSession({
...Object.assign({}, caps.firstMatch[0], caps.alwaysMatch),
capability_id: pendingSessionId,
// mark the insertion date
createdAt: new Date().getTime(),
});
/**
* Wait untill a free device is available for the given capabilities
*/
console.log(`Acquiring Lock with name ${this.getLockName(mergedCapabilites)}`);
const device = await commandsQueueGuard.acquire(
this.getLockName(mergedCapabilites),
async (): Promise<IDevice> => {
//await refreshDeviceList();
try {
return await allocateDeviceForSession(
pendingSessionId,
caps,
this.pluginArgs.deviceAvailabilityTimeoutMs,
this.pluginArgs.deviceAvailabilityQueryIntervalMs,
this.pluginArgs,
);
} catch (err) {
await removePendingSession(pendingSessionId);
throw err;
}
},
);
let session: CreateSessionResponseInternal | W3CNewSessionResponseError | Error;
const isRemoteOrCloudSession = !device.nodeId || device.nodeId !== DevicePlugin.NODE_ID;
log.debug(
`device.host: ${device.host} and pluginArgs.bindHostOrIp: ${this.pluginArgs.bindHostOrIp}`,
);
// if device is not on the same node, forward the session request. Unless hub is not defined then create session on the same node
if (isRemoteOrCloudSession) {
log.debug(`📱${pendingSessionId} --- Forwarding session request to ${device.host}`);
caps['pendingSessionId'] = pendingSessionId;
session = await this.forwardSessionRequest(device, caps, mergedCapabilites);
debugLog(`📱${pendingSessionId} --- Forwarded session response: ${JSON.stringify(session)}`);
} else {
log.debug('📱 Creating session on the same node');
const sessionType = device.cloud
? SessionType.CLOUD
: device.nodeId !== DevicePlugin.NODE_ID
? SessionType.REMOTE
: SessionType.LOCAL;
await EventBus.fire(
new BeforeSessionCreatedEvent({ device, sessionType: sessionType, caps }),
);
session = await next();
if (
device.platform === 'ios' &&
device.realDevice &&
device.nodeId === DevicePlugin.NODE_ID
) {
log.info(`📱 Forwarding ios port to real device ${device.udid} for MJPEG streaming`);
try {
await DEVICE_CONNECTIONS_FACTORY.requestConnection(device.udid, device.mjpegServerPort, {
usePortForwarding: true,
devicePort: device.mjpegServerPort,
});
} catch (err) {
/* Not required for now as the port forwarding is handled by xcuitest river itself */
log.warn(`Error while forwarding ios port to real device ${device.udid}. Error: ${err}`);
}
}
debugLog(`📱 Session response: ${JSON.stringify(session)}`);
}
// non-forwarded session can also be an error
log.debug(`📱 ${pendingSessionId} Session response: `, JSON.stringify(session));
log.debug(`📱 Removing pending session with capability_id: ${pendingSessionId}`);
await removePendingSession(pendingSessionId);
// Do we have valid session response?
if (this.isCreateSessionResponseInternal(session)) {
log.debug(`${pendingSessionId} 📱 Session response is CreateSessionResponseInternal`);
sanitizeSessionCapabilities(session.value[1]);
const sessionId = (session as CreateSessionResponseInternal).value[0];
const sessionResponse = (session as CreateSessionResponseInternal).value[1];
const deviceFarmCapabilities = getDeviceFarmCapabilities(caps);
log.info(
`📱 ${pendingSessionId} ----- Device UDID ${device.udid} blocked for session ${sessionId}`,
);
const user =
DevicePlugin.IS_HUB && this.pluginArgs.enableAuthentication
? await getUserFromCapabilities(mergedCapabilites)
: null;
await updatedAllocatedDevice(device, {
busy: true,
session_id: sessionId,
lastCmdExecutedAt: new Date().getTime(),
sessionStartTime: new Date().getTime(),
sessionResponse: sessionResponse,
mjpegServerPort: sessionResponse.mjpegServerPort,
activeUser: user
? {
id: user.id,
firstname: user.firstname,
lastname: user.lastname,
}
: undefined,
deviceFarmCapabilities,
});
if (isRemoteOrCloudSession) {
addProxyHandler(sessionId, device.host);
}
const isManualSession = mergedCapabilites['df:skipReport'];
if (!isManualSession) {
await EventBus.fire(
new SessionCreatedEvent({
sessionId,
device,
sessionResponse,
deviceFarmCapabilities,
pluginNodeId: DevicePlugin.NODE_ID,
driver: driver,
adb: DevicePlugin.adbInstance,
}),
);
} else {
log.info('Skipping dashboard report');
}
log.info(
`${pendingSessionId} 📱 Updating Device ${device.udid} with session ID ${sessionId}`,
);
if (device.platform.toLowerCase() === 'ios' && !isRemoteOrCloudSession) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const sessionDriver = driver.sessions[sessionId].proxydriver || driver.sessions[sessionId];
const wda = sessionDriver.wda.jwproxy;
const proxiedInfo = {
proxyUrl: `${wda.scheme}://${wda.server}:${wda.port}`,
proxySessionId: wda.sessionId,
sessionId: sessionId,
};
await updatedAllocatedDevice(device, proxiedInfo);
if (this.pluginArgs.hub !== undefined) {
const node = new NodeDevices(this.pluginArgs.hub);
await node.updateDeviceInfoToHub(device.udid, proxiedInfo);
}
}
} else {
await unblockDevice(device.udid, device.host);
log.info(
`${pendingSessionId} 📱 Device UDID ${device.udid} unblocked. Reason: Failed to create session`,
);
this.throwProperError(session, device.host);
}
debugLog(`${pendingSessionId} 📱 Returning session: ${JSON.stringify(session)}`);
return session;
}
throwProperError(session: any, host: string) {
debugLog(`Inside throwProperError: ${JSON.stringify(session)}`);
if (session instanceof Error) {
throw session;
} else if (session.hasOwnProperty('error')) {
const errorMessage = (session as W3CNewSessionResponseError).error;
if (errorMessage) {
throw new Error(errorMessage);
} else {
throw new Error(
`Unknown error while creating session: ${JSON.stringify(
session,
)}. \nBetter look at appium log on the node: ${host}`,
);
}
} else {
throw new Error(
`Unknown error while creating session: ${JSON.stringify(
session,
)}. \nBetter look at appium log on the node: ${host}`,
);
}
}
// type guard for CreateSessionResponseInternal
private isCreateSessionResponseInternal(
something: any,
): something is CreateSessionResponseInternal {
return (
something.hasOwnProperty('value') &&
something.value.length === 3 &&
something.value[0] &&
something.value[1] &&
something.value[2]
);
}
private async forwardSessionRequest(
device: IDevice,
caps: ISessionCapability,
mergedCapabilites: Record<string, string>,
): Promise<CreateSessionResponseInternal | Error> {
const remoteUrl = `${nodeUrl(device, DevicePlugin.nodeBasePath)}/session`;
const capabilitiesToCreateSession = { capabilities: caps };
if (device.hasOwnProperty('cloud') && device.cloud.toLowerCase() === Cloud.LAMBDATEST) {
if (
capabilitiesToCreateSession.capabilities.alwaysMatch &&
Object.keys(capabilitiesToCreateSession.capabilities.alwaysMatch).length == 0
) {
delete capabilitiesToCreateSession.capabilities.alwaysMatch;
}
if (
capabilitiesToCreateSession.capabilities.firstMatch &&
_.isArray(capabilitiesToCreateSession.capabilities.firstMatch) &&
(!capabilitiesToCreateSession.capabilities.firstMatch.length ||
capabilitiesToCreateSession.capabilities.firstMatch.every(
(m) => Object.keys(m).length == 0,
))
) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
delete capabilitiesToCreateSession.capabilities.firstMatch;
}
} else {
let jwt = '';
if (this.pluginArgs.enableAuthentication) {
const user = await getUserFromCapabilities(mergedCapabilites);
if (user) {
jwt = await generateTokenForNode(device.nodeId!, user.id);
}
}
if (capabilitiesToCreateSession.capabilities.alwaysMatch) {
capabilitiesToCreateSession.capabilities.alwaysMatch['df:udid'] = device.udid;
if (jwt) {
capabilitiesToCreateSession.capabilities.alwaysMatch['df:jwt'] = jwt;
}
} else {
capabilitiesToCreateSession.capabilities.firstMatch[0]['df:udid'] = device.udid;
if (jwt) {
capabilitiesToCreateSession.capabilities.firstMatch[0]['df:jwt'] = jwt;
}
}
}
log.info(
`Creating session with desiredCapabilities: "${JSON.stringify(capabilitiesToCreateSession)}"`,
);
const config: any = {
method: 'post',
url: remoteUrl,
timeout: this.pluginArgs.remoteConnectionTimeout,
httpAgent: new http.Agent({
keepAlive: true,
keepAliveMsecs: 120000,
}),
httpsAgent: new https.Agent({
rejectUnauthorized: false,
keepAlive: true,
keepAliveMsecs: 120000,
}),
headers: {
'Content-Type': 'application/json',
},
data: capabilitiesToCreateSession,
};
//log.info(`Add proxy to axios config only if it is set: ${JSON.stringify(proxy)}`);
if (proxy != undefined) {
log.info(`Added proxy to axios config: ${JSON.stringify(proxy)}`);
config.httpsAgent = new HttpsProxyAgent(proxy);
config.httpAgent = new HttpProxyAgent(proxy);
config.proxy = false;
}
log.info(`With axios config: "${JSON.stringify(config)}"`);
const createdSession: W3CNewSessionResponse | Error = await this.invokeSessionRequest(config);
debugLog(`📱 Session Creation response: ${JSON.stringify(createdSession)}`);
if (createdSession instanceof Error) {
return createdSession;
} else {
return {
protocol: 'W3C',
value: [createdSession.value.sessionId, createdSession.value.capabilities, 'W3C'],
};
}
}
async invokeSessionRequest(config: any): Promise<W3CNewSessionResponse | Error> {
let sessionDetails: W3CNewSessionResponse | null = null;
let errorMessage: string | null = null;
try {
const response = await axios(config);
log.debug('remote node response', JSON.stringify(response.data));
// Appium endpoint returns session details w3c format: https://github.com/jlipps/simple-wd-spec?tab=readme-ov-file#new-session
sessionDetails = response.data as unknown as W3CNewSessionResponse;
// check if we have error in response by checking sessionDetails.value type
if ('error' in sessionDetails.value) {
log.error(`Error while creating session: ${sessionDetails.value.error}`);
errorMessage = sessionDetails.value.error as string;
}
} catch (error: AxiosError<any> | any) {
log.debug(`Received error from remote node: ${JSON.stringify(error)}`);
if (error instanceof AxiosError) {
errorMessage = JSON.stringify(error.response?.data);
} else {
errorMessage = error;
}
}
// Actually errorMessage will be empty when axios is getting peer connection error/disconnected.
// So, let's invert the situation and return error when sessionDetails is null
if (_.isNil(sessionDetails)) {
log.error(`Error while creating session: ${errorMessage}`);
if (_.isNil(errorMessage)) {
errorMessage = 'Unknown error while creating session';
}
return new Error(errorMessage);
} else {
log.debug(
`📱 Session received with details: ${JSON.stringify(
!sessionDetails ? {} : sessionDetails,
)}`,
);
if (this.isW3CNewSessionResponse(sessionDetails)) {
return sessionDetails as W3CNewSessionResponse;
} else {
return new Error(`Unknown error while creating session: ${JSON.stringify(sessionDetails)}`);
}
}
}
private isW3CNewSessionResponse(something: any): something is W3CNewSessionResponse {
return (
something.hasOwnProperty('value') &&
something.value.hasOwnProperty('sessionId') &&
something.value.hasOwnProperty('capabilities')
);
}
async deleteSession(next: () => any, driver: any, sessionId: any) {
const device = await getDevice({
session_id: sessionId,
});
// Collect all ports used by the device and release them
const portsToRelease: (number | undefined | null)[] = [];
// Ports from device object
if (device) {
// iOS ports
if (device.wdaLocalPort) portsToRelease.push(device.wdaLocalPort);
if (device.mjpegServerPort) portsToRelease.push(device.mjpegServerPort);
if (device.goIOSAgentPort) portsToRelease.push(device.goIOSAgentPort);
// Android ports (stored on device if available)
if (device.systemPort) portsToRelease.push(device.systemPort);
if (device.adbPort) portsToRelease.push(device.adbPort);
// Ports from sessionResponse capabilities (Android and iOS)
// sessionResponse contains the capabilities returned from Appium
if (device.sessionResponse) {
const sessionResponse = device.sessionResponse;
// Check for ports with appium: prefix
const capabilities = sessionResponse.capabilities || sessionResponse;
// Android ports
const systemPort = capabilities['appium:systemPort'] || capabilities.systemPort;
const chromeDriverPort =
capabilities['appium:chromeDriverPort'] || capabilities.chromeDriverPort;
const flutterSystemPort =
capabilities['appium:flutterSystemPort'] || capabilities.flutterSystemPort;
// iOS ports
const wdaLocalPort = capabilities['appium:wdaLocalPort'] || capabilities.wdaLocalPort;
// Common ports
const mjpegServerPort =
capabilities['appium:mjpegServerPort'] || capabilities.mjpegServerPort;
if (systemPort) portsToRelease.push(systemPort);
if (chromeDriverPort) portsToRelease.push(chromeDriverPort);
if (flutterSystemPort) portsToRelease.push(flutterSystemPort);
if (wdaLocalPort) portsToRelease.push(wdaLocalPort);
if (mjpegServerPort) portsToRelease.push(mjpegServerPort);
}
}
await unblockDeviceMatchingFilter({ session_id: sessionId });
log.info(`📱 Unblocking the device that is blocked for session ${sessionId}`);
const res = await next();
await EventBus.fire(new AfterSessionDeletedEvent({ sessionId: sessionId, device: device }));
if (device?.platform === 'ios' && device.realDevice) {
try {
await DEVICE_CONNECTIONS_FACTORY.releaseConnection(device.udid);
} catch (err) {
log.warn(`Error while releasing connection for device ${device.udid}. Error: ${err}`);
}
}
if (device) {
log.info(`📱 Cleanup: Device found: ${device.udid}`);
const deviceFarmManager = Container.get(DeviceFarmManager);
const deviceManagers = await deviceFarmManager.deviceInstances();
log.info(
`📱 Cleanup: Loaded managers: ${deviceManagers.map((m) => m.constructor.name).join(', ')}`,
);
if (device.platform.toLowerCase() === 'android') {
const androidApps =
device.deviceFarmCapabilities?.androidCleanUpApps || this.pluginArgs.androidCleanUpApps;
log.info(`📱 Cleanup: Android apps to cleanup: ${JSON.stringify(androidApps)}`);
if (androidApps && androidApps.length > 0) {
const androidManager = deviceManagers.find((m) => m instanceof AndroidDeviceManager);
if (androidManager) {
if (androidManager.uninstallApp) {
for (const app of androidApps) {
await androidManager.uninstallApp(device, app);
}
}
} else {
log.warn(`📱 Cleanup: AndroidManager not found in device managers.`);
}
}
} else if (device.platform.toLowerCase() === 'ios') {
const iosApps =
device.deviceFarmCapabilities?.iosCleanUpApps || this.pluginArgs.iosCleanUpApps;
log.info(`📱 Cleanup: iOS apps to cleanup: ${JSON.stringify(iosApps)}`);
if (iosApps && iosApps.length > 0) {
const iosManager = deviceManagers.find((m) => m instanceof IOSDeviceManager);
if (iosManager) {
if (iosManager.uninstallApp) {
for (const app of iosApps) {
await iosManager.uninstallApp(device, app);
}
}
} else {
log.warn(`📱 Cleanup: IOSDeviceManager not found in device managers.`);
}
}
}
} else {
log.info(`📱 Cleanup: No device found for session ${sessionId}`);
}
// Release all collected ports
const validPorts = portsToRelease.filter((p) => p !== null && p !== undefined);
if (validPorts.length > 0) {
releasePorts(validPorts);
log.info(
`📱 Released ${validPorts.length} port(s) for session ${sessionId}: ${validPorts.join(', ')}`,
);
}
return res;
}
}
Object.assign(DevicePlugin.prototype, commands);
export { DevicePlugin };