emulator.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. #!/usr/bin/env node
  2. /*
  3. Licensed to the Apache Software Foundation (ASF) under one
  4. or more contributor license agreements. See the NOTICE file
  5. distributed with this work for additional information
  6. regarding copyright ownership. The ASF licenses this file
  7. to you under the Apache License, Version 2.0 (the
  8. "License"); you may not use this file except in compliance
  9. with the License. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing,
  12. software distributed under the License is distributed on an
  13. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. KIND, either express or implied. See the License for the
  15. specific language governing permissions and limitations
  16. under the License.
  17. */
  18. /* jshint sub:true */
  19. var android_versions = require('android-versions');
  20. var retry = require('./retry');
  21. var build = require('./build');
  22. var path = require('path');
  23. var Adb = require('./Adb');
  24. var AndroidManifest = require('./AndroidManifest');
  25. var events = require('cordova-common').events;
  26. var superspawn = require('cordova-common').superspawn;
  27. var CordovaError = require('cordova-common').CordovaError;
  28. var shelljs = require('shelljs');
  29. var android_sdk = require('./android_sdk');
  30. var check_reqs = require('./check_reqs');
  31. var Q = require('q');
  32. var os = require('os');
  33. var fs = require('fs');
  34. var child_process = require('child_process');
  35. // constants
  36. var ONE_SECOND = 1000; // in milliseconds
  37. var ONE_MINUTE = 60 * ONE_SECOND; // in milliseconds
  38. var INSTALL_COMMAND_TIMEOUT = 5 * ONE_MINUTE; // in milliseconds
  39. var NUM_INSTALL_RETRIES = 3;
  40. var CHECK_BOOTED_INTERVAL = 3 * ONE_SECOND; // in milliseconds
  41. var EXEC_KILL_SIGNAL = 'SIGKILL';
  42. function forgivingWhichSync (cmd) {
  43. try {
  44. return fs.realpathSync(shelljs.which(cmd));
  45. } catch (e) {
  46. return '';
  47. }
  48. }
  49. module.exports.list_images_using_avdmanager = function () {
  50. return superspawn.spawn('avdmanager', ['list', 'avd']).then(function (output) {
  51. var response = output.split('\n');
  52. var emulator_list = [];
  53. for (var i = 1; i < response.length; i++) {
  54. // To return more detailed information use img_obj
  55. var img_obj = {};
  56. if (response[i].match(/Name:\s/)) {
  57. img_obj['name'] = response[i].split('Name: ')[1].replace('\r', '');
  58. if (response[i + 1].match(/Device:\s/)) {
  59. i++;
  60. img_obj['device'] = response[i].split('Device: ')[1].replace('\r', '');
  61. }
  62. if (response[i + 1].match(/Path:\s/)) {
  63. i++;
  64. img_obj['path'] = response[i].split('Path: ')[1].replace('\r', '');
  65. }
  66. if (response[i + 1].match(/Target:\s/)) {
  67. i++;
  68. if (response[i + 1].match(/ABI:\s/)) {
  69. img_obj['abi'] = response[i + 1].split('ABI: ')[1].replace('\r', '');
  70. }
  71. // This next conditional just aims to match the old output of `android list avd`
  72. // We do so so that we don't have to change the logic when parsing for the
  73. // best emulator target to spawn (see below in `best_image`)
  74. // This allows us to transitionally support both `android` and `avdmanager` binaries,
  75. // depending on what SDK version the user has
  76. if (response[i + 1].match(/Based\son:\s/)) {
  77. img_obj['target'] = response[i + 1].split('Based on:')[1];
  78. if (img_obj['target'].match(/Tag\/ABI:\s/)) {
  79. img_obj['target'] = img_obj['target'].split('Tag/ABI:')[0].replace('\r', '').trim();
  80. if (img_obj['target'].indexOf('(') > -1) {
  81. img_obj['target'] = img_obj['target'].substr(0, img_obj['target'].indexOf('(') - 1).trim();
  82. }
  83. }
  84. var version_string = img_obj['target'].replace(/Android\s+/, '');
  85. var api_level = android_sdk.version_string_to_api_level[version_string];
  86. if (api_level) {
  87. img_obj['target'] += ' (API level ' + api_level + ')';
  88. }
  89. }
  90. }
  91. if (response[i + 1].match(/Skin:\s/)) {
  92. i++;
  93. img_obj['skin'] = response[i].split('Skin: ')[1].replace('\r', '');
  94. }
  95. emulator_list.push(img_obj);
  96. }
  97. /* To just return a list of names use this
  98. if (response[i].match(/Name:\s/)) {
  99. emulator_list.push(response[i].split('Name: ')[1].replace('\r', '');
  100. } */
  101. }
  102. return emulator_list;
  103. });
  104. };
  105. module.exports.list_images_using_android = function () {
  106. return superspawn.spawn('android', ['list', 'avd']).then(function (output) {
  107. var response = output.split('\n');
  108. var emulator_list = [];
  109. for (var i = 1; i < response.length; i++) {
  110. // To return more detailed information use img_obj
  111. var img_obj = {};
  112. if (response[i].match(/Name:\s/)) {
  113. img_obj['name'] = response[i].split('Name: ')[1].replace('\r', '');
  114. if (response[i + 1].match(/Device:\s/)) {
  115. i++;
  116. img_obj['device'] = response[i].split('Device: ')[1].replace('\r', '');
  117. }
  118. if (response[i + 1].match(/Path:\s/)) {
  119. i++;
  120. img_obj['path'] = response[i].split('Path: ')[1].replace('\r', '');
  121. }
  122. if (response[i + 1].match(/\(API\slevel\s/) || (response[i + 2] && response[i + 2].match(/\(API\slevel\s/))) {
  123. i++;
  124. var secondLine = response[i + 1].match(/\(API\slevel\s/) ? response[i + 1] : '';
  125. img_obj['target'] = (response[i] + secondLine).split('Target: ')[1].replace('\r', '');
  126. }
  127. if (response[i + 1].match(/ABI:\s/)) {
  128. i++;
  129. img_obj['abi'] = response[i].split('ABI: ')[1].replace('\r', '');
  130. }
  131. if (response[i + 1].match(/Skin:\s/)) {
  132. i++;
  133. img_obj['skin'] = response[i].split('Skin: ')[1].replace('\r', '');
  134. }
  135. emulator_list.push(img_obj);
  136. }
  137. /* To just return a list of names use this
  138. if (response[i].match(/Name:\s/)) {
  139. emulator_list.push(response[i].split('Name: ')[1].replace('\r', '');
  140. } */
  141. }
  142. return emulator_list;
  143. });
  144. };
  145. /**
  146. * Returns a Promise for a list of emulator images in the form of objects
  147. * {
  148. name : <emulator_name>,
  149. device : <device>,
  150. path : <path_to_emulator_image>,
  151. target : <api_target>,
  152. abi : <cpu>,
  153. skin : <skin>
  154. }
  155. */
  156. module.exports.list_images = function () {
  157. return Q.fcall(function () {
  158. if (forgivingWhichSync('avdmanager')) {
  159. return module.exports.list_images_using_avdmanager();
  160. } else if (forgivingWhichSync('android')) {
  161. return module.exports.list_images_using_android();
  162. } else {
  163. return Q().then(function () {
  164. throw new CordovaError('Could not find either `android` or `avdmanager` on your $PATH! Are you sure the Android SDK is installed and available?');
  165. });
  166. }
  167. }).then(function (avds) {
  168. // In case we're missing the Android OS version string from the target description, add it.
  169. return avds.map(function (avd) {
  170. if (avd.target && avd.target.indexOf('Android API') > -1 && avd.target.indexOf('API level') < 0) {
  171. var api_level = avd.target.match(/\d+/);
  172. if (api_level) {
  173. var level = android_versions.get(api_level);
  174. avd.target = 'Android ' + level.semver + ' (API level ' + api_level + ')';
  175. }
  176. }
  177. return avd;
  178. });
  179. });
  180. };
  181. /**
  182. * Will return the closest avd to the projects target
  183. * or undefined if no avds exist.
  184. * Returns a promise.
  185. */
  186. module.exports.best_image = function () {
  187. return this.list_images().then(function (images) {
  188. // Just return undefined if there is no images
  189. if (images.length === 0) return;
  190. var closest = 9999;
  191. var best = images[0];
  192. var project_target = check_reqs.get_target().replace('android-', '');
  193. for (var i in images) {
  194. var target = images[i].target;
  195. if (target) {
  196. var num = target.split('(API level ')[1].replace(')', '');
  197. if (num === project_target) {
  198. return images[i];
  199. } else if (project_target - num < closest && project_target > num) {
  200. closest = project_target - num;
  201. best = images[i];
  202. }
  203. }
  204. }
  205. return best;
  206. });
  207. };
  208. // Returns a promise.
  209. module.exports.list_started = function () {
  210. return Adb.devices({emulators: true});
  211. };
  212. // Returns a promise.
  213. // TODO: we should remove this, there's a more robust method under android_sdk.js
  214. module.exports.list_targets = function () {
  215. return superspawn.spawn('android', ['list', 'targets'], {cwd: os.tmpdir()}).then(function (output) {
  216. var target_out = output.split('\n');
  217. var targets = [];
  218. for (var i = target_out.length; i >= 0; i--) {
  219. if (target_out[i].match(/id:/)) {
  220. targets.push(targets[i].split(' ')[1]);
  221. }
  222. }
  223. return targets;
  224. });
  225. };
  226. /*
  227. * Gets unused port for android emulator, between 5554 and 5584
  228. * Returns a promise.
  229. */
  230. module.exports.get_available_port = function () {
  231. var self = this;
  232. return self.list_started().then(function (emulators) {
  233. for (var p = 5584; p >= 5554; p -= 2) {
  234. if (emulators.indexOf('emulator-' + p) === -1) {
  235. events.emit('verbose', 'Found available port: ' + p);
  236. return p;
  237. }
  238. }
  239. throw new CordovaError('Could not find an available avd port');
  240. });
  241. };
  242. /*
  243. * Starts an emulator with the given ID,
  244. * and returns the started ID of that emulator.
  245. * If no ID is given it will use the first image available,
  246. * if no image is available it will error out (maybe create one?).
  247. * If no boot timeout is given or the value is negative it will wait forever for
  248. * the emulator to boot
  249. *
  250. * Returns a promise.
  251. */
  252. module.exports.start = function (emulator_ID, boot_timeout) {
  253. var self = this;
  254. return Q().then(function () {
  255. if (emulator_ID) return Q(emulator_ID);
  256. return self.best_image().then(function (best) {
  257. if (best && best.name) {
  258. events.emit('warn', 'No emulator specified, defaulting to ' + best.name);
  259. return best.name;
  260. }
  261. var androidCmd = check_reqs.getAbsoluteAndroidCmd();
  262. return Q.reject(new CordovaError('No emulator images (avds) found.\n' +
  263. '1. Download desired System Image by running: ' + androidCmd + ' sdk\n' +
  264. '2. Create an AVD by running: ' + androidCmd + ' avd\n' +
  265. 'HINT: For a faster emulator, use an Intel System Image and install the HAXM device driver\n'));
  266. });
  267. }).then(function (emulatorId) {
  268. return self.get_available_port().then(function (port) {
  269. // Figure out the directory the emulator binary runs in, and set the cwd to that directory.
  270. // Workaround for https://code.google.com/p/android/issues/detail?id=235461
  271. var emulator_dir = path.dirname(shelljs.which('emulator'));
  272. var args = ['-avd', emulatorId, '-port', port];
  273. // Don't wait for it to finish, since the emulator will probably keep running for a long time.
  274. child_process
  275. .spawn('emulator', args, { stdio: 'inherit', detached: true, cwd: emulator_dir })
  276. .unref();
  277. // wait for emulator to start
  278. events.emit('log', 'Waiting for emulator to start...');
  279. return self.wait_for_emulator(port);
  280. });
  281. }).then(function (emulatorId) {
  282. if (!emulatorId) { return Q.reject(new CordovaError('Failed to start emulator')); }
  283. // wait for emulator to boot up
  284. process.stdout.write('Waiting for emulator to boot (this may take a while)...');
  285. return self.wait_for_boot(emulatorId, boot_timeout).then(function (success) {
  286. if (success) {
  287. events.emit('log', 'BOOT COMPLETE');
  288. // unlock screen
  289. return Adb.shell(emulatorId, 'input keyevent 82').then(function () {
  290. // return the new emulator id for the started emulators
  291. return emulatorId;
  292. });
  293. } else {
  294. // We timed out waiting for the boot to happen
  295. return null;
  296. }
  297. });
  298. });
  299. };
  300. /*
  301. * Waits for an emulator to boot on a given port.
  302. * Returns this emulator's ID in a promise.
  303. */
  304. module.exports.wait_for_emulator = function (port) {
  305. var self = this;
  306. return Q().then(function () {
  307. var emulator_id = 'emulator-' + port;
  308. return Adb.shell(emulator_id, 'getprop dev.bootcomplete').then(function (output) {
  309. if (output.indexOf('1') >= 0) {
  310. return emulator_id;
  311. }
  312. return self.wait_for_emulator(port);
  313. }, function (error) {
  314. if ((error && error.message &&
  315. (error.message.indexOf('not found') > -1)) ||
  316. (error.message.indexOf('device offline') > -1)) {
  317. // emulator not yet started, continue waiting
  318. return self.wait_for_emulator(port);
  319. } else {
  320. // something unexpected has happened
  321. throw error;
  322. }
  323. });
  324. });
  325. };
  326. /*
  327. * Waits for the core android process of the emulator to start. Returns a
  328. * promise that resolves to a boolean indicating success. Not specifying a
  329. * time_remaining or passing a negative value will cause it to wait forever
  330. */
  331. module.exports.wait_for_boot = function (emulator_id, time_remaining) {
  332. var self = this;
  333. return Adb.shell(emulator_id, 'ps').then(function (output) {
  334. if (output.match(/android\.process\.acore/)) {
  335. return true;
  336. } else if (time_remaining === 0) {
  337. return false;
  338. } else {
  339. process.stdout.write('.');
  340. // Check at regular intervals
  341. return Q.delay(time_remaining < CHECK_BOOTED_INTERVAL ? time_remaining : CHECK_BOOTED_INTERVAL).then(function () {
  342. var updated_time = time_remaining >= 0 ? Math.max(time_remaining - CHECK_BOOTED_INTERVAL, 0) : time_remaining;
  343. return self.wait_for_boot(emulator_id, updated_time);
  344. });
  345. }
  346. });
  347. };
  348. /*
  349. * Create avd
  350. * TODO : Enter the stdin input required to complete the creation of an avd.
  351. * Returns a promise.
  352. */
  353. module.exports.create_image = function (name, target) {
  354. console.log('Creating new avd named ' + name);
  355. if (target) {
  356. return superspawn.spawn('android', ['create', 'avd', '--name', name, '--target', target]).then(null, function (error) {
  357. console.error('ERROR : Failed to create emulator image : ');
  358. console.error(' Do you have the latest android targets including ' + target + '?');
  359. console.error(error);
  360. });
  361. } else {
  362. console.log('WARNING : Project target not found, creating avd with a different target but the project may fail to install.');
  363. // TODO: there's a more robust method for finding targets in android_sdk.js
  364. return superspawn.spawn('android', ['create', 'avd', '--name', name, '--target', this.list_targets()[0]]).then(function () {
  365. // TODO: This seems like another error case, even though it always happens.
  366. console.error('ERROR : Unable to create an avd emulator, no targets found.');
  367. console.error('Ensure you have targets available by running the "android" command');
  368. return Q.reject();
  369. }, function (error) {
  370. console.error('ERROR : Failed to create emulator image : ');
  371. console.error(error);
  372. });
  373. }
  374. };
  375. module.exports.resolveTarget = function (target) {
  376. return this.list_started().then(function (emulator_list) {
  377. if (emulator_list.length < 1) {
  378. return Q.reject('No running Android emulators found, please start an emulator before deploying your project.');
  379. }
  380. // default emulator
  381. target = target || emulator_list[0];
  382. if (emulator_list.indexOf(target) < 0) {
  383. return Q.reject('Unable to find target \'' + target + '\'. Failed to deploy to emulator.');
  384. }
  385. return build.detectArchitecture(target).then(function (arch) {
  386. return {target: target, arch: arch, isEmulator: true};
  387. });
  388. });
  389. };
  390. /*
  391. * Installs a previously built application on the emulator and launches it.
  392. * If no target is specified, then it picks one.
  393. * If no started emulators are found, error out.
  394. * Returns a promise.
  395. */
  396. module.exports.install = function (givenTarget, buildResults) {
  397. var target;
  398. var manifest = new AndroidManifest(path.join(__dirname, '../../AndroidManifest.xml'));
  399. var pkgName = manifest.getPackageId();
  400. // resolve the target emulator
  401. return Q().then(function () {
  402. if (givenTarget && typeof givenTarget === 'object') {
  403. return givenTarget;
  404. } else {
  405. return module.exports.resolveTarget(givenTarget);
  406. }
  407. // set the resolved target
  408. }).then(function (resolvedTarget) {
  409. target = resolvedTarget;
  410. // install the app
  411. }).then(function () {
  412. // This promise is always resolved, even if 'adb uninstall' fails to uninstall app
  413. // or the app doesn't installed at all, so no error catching needed.
  414. return Q.when().then(function () {
  415. var apk_path = build.findBestApkForArchitecture(buildResults, target.arch);
  416. var execOptions = {
  417. cwd: os.tmpdir(),
  418. timeout: INSTALL_COMMAND_TIMEOUT, // in milliseconds
  419. killSignal: EXEC_KILL_SIGNAL
  420. };
  421. events.emit('log', 'Using apk: ' + apk_path);
  422. events.emit('log', 'Package name: ' + pkgName);
  423. events.emit('verbose', 'Installing app on emulator...');
  424. // A special function to call adb install in specific environment w/ specific options.
  425. // Introduced as a part of fix for http://issues.apache.org/jira/browse/CB-9119
  426. // to workaround sporadic emulator hangs
  427. function adbInstallWithOptions (target, apk, opts) {
  428. events.emit('verbose', 'Installing apk ' + apk + ' on ' + target + '...');
  429. var command = 'adb -s ' + target + ' install -r "' + apk + '"';
  430. return Q.promise(function (resolve, reject) {
  431. child_process.exec(command, opts, function (err, stdout, stderr) {
  432. if (err) reject(new CordovaError('Error executing "' + command + '": ' + stderr));
  433. // adb does not return an error code even if installation fails. Instead it puts a specific
  434. // message to stdout, so we have to use RegExp matching to detect installation failure.
  435. else if (/Failure/.test(stdout)) {
  436. if (stdout.match(/INSTALL_PARSE_FAILED_NO_CERTIFICATES/)) {
  437. stdout += 'Sign the build using \'-- --keystore\' or \'--buildConfig\'' +
  438. ' or sign and deploy the unsigned apk manually using Android tools.';
  439. } else if (stdout.match(/INSTALL_FAILED_VERSION_DOWNGRADE/)) {
  440. stdout += 'You\'re trying to install apk with a lower versionCode that is already installed.' +
  441. '\nEither uninstall an app or increment the versionCode.';
  442. }
  443. reject(new CordovaError('Failed to install apk to emulator: ' + stdout));
  444. } else resolve(stdout);
  445. });
  446. });
  447. }
  448. function installPromise () {
  449. return adbInstallWithOptions(target.target, apk_path, execOptions).catch(function (error) {
  450. // CB-9557 CB-10157 only uninstall and reinstall app if the one that
  451. // is already installed on device was signed w/different certificate
  452. if (!/INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES/.test(error.toString())) { throw error; }
  453. events.emit('warn', 'Uninstalling app from device and reinstalling it because the ' +
  454. 'currently installed app was signed with different key');
  455. // This promise is always resolved, even if 'adb uninstall' fails to uninstall app
  456. // or the app doesn't installed at all, so no error catching needed.
  457. return Adb.uninstall(target.target, pkgName).then(function () {
  458. return adbInstallWithOptions(target.target, apk_path, execOptions);
  459. });
  460. });
  461. }
  462. return retry.retryPromise(NUM_INSTALL_RETRIES, installPromise).then(function (output) {
  463. events.emit('log', 'INSTALL SUCCESS');
  464. });
  465. });
  466. // unlock screen
  467. }).then(function () {
  468. events.emit('verbose', 'Unlocking screen...');
  469. return Adb.shell(target.target, 'input keyevent 82');
  470. }).then(function () {
  471. Adb.start(target.target, pkgName + '/.' + manifest.getActivity().getName());
  472. // report success or failure
  473. }).then(function (output) {
  474. events.emit('log', 'LAUNCH SUCCESS');
  475. });
  476. };