All files / lib utils.js

83.33% Statements 60/72
62.96% Branches 17/27
86.67% Functions 13/15
84.51% Lines 60/71
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                            1x               3x 3x 3x                         4x 4x 4x 4x     4x         4x   2x 2x     1x     3x     3x                     3x             2x   2x 2x 2x   52x 52x     52x     52x                                       2x 4x 4x 4x   4x     2x     4x     2x           1x         2x   2x         14x   14x 42x   42x     206x                                                 1x 1x                     2x 2x         1x 1x   1x 1x               2x 2x   2x         1x 1x             85x 105x 105x 105x 85x 85x   105x            
import log from './logger';
import _ from 'lodash';
import { exec } from 'teen_process';
import { waitForCondition } from 'asyncbox';
import { getVersion } from 'appium-xcode';
import { getDevices } from 'node-simctl';
import { fs } from 'appium-support';
import { Certificate } from './certificate';
import { restoreTouchEnrollShortcuts } from './touch-enroll';
import path from 'path';
import Simulator from './simulator-xcode-6';
import fkill from 'fkill';
 
 
const DEFAULT_SIM_SHUTDOWN_TIMEOUT = 10000;
 
// pgrep/pkill exit codes:
// 0       One or more processes were matched.
// 1       No processes were matched.
// 2       Invalid options were specified on the command line.
// 3       An internal error occurred.
 
async function pkill (appName, forceKill = false) {
  let args = forceKill ? ['-9'] : [];
  args.push('-x', appName);
  try {
    await exec('pkill', args);
    return 0;
  } catch (err) {
    if (!_.isUndefined(err.code)) {
      throw new Error(`Cannot forcefully terminate ${appName}. pkill error code: ${err.code}`);
    }
    log.error(`Received unexpected error while trying to kill ${appName}: ${err.message}`);
    throw err;
  }
}
 
async function killAllSimulators (timeout = DEFAULT_SIM_SHUTDOWN_TIMEOUT) {
  log.debug('Killing all iOS Simulators');
  const xcodeVersion = await getVersion(true);
  const appName = xcodeVersion.major >= 7 ? 'Simulator' : 'iOS Simulator';
 
  // later versions are slower to close
  timeout = timeout * (xcodeVersion.major === 8 ? 2 : 1);
 
  // Restore default shortcut key to original state
  await restoreTouchEnrollShortcuts();
 
  let pids;
  try {
    let {stdout} = await exec('pgrep', ['-x', appName]);
    pids = stdout.trim().split('\n').map((pid) => parseInt(pid, 10));
  } catch (e) {
    if (e.code === 1) {
      log.debug(`${appName} is not running. Continuing...`);
      return;
    }
    log.warn(`pgrep error ${e.code} while detecting whether ${appName} is running. Trying to kill anyway.`);
  }
 
  await (async function performKill (pids = []) {
    try {
      await exec('xcrun', ['simctl', 'shutdown', 'booted'], {timeout});
    } catch (ign) {}
 
    if (pids.length) {
      log.debug(`Using fkill to kill processes: ${pids.join(', ')}`);
      try {
        await fkill(pids, {force: true});
      } catch (ign) {}
    } else {
      log.debug(`Using pkill to kill application: ${appName}`);
      await pkill(appName, true);
    }
  })(pids);
 
  // wait for all the devices to be shutdown before Continuing
  // but only print out the failed ones when they are actually fully failed
  let remainingDevices = [];
  async function allSimsAreDown () {
    remainingDevices = [];
    let devices = await getDevices();
    devices = _.flatten(_.values(devices));
    return _.every(devices, (sim) => {
      let state = sim.state.toLowerCase();
      let done = state === 'shutdown' ||
                 state === 'unavailable' ||
                 state === 'disconnected';
      Iif (!done) {
        remainingDevices.push(`${sim.name} (${sim.sdk}, udid: ${sim.udid}) is still in state '${state}'`);
      }
      return done;
    });
  }
  try {
    await waitForCondition(allSimsAreDown, {
      waitMs: timeout,
      intervalMs: 200
    });
  } catch (err) {
    if (remainingDevices.length > 0) {
      log.warn(`The following devices are still not in the correct state after ${timeout} ms:`);
      for (let device of remainingDevices) {
        log.warn(`    ${device}`);
      }
    }
    throw err;
  }
}
 
async function endAllSimulatorDaemons () {
  log.debug('Ending all simulator daemons');
  for (let servicePattern of ['com.apple.iphonesimulator', 'com.apple.CoreSimulator']) {
    log.debug(`Killing any other ${servicePattern} daemons`);
    let launchCtlCommand = `launchctl list | grep ${servicePattern} | cut -f 3 | xargs -n 1 launchctl`;
    try {
      let stopCmd = `${launchCtlCommand} stop`;
      await exec('bash', ['-c', stopCmd]);
    } catch (err) {
      log.warn(`Could not stop ${servicePattern} daemons, carrying on anyway!`);
    }
    try {
      let removeCmd = `${launchCtlCommand} remove`;
      await exec('bash', ['-c', removeCmd]);
    } catch (err) {
      log.warn(`Could not remove ${servicePattern} daemons, carrying on anyway!`);
    }
  }
  // waiting until the simulator service has died.
  try {
    await waitForCondition(async () => {
      let {stdout} = await exec('bash', ['-c',
        `ps -e  | grep launchd_sim | grep -v bash | grep -v grep | awk {'print$1'}`]);
      return stdout.trim().length === 0;
    }, {waitMs: 5000, intervalMs: 500});
  } catch (err) {
    log.warn(`Could not end all simulator daemons, carrying on!`);
  }
  log.debug('Finishing ending all simulator daemons');
}
 
async function simExists (udid) {
  // see the README for github.com/appium/node-simctl for example output of getDevices()
  let devices = await getDevices();
 
  devices = _.toPairs(devices).map((pair) => {
    return pair[1];
  }).reduce((a, b) => {
    return a.concat(b);
  }, []);
  return !!_.find(devices, (sim) => {
    return sim.udid === udid;
  });
}
 
async function safeRimRaf (delPath, tryNum = 0) {
  try {
    await fs.rimraf(delPath);
  } catch (err) {
    if (tryNum < 20) {
      if (err.message.indexOf('ENOTEMPTY') !== -1) {
        log.debug(`Path '${delPath}' was not empty during delete; retrying`);
        return safeRimRaf(delPath, tryNum + 1);
      } else if (err.message.indexOf('ENOENT') !== -1) {
        log.debug(`Path '${delPath}'' did not exist when we tried to delete, ignoring`);
        return safeRimRaf(delPath, tryNum + 1);
      }
    }
  }
}
 
async function installSSLCert (pemText, udid) {
  // Check that openssl is installed on the path
  try {
    await fs.which('openssl');
  } catch (e) {
    log.debug(`customSSLCert requires openssl to be available on path`);
    log.errorAndThrow(`Command 'openssl' not found`);
  }
 
  // Check that sqlite3 is installed on the path
  try {
    await fs.which('sqlite3');
  } catch (e) {
    log.debug(`customSSLCert requires sqlite3 to be available on path`);
    log.errorAndThrow(`Command 'sqlite3' not found`);
  }
 
  let tempFileName = path.resolve(`${__dirname}/temp-ssl-cert.pem`);
  let pathToKeychain = path.resolve(new Simulator(udid).getDir());
  await fs.writeFile(tempFileName, pemText);
  try {
    await fs.stat(pathToKeychain);
  } catch (e) {
    log.debug(`Could not install SSL certificate. No simulator with udid '${udid}'`);
    log.errorAndThrow(e);
  }
  let certificate = new Certificate(tempFileName);
  log.debug(`Installing certificate to ${pathToKeychain}`);
  await certificate.add(pathToKeychain);
  await fs.unlink(tempFileName);
  return certificate;
}
 
async function uninstallSSLCert (pemText, udid) {
  try {
    let tempFileName = path.resolve(__dirname, 'temp-ssl-cert.pem');
    let pathToKeychain = path.resolve(new Simulator(udid).getDir());
    await fs.writeFile(tempFileName, pemText);
    let certificate = new Certificate(tempFileName);
    await certificate.remove(pathToKeychain);
    await fs.unlink(tempFileName);
    return certificate;
  } catch (e) {
    log.debug(`Could not uninstall SSL certificate. No simulator with udid '${udid}'`);
    log.errorAndThrow(e);
  }
}
 
/**
 * Runs a command line sqlite3 query
 */
async function execSQLiteQuery (db, query, ...queryParams) {
  let queryTokens = query.split('?');
  let formattedQuery = [];
  queryParams.forEach((param, i) => {
    formattedQuery.push(queryTokens[i]);
    formattedQuery.push(param.replace(/'/g, "''"));
  });
  formattedQuery.push(queryTokens[queryTokens.length - 1]);
 
  return await exec('sqlite3', ['-line', db, formattedQuery.join('')]);
}
 
export { killAllSimulators, endAllSimulatorDaemons, safeRimRaf, simExists, installSSLCert, uninstallSSLCert, execSQLiteQuery };