Skip to content

Commit

Permalink
refactor: Allow usage of logger shared with the parent driver (#578)
Browse files Browse the repository at this point in the history
  • Loading branch information
mykola-mokhnach authored Mar 30, 2022
1 parent db140f7 commit d5ddb46
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 58 deletions.
70 changes: 36 additions & 34 deletions lib/webdriveragent.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import url from 'url';
import B from 'bluebird';
import { JWProxy } from '@appium/base-driver';
import { fs, util, plist, mkdirp } from '@appium/support';
import log from './logger';
import defaultLogger from './logger';
import { NoSessionProxy } from './no-session-proxy';
import {
getWDAUpgradeTimestamp, resetTestProcesses, getPIDsListeningOnPort
Expand All @@ -24,10 +24,11 @@ const WDA_CF_BUNDLE_NAME = 'WebDriverAgentRunner-Runner';
const SHARED_RESOURCES_GUARD = new AsyncLock();

class WebDriverAgent {
constructor (xcodeVersion, args = {}) {
constructor (xcodeVersion, args = {}, log = null) {
this.xcodeVersion = xcodeVersion;

this.args = _.clone(args);
this.log = log ?? defaultLogger;

this.device = args.device;
this.platformVersion = args.platformVersion;
Expand Down Expand Up @@ -83,18 +84,18 @@ class WebDriverAgent {
allowProvisioningDeviceRegistration: args.allowProvisioningDeviceRegistration,
resultBundlePath: args.resultBundlePath,
resultBundleVersion: args.resultBundleVersion,
});
}, this.log);
}

setWDAPaths (bootstrapPath, agentPath) {
// allow the user to specify a place for WDA. This is undocumented and
// only here for the purposes of testing development of WDA
this.bootstrapPath = bootstrapPath || BOOTSTRAP_PATH;
log.info(`Using WDA path: '${this.bootstrapPath}'`);
this.log.info(`Using WDA path: '${this.bootstrapPath}'`);

// for backward compatibility we need to be able to specify agentPath too
this.agentPath = agentPath || path.resolve(this.bootstrapPath, 'WebDriverAgent.xcodeproj');
log.info(`Using WDA agent: '${this.agentPath}'`);
this.log.info(`Using WDA agent: '${this.agentPath}'`);
}

async cleanupObsoleteProcesses () {
Expand All @@ -103,17 +104,17 @@ class WebDriverAgent {
!cmdLine.toLowerCase().includes(this.device.udid.toLowerCase()));

if (_.isEmpty(obsoletePids)) {
log.debug(`No obsolete cached processes from previous WDA sessions ` +
this.log.debug(`No obsolete cached processes from previous WDA sessions ` +
`listening on port ${this.url.port} have been found`);
return;
}

log.info(`Detected ${obsoletePids.length} obsolete cached process${obsoletePids.length === 1 ? '' : 'es'} ` +
this.log.info(`Detected ${obsoletePids.length} obsolete cached process${obsoletePids.length === 1 ? '' : 'es'} ` +
`from previous WDA sessions. Cleaning them up`);
try {
await exec('kill', obsoletePids);
} catch (e) {
log.warn(`Failed to kill obsolete cached process${obsoletePids.length === 1 ? '' : 'es'} '${obsoletePids}'. ` +
this.log.warn(`Failed to kill obsolete cached process${obsoletePids.length === 1 ? '' : 'es'} '${obsoletePids}'. ` +
`Original error: ${e.message}`);
}
}
Expand Down Expand Up @@ -166,7 +167,7 @@ class WebDriverAgent {
try {
return await noSessionProxy.command('/status', 'GET');
} catch (err) {
log.debug(`WDA is not listening at '${this.url.href}'`);
this.log.debug(`WDA is not listening at '${this.url.href}'`);
return null;
}
}
Expand All @@ -180,31 +181,31 @@ class WebDriverAgent {
try {
const bundleIds = await this.device.getUserInstalledBundleIdsByBundleName(WDA_CF_BUNDLE_NAME);
if (_.isEmpty(bundleIds)) {
log.debug('No WDAs on the device.');
this.log.debug('No WDAs on the device.');
return;
}

log.debug(`Uninstalling WDAs: '${bundleIds}'`);
this.log.debug(`Uninstalling WDAs: '${bundleIds}'`);
for (const bundleId of bundleIds) {
await this.device.removeApp(bundleId);
}
} catch (e) {
log.debug(e);
log.warn(`WebDriverAgent uninstall failed. Perhaps, it is already uninstalled? ` +
this.log.debug(e);
this.log.warn(`WebDriverAgent uninstall failed. Perhaps, it is already uninstalled? ` +
`Original error: ${e.message}`);
}
}

async _cleanupProjectIfFresh () {
const homeFolder = process.env.HOME;
if (!homeFolder) {
log.info('The HOME folder path cannot be determined');
this.log.info('The HOME folder path cannot be determined');
return;
}

const currentUpgradeTimestamp = await getWDAUpgradeTimestamp();
if (!_.isInteger(currentUpgradeTimestamp)) {
log.info('It is impossible to determine the timestamp of the package');
this.log.info('It is impossible to determine the timestamp of the package');
return;
}

Expand All @@ -213,39 +214,39 @@ class WebDriverAgent {
try {
await fs.access(timestampPath, fs.W_OK);
} catch (ign) {
log.info(`WebDriverAgent upgrade timestamp at '${timestampPath}' is not writeable. ` +
this.log.info(`WebDriverAgent upgrade timestamp at '${timestampPath}' is not writeable. ` +
`Skipping sources cleanup`);
return;
}
const recentUpgradeTimestamp = parseInt(await fs.readFile(timestampPath, 'utf8'), 10);
if (_.isInteger(recentUpgradeTimestamp)) {
if (recentUpgradeTimestamp >= currentUpgradeTimestamp) {
log.info(`WebDriverAgent does not need a cleanup. The sources are up to date ` +
this.log.info(`WebDriverAgent does not need a cleanup. The sources are up to date ` +
`(${recentUpgradeTimestamp} >= ${currentUpgradeTimestamp})`);
return;
}
log.info(`WebDriverAgent sources have been upgraded ` +
this.log.info(`WebDriverAgent sources have been upgraded ` +
`(${recentUpgradeTimestamp} < ${currentUpgradeTimestamp})`);
} else {
log.warn(`The recent upgrade timestamp at '${timestampPath}' is corrupted. Trying to fix it`);
this.log.warn(`The recent upgrade timestamp at '${timestampPath}' is corrupted. Trying to fix it`);
}
}

try {
await mkdirp(path.dirname(timestampPath));
await fs.writeFile(timestampPath, `${currentUpgradeTimestamp}`, 'utf8');
log.debug(`Stored the recent WebDriverAgent upgrade timestamp ${currentUpgradeTimestamp} ` +
this.log.debug(`Stored the recent WebDriverAgent upgrade timestamp ${currentUpgradeTimestamp} ` +
`at '${timestampPath}'`);
} catch (e) {
log.info(`Unable to create the recent WebDriverAgent upgrade timestamp at '${timestampPath}'. ` +
this.log.info(`Unable to create the recent WebDriverAgent upgrade timestamp at '${timestampPath}'. ` +
`Original error: ${e.message}`);
return;
}

try {
await this.xcodebuild.cleanProject();
} catch (e) {
log.warn(`Cannot perform WebDriverAgent project cleanup. Original error: ${e.message}`);
this.log.warn(`Cannot perform WebDriverAgent project cleanup. Original error: ${e.message}`);
}
}

Expand Down Expand Up @@ -274,13 +275,13 @@ class WebDriverAgent {
*/
async launch (sessionId) {
if (this.webDriverAgentUrl) {
log.info(`Using provided WebdriverAgent at '${this.webDriverAgentUrl}'`);
this.log.info(`Using provided WebdriverAgent at '${this.webDriverAgentUrl}'`);
this.url = this.webDriverAgentUrl;
this.setupProxies(sessionId);
return await this.getStatus();
}

log.info('Launching WebDriverAgent on the device');
this.log.info('Launching WebDriverAgent on the device');

this.setupProxies(sessionId);

Expand All @@ -292,7 +293,7 @@ class WebDriverAgent {
// useXctestrunFile and usePrebuiltWDA use existing dependencies
// It depends on user side
if (this.idb || this.useXctestrunFile || (this.derivedDataPath && this.usePrebuiltWDA)) {
log.info('Skipped WDA project cleanup according to the provided capabilities');
this.log.info('Skipped WDA project cleanup according to the provided capabilities');
} else {
const synchronizationKey = path.normalize(this.bootstrapPath);
await SHARED_RESOURCES_GUARD.acquire(synchronizationKey,
Expand All @@ -316,7 +317,7 @@ class WebDriverAgent {
}

async startWithIDB () {
log.info('Will launch WDA with idb instead of xcodebuild since the corresponding flag is enabled');
this.log.info('Will launch WDA with idb instead of xcodebuild since the corresponding flag is enabled');
const {wdaBundleId, testBundleId} = await this.prepareWDA();
const env = {
USE_PORT: this.wdaRemotePort,
Expand Down Expand Up @@ -371,6 +372,7 @@ class WebDriverAgent {

setupProxies (sessionId) {
const proxyOpts = {
log: this.log,
server: this.url.hostname,
port: this.url.port,
base: this.basePath,
Expand All @@ -386,7 +388,7 @@ class WebDriverAgent {
}

async quit () {
log.info('Shutting down sub-processes');
this.log.info('Shutting down sub-processes');

await this.xcodebuild.quit();
await this.xcodebuild.reset();
Expand Down Expand Up @@ -443,7 +445,7 @@ class WebDriverAgent {
async setupCaching () {
const status = await this.getStatus();
if (!status || !status.build) {
log.debug('WDA is currently not running. There is nothing to cache');
this.log.debug('WDA is currently not running. There is nothing to cache');
return;
}

Expand All @@ -453,28 +455,28 @@ class WebDriverAgent {
} = status.build;
// for real device
if (util.hasValue(productBundleIdentifier) && util.hasValue(this.updatedWDABundleId) && this.updatedWDABundleId !== productBundleIdentifier) {
log.info(`Will uninstall running WDA since it has different bundle id. The actual value is '${productBundleIdentifier}'.`);
this.log.info(`Will uninstall running WDA since it has different bundle id. The actual value is '${productBundleIdentifier}'.`);
return await this.uninstall();
}
// for simulator
if (util.hasValue(productBundleIdentifier) && !util.hasValue(this.updatedWDABundleId) && WDA_RUNNER_BUNDLE_ID !== productBundleIdentifier) {
log.info(`Will uninstall running WDA since its bundle id is not equal to the default value ${WDA_RUNNER_BUNDLE_ID}`);
this.log.info(`Will uninstall running WDA since its bundle id is not equal to the default value ${WDA_RUNNER_BUNDLE_ID}`);
return await this.uninstall();
}

const actualUpgradeTimestamp = await getWDAUpgradeTimestamp();
log.debug(`Upgrade timestamp of the currently bundled WDA: ${actualUpgradeTimestamp}`);
log.debug(`Upgrade timestamp of the WDA on the device: ${upgradedAt}`);
this.log.debug(`Upgrade timestamp of the currently bundled WDA: ${actualUpgradeTimestamp}`);
this.log.debug(`Upgrade timestamp of the WDA on the device: ${upgradedAt}`);
if (actualUpgradeTimestamp && upgradedAt && _.toLower(`${actualUpgradeTimestamp}`) !== _.toLower(`${upgradedAt}`)) {
log.info('Will uninstall running WDA since it has different version in comparison to the one ' +
this.log.info('Will uninstall running WDA since it has different version in comparison to the one ' +
`which is bundled with appium-xcuitest-driver module (${actualUpgradeTimestamp} != ${upgradedAt})`);
return await this.uninstall();
}

const message = util.hasValue(productBundleIdentifier)
? `Will reuse previously cached WDA instance at '${this.url.href}' with '${productBundleIdentifier}'`
: `Will reuse previously cached WDA instance at '${this.url.href}'`;
log.info(`${message}. Set the wdaLocalPort capability to a value different from ${this.url.port} if this is an undesired behavior.`);
this.log.info(`${message}. Set the wdaLocalPort capability to a value different from ${this.url.port} if this is an undesired behavior.`);
this.webDriverAgentUrl = this.url.href;
}

Expand Down
Loading

0 comments on commit d5ddb46

Please sign in to comment.