fuchsia_device.dart 25.2 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

7 8
import 'package:meta/meta.dart';

9
import '../application_package.dart';
10
import '../artifacts.dart';
11
import '../base/common.dart';
12 13
import '../base/context.dart';
import '../base/file_system.dart';
14
import '../base/io.dart';
15
import '../base/logger.dart';
16
import '../base/net.dart';
17
import '../base/process.dart';
18
import '../base/time.dart';
19 20
import '../build_info.dart';
import '../device.dart';
21
import '../globals.dart' as globals;
22
import '../project.dart';
23
import '../vmservice.dart';
24

25 26 27 28
import 'amber_ctl.dart';
import 'application_package.dart';
import 'fuchsia_build.dart';
import 'fuchsia_pm.dart';
29 30
import 'fuchsia_sdk.dart';
import 'fuchsia_workflow.dart';
31 32 33 34 35 36 37 38 39 40 41 42 43 44
import 'tiles_ctl.dart';

/// The [FuchsiaDeviceTools] instance.
FuchsiaDeviceTools get fuchsiaDeviceTools => context.get<FuchsiaDeviceTools>();

/// Fuchsia device-side tools.
class FuchsiaDeviceTools {
  FuchsiaAmberCtl _amberCtl;
  FuchsiaAmberCtl get amberCtl => _amberCtl ??= FuchsiaAmberCtl();

  FuchsiaTilesCtl _tilesCtl;
  FuchsiaTilesCtl get tilesCtl => _tilesCtl ??= FuchsiaTilesCtl();
}

45 46 47
final String _ipv4Loopback = InternetAddress.loopbackIPv4.address;
final String _ipv6Loopback = InternetAddress.loopbackIPv6.address;

48 49 50 51 52
// Enables testing the fuchsia isolate discovery
Future<VMService> _kDefaultFuchsiaIsolateDiscoveryConnector(Uri uri) {
  return VMService.connect(uri);
}

53 54
/// Read the log for a particular device.
class _FuchsiaLogReader extends DeviceLogReader {
55
  _FuchsiaLogReader(this._device, [this._app]);
56

57 58
  // \S matches non-whitespace characters.
  static final RegExp _flutterLogOutput = RegExp(r'INFO: \S+\(flutter\): ');
59

60 61
  final FuchsiaDevice _device;
  final ApplicationPackage _app;
62

63 64
  @override
  String get name => _device.name;
65 66 67 68

  Stream<String> _logLines;
  @override
  Stream<String> get logLines {
69 70
    final Stream<String> logStream = fuchsiaSdk.syslogs(_device.id);
    _logLines ??= _processLogs(logStream);
71 72 73
    return _logLines;
  }

74
  Stream<String> _processLogs(Stream<String> lines) {
75 76 77
    if (lines == null) {
      return null;
    }
78 79 80 81 82 83
    // Get the starting time of the log processor to filter logs from before
    // the process attached.
    final DateTime startTime = systemClock.now();
    // Determine if line comes from flutter, and optionally whether it matches
    // the correct fuchsia module.
    final RegExp matchRegExp = _app == null
84
        ? _flutterLogOutput
85
        : RegExp('INFO: ${_app.name}(\.cmx)?\\(flutter\\): ');
86 87
    return Stream<String>.eventTransformed(
      lines,
88
      (EventSink<String> output) => _FuchsiaLogSink(output, matchRegExp, startTime),
89
    );
90 91
  }

92 93
  @override
  String toString() => name;
94 95 96 97 98 99

  @override
  void dispose() {
    // The Fuchsia SDK syslog process is killed when the subscription to the
    // logLines Stream is canceled.
  }
100 101
}

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
class _FuchsiaLogSink implements EventSink<String> {
  _FuchsiaLogSink(this._outputSink, this._matchRegExp, this._startTime);

  static final RegExp _utcDateOutput = RegExp(r'\d+\-\d+\-\d+ \d+:\d+:\d+');
  final EventSink<String> _outputSink;
  final RegExp _matchRegExp;
  final DateTime _startTime;

  @override
  void add(String line) {
    if (!_matchRegExp.hasMatch(line)) {
      return;
    }
    final String rawDate = _utcDateOutput.firstMatch(line)?.group(0);
    if (rawDate == null) {
      return;
    }
    final DateTime logTime = DateTime.parse(rawDate);
    if (logTime.millisecondsSinceEpoch < _startTime.millisecondsSinceEpoch) {
      return;
    }
123 124
    _outputSink.add(
        '[${logTime.toLocal()}] Flutter: ${line.split(_matchRegExp).last}');
125 126 127
  }

  @override
128
  void addError(Object error, [StackTrace stackTrace]) {
129 130 131 132
    _outputSink.addError(error, stackTrace);
  }

  @override
133 134 135
  void close() {
    _outputSink.close();
  }
136 137
}

138 139 140 141
class FuchsiaDevices extends PollingDeviceDiscovery {
  FuchsiaDevices() : super('Fuchsia devices');

  @override
142
  bool get supportsPlatform => isFuchsiaSupportedPlatform();
143 144 145 146 147 148 149 150 151

  @override
  bool get canListAnything => fuchsiaWorkflow.canListDevices;

  @override
  Future<List<Device>> pollingGetDevices() async {
    if (!fuchsiaWorkflow.canListDevices) {
      return <Device>[];
    }
152
    final String text = await fuchsiaSdk.listDevices();
153
    if (text == null || text.isEmpty) {
154 155
      return <Device>[];
    }
156
    final List<FuchsiaDevice> devices = await parseListDevices(text);
157
    return devices;
158 159 160 161 162 163 164
  }

  @override
  Future<List<String>> getDiagnostics() async => const <String>[];
}

@visibleForTesting
165
Future<List<FuchsiaDevice>> parseListDevices(String text) async {
166
  final List<FuchsiaDevice> devices = <FuchsiaDevice>[];
167
  for (final String rawLine in text.trim().split('\n')) {
168
    final String line = rawLine.trim();
169
    // ['ip', 'device name']
170
    final List<String> words = line.split(' ');
171 172 173
    if (words.length < 2) {
      continue;
    }
174
    final String name = words[1];
175 176 177 178 179 180 181 182 183
    final String resolvedHost = await fuchsiaSdk.fuchsiaDevFinder.resolve(
      name,
      local: false,
    );
    if (resolvedHost == null) {
      globals.printError('Failed to resolve host for Fuchsia device `$name`');
      continue;
    }
    devices.add(FuchsiaDevice(resolvedHost, name: name));
184
  }
185
  return devices;
186 187
}

188
class FuchsiaDevice extends Device {
189 190 191 192 193 194
  FuchsiaDevice(String id, {this.name}) : super(
      id,
      platformType: PlatformType.fuchsia,
      category: null,
      ephemeral: false,
  );
195 196

  @override
197 198 199 200
  bool get supportsHotReload => true;

  @override
  bool get supportsHotRestart => false;
201

202
  @override
203
  bool get supportsFlutterExit => false;
204

205 206 207 208
  @override
  final String name;

  @override
209
  Future<bool> get isLocalEmulator async => false;
210

211 212 213
  @override
  Future<String> get emulatorId async => null;

214 215 216 217
  @override
  bool get supportsStartPaused => false;

  @override
218
  Future<bool> isAppInstalled(ApplicationPackage app) async => false;
219 220

  @override
221
  Future<bool> isLatestBuildInstalled(ApplicationPackage app) async => false;
222 223

  @override
224
  Future<bool> installApp(ApplicationPackage app) => Future<bool>.value(false);
225 226

  @override
227
  Future<bool> uninstallApp(ApplicationPackage app) async => false;
228 229 230 231 232 233

  @override
  bool isSupported() => true;

  @override
  Future<LaunchResult> startApp(
234
    covariant FuchsiaApp package, {
235 236 237 238
    String mainPath,
    String route,
    DebuggingOptions debuggingOptions,
    Map<String, dynamic> platformArgs,
239 240
    bool prebuiltApplication = false,
    bool ipv6 = false,
241 242 243
  }) async {
    if (!prebuiltApplication) {
      await buildFuchsia(fuchsiaProject: FlutterProject.current().fuchsia,
244
                         targetPlatform: await targetPlatform,
245 246 247 248 249
                         target: mainPath,
                         buildInfo: debuggingOptions.buildInfo);
    }
    // Stop the app if it's currently running.
    await stopApp(package);
250 251 252 253
    final String host = await fuchsiaSdk.fuchsiaDevFinder.resolve(
      name,
      local: true,
    );
254
    if (host == null) {
255
      globals.printError('Failed to resolve host for Fuchsia device');
256 257
      return LaunchResult.failed();
    }
258
    // Find out who the device thinks we are.
259
    final int port = await globals.os.findFreePort();
260
    if (port == 0) {
261
      globals.printError('Failed to find a free port');
262 263
      return LaunchResult.failed();
    }
264 265 266

    // Try Start with a fresh package repo in case one was left over from a
    // previous run.
267
    final Directory packageRepo =
268
        globals.fs.directory(globals.fs.path.join(getFuchsiaBuildDirectory(), '.pkg-repo'));
269 270 271 272 273 274
    try {
      if (packageRepo.existsSync()) {
        packageRepo.deleteSync(recursive: true);
      }
      packageRepo.createSync(recursive: true);
    } catch (e) {
275
      globals.printError('Failed to create Fuchisa package repo directory '
276 277 278
                 'at ${packageRepo.path}: $e');
      return LaunchResult.failed();
    }
279 280

    final String appName = FlutterProject.current().manifest.appName;
281
    final Status status = globals.logger.startProgress(
282
      'Starting Fuchsia application $appName...',
283 284 285 286 287
      timeout: null,
    );
    FuchsiaPackageServer fuchsiaPackageServer;
    bool serverRegistered = false;
    try {
288 289 290 291
      // Ask amber to pre-fetch some things we'll need before setting up our own
      // package server. This is to avoid relying on amber correctly using
      // multiple package servers, support for which is in flux.
      if (!await fuchsiaDeviceTools.amberCtl.getUp(this, 'tiles')) {
292
        globals.printError('Failed to get amber to prefetch tiles');
293 294 295
        return LaunchResult.failed();
      }
      if (!await fuchsiaDeviceTools.amberCtl.getUp(this, 'tiles_ctl')) {
296
        globals.printError('Failed to get amber to prefetch tiles_ctl');
297 298 299
        return LaunchResult.failed();
      }

300
      // Start up a package server.
301
      const String packageServerName = FuchsiaPackageServer.toolHost;
302 303
      fuchsiaPackageServer = FuchsiaPackageServer(
          packageRepo.path, packageServerName, host, port);
304
      if (!await fuchsiaPackageServer.start()) {
305
        globals.printError('Failed to start the Fuchsia package server');
306 307
        return LaunchResult.failed();
      }
308 309

      // Serve the application's package.
310 311 312
      final File farArchive = package.farArchive(
          debuggingOptions.buildInfo.mode);
      if (!await fuchsiaPackageServer.addPackage(farArchive)) {
313
        globals.printError('Failed to add package to the package server');
314 315 316
        return LaunchResult.failed();
      }

317
      // Serve the flutter_runner.
318
      final File flutterRunnerArchive = globals.fs.file(globals.artifacts.getArtifactPath(
319
        Artifact.fuchsiaFlutterRunner,
320 321 322 323
        platform: await targetPlatform,
        mode: debuggingOptions.buildInfo.mode,
      ));
      if (!await fuchsiaPackageServer.addPackage(flutterRunnerArchive)) {
324
        globals.printError('Failed to add flutter_runner package to the package server');
325 326 327
        return LaunchResult.failed();
      }

328 329
      // Teach the package controller about the package server.
      if (!await fuchsiaDeviceTools.amberCtl.addRepoCfg(this, fuchsiaPackageServer)) {
330
        globals.printError('Failed to teach amber about the package server');
331 332 333 334
        return LaunchResult.failed();
      }
      serverRegistered = true;

335
      // Tell the package controller to prefetch the flutter_runner.
336 337 338 339 340 341 342 343 344 345 346 347 348
      String flutterRunnerName;
      if (debuggingOptions.buildInfo.usesAot) {
        if (debuggingOptions.buildInfo.mode.isRelease) {
          flutterRunnerName = 'flutter_aot_product_runner';
        } else {
          flutterRunnerName = 'flutter_aot_runner';
        }
      } else {
        if (debuggingOptions.buildInfo.mode.isRelease) {
          flutterRunnerName = 'flutter_jit_product_runner';
        } else {
          flutterRunnerName = 'flutter_jit_runner';
        }
349 350 351
      }
      if (!await fuchsiaDeviceTools.amberCtl.pkgCtlResolve(
          this, fuchsiaPackageServer, flutterRunnerName)) {
352
        globals.printError('Failed to get pkgctl to prefetch the flutter_runner');
353 354 355
        return LaunchResult.failed();
      }

356 357 358
      // Tell the package controller to prefetch the app.
      if (!await fuchsiaDeviceTools.amberCtl.pkgCtlResolve(
          this, fuchsiaPackageServer, appName)) {
359
        globals.printError('Failed to get pkgctl to prefetch the package');
360 361 362 363 364
        return LaunchResult.failed();
      }

      // Ensure tiles_ctl is started, and start the app.
      if (!await FuchsiaTilesCtl.ensureStarted(this)) {
365
        globals.printError('Failed to ensure that tiles is started on the device');
366 367 368 369
        return LaunchResult.failed();
      }

      // Instruct tiles_ctl to start the app.
370
      final String fuchsiaUrl = 'fuchsia-pkg://$packageServerName/$appName#meta/$appName.cmx';
371
      if (!await fuchsiaDeviceTools.tilesCtl.add(this, fuchsiaUrl, <String>[])) {
372
        globals.printError('Failed to add the app to tiles');
373 374 375
        return LaunchResult.failed();
      }
    } finally {
376 377
      // Try to un-teach the package controller about the package server if
      // needed.
378
      if (serverRegistered) {
379
        await fuchsiaDeviceTools.amberCtl.pkgCtlRepoRemove(this, fuchsiaPackageServer);
380 381
      }
      // Shutdown the package server and delete the package repo;
382
      globals.printTrace('Shutting down the tool\'s package server.');
383
      fuchsiaPackageServer?.stop();
384
      globals.printTrace('Removing the tool\'s package repo: at ${packageRepo.path}');
385 386 387
      try {
        packageRepo.deleteSync(recursive: true);
      } catch (e) {
388
        globals.printError('Failed to remove Fuchsia package repo directory '
389 390
                   'at ${packageRepo.path}: $e.');
      }
391 392 393
      status.cancel();
    }

394
    if (debuggingOptions.buildInfo.mode.isRelease) {
395
      globals.printTrace('App succesfully started in a release mode.');
396 397
      return LaunchResult.succeeded();
    }
398
    globals.printTrace('App started in a non-release mode. Setting up vmservice connection.');
399 400 401

    // In a debug or profile build, try to find the observatory uri.
    final FuchsiaIsolateDiscoveryProtocol discovery =
402
      getIsolateDiscoveryProtocol(appName);
403 404 405 406 407 408 409
    try {
      final Uri observatoryUri = await discovery.uri;
      return LaunchResult.succeeded(observatoryUri: observatoryUri);
    } finally {
      discovery.dispose();
    }
  }
410 411

  @override
412 413 414
  Future<bool> stopApp(covariant FuchsiaApp app) async {
    final int appKey = await FuchsiaTilesCtl.findAppKey(this, app.id);
    if (appKey != -1) {
415
      if (!await fuchsiaDeviceTools.tilesCtl.remove(this, appKey)) {
416
        globals.printError('tiles_ctl remove on ${app.id} failed.');
417 418 419 420
        return false;
      }
    }
    return true;
421 422
  }

423 424 425 426 427
  TargetPlatform _targetPlatform;

  Future<TargetPlatform> _queryTargetPlatform() async {
    final RunResult result = await shell('uname -m');
    if (result.exitCode != 0) {
428
      globals.printError('Could not determine Fuchsia target platform type:\n$result\n'
429 430 431 432 433 434 435 436 437 438
                 'Defaulting to arm64.');
      return TargetPlatform.fuchsia_arm64;
    }
    final String machine = result.stdout.trim();
    switch (machine) {
      case 'aarch64':
        return TargetPlatform.fuchsia_arm64;
      case 'x86_64':
        return TargetPlatform.fuchsia_x64;
      default:
439
        globals.printError('Unknown Fuchsia target platform "$machine". '
440 441 442 443 444
                   'Defaulting to arm64.');
        return TargetPlatform.fuchsia_arm64;
    }
  }

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
  @override
  bool get supportsScreenshot => isFuchsiaSupportedPlatform();

  @override
  Future<void> takeScreenshot(File outputFile) async {
    if (outputFile.basename.split('.').last != 'ppm') {
      throw '${outputFile.path} must be a .ppm file';
    }
    final RunResult screencapResult = await shell('screencap > /tmp/screenshot.ppm');
    if (screencapResult.exitCode != 0) {
      throw 'Could not take a screenshot on device $name:\n$screencapResult';
    }
    try {
      final RunResult scpResult =  await scp('/tmp/screenshot.ppm', outputFile.path);
      if (scpResult.exitCode != 0) {
        throw 'Failed to copy screenshot from device:\n$scpResult';
      }
    } finally {
      try {
        final RunResult deleteResult = await shell('rm /tmp/screenshot.ppm');
        if (deleteResult.exitCode != 0) {
          globals.printError(
            'Failed to delete screenshot.ppm from the device:\n$deleteResult'
          );
        }
      } catch (_) {
        globals.printError(
          'Failed to delete screenshot.ppm from the device'
        );
      }
    }
  }

478
  @override
479
  Future<TargetPlatform> get targetPlatform async => _targetPlatform ??= await _queryTargetPlatform();
480 481

  @override
482 483 484 485
  Future<String> get sdkNameAndVersion async {
    const String versionPath = '/pkgfs/packages/build-info/0/data/version';
    final RunResult catResult = await shell('cat $versionPath');
    if (catResult.exitCode != 0) {
486
      globals.printTrace('Failed to cat $versionPath: ${catResult.stderr}');
487 488 489 490
      return 'Fuchsia';
    }
    final String version = catResult.stdout.trim();
    if (version.isEmpty) {
491
      globals.printTrace('$versionPath was empty');
492 493 494 495
      return 'Fuchsia';
    }
    return 'Fuchsia $version';
  }
496 497

  @override
498 499
  DeviceLogReader getLogReader({ApplicationPackage app}) =>
      _logReader ??= _FuchsiaLogReader(this, app);
500
  _FuchsiaLogReader _logReader;
501 502

  @override
503 504
  DevicePortForwarder get portForwarder =>
      _portForwarder ??= _FuchsiaPortForwarder(this);
505 506 507 508 509 510
  DevicePortForwarder _portForwarder;

  @visibleForTesting
  set portForwarder(DevicePortForwarder forwarder) {
    _portForwarder = forwarder;
  }
511 512

  @override
513
  void clearLogs() {}
514

515 516 517 518
  bool _ipv6;

  /// [true] if the current host address is IPv6.
  bool get ipv6 => _ipv6 ??= isIPv6Address(id);
519

520 521
  /// List the ports currently running a dart observatory.
  Future<List<int>> servicePorts() async {
522 523 524
    const String findCommand = 'find /hub -name vmservice-port';
    final RunResult findResult = await shell(findCommand);
    if (findResult.exitCode != 0) {
525
      throwToolExit("'$findCommand' on device $name failed. stderr: '${findResult.stderr}'");
526 527 528
      return null;
    }
    final String findOutput = findResult.stdout;
529
    if (findOutput.trim() == '') {
530 531
      throwToolExit(
          'No Dart Observatories found. Are you running a debug build?');
532 533 534
      return null;
    }
    final List<int> ports = <int>[];
535
    for (final String path in findOutput.split('\n')) {
536 537 538
      if (path == '') {
        continue;
      }
539 540 541
      final String lsCommand = 'ls $path';
      final RunResult lsResult = await shell(lsCommand);
      if (lsResult.exitCode != 0) {
542
        throwToolExit("'$lsCommand' on device $name failed");
543 544 545
        return null;
      }
      final String lsOutput = lsResult.stdout;
546
      for (final String line in lsOutput.split('\n')) {
547 548 549 550 551 552 553 554 555 556
        if (line == '') {
          continue;
        }
        final int port = int.tryParse(line);
        if (port != null) {
          ports.add(port);
        }
      }
    }
    return ports;
557 558 559
  }

  /// Run `command` on the Fuchsia device shell.
560 561 562 563 564
  Future<RunResult> shell(String command) async {
    if (fuchsiaArtifacts.sshConfig == null) {
      throwToolExit('Cannot interact with device. No ssh config.\n'
                    'Try setting FUCHSIA_SSH_CONFIG or FUCHSIA_BUILD_DIR.');
    }
565
    return await processUtils.run(<String>[
566 567 568
      'ssh',
      '-F',
      fuchsiaArtifacts.sshConfig.absolute.path,
569
      id, // Device's IP address.
570
      command,
571
    ]);
572 573
  }

574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
  /// Transfer the file [origin] from the device to [destination].
  Future<RunResult> scp(String origin, String destination) async {
    if (fuchsiaArtifacts.sshConfig == null) {
      throwToolExit('Cannot interact with device. No ssh config.\n'
                    'Try setting FUCHSIA_SSH_CONFIG or FUCHSIA_BUILD_DIR.');
    }
    return await processUtils.run(<String>[
      'scp',
      '-F',
      fuchsiaArtifacts.sshConfig.absolute.path,
      '$id:$origin',
      destination,
    ]);
  }

589 590 591 592 593 594 595 596
  /// Finds the first port running a VM matching `isolateName` from the
  /// provided set of `ports`.
  ///
  /// Returns null if no isolate port can be found.
  ///
  // TODO(jonahwilliams): replacing this with the hub will require an update
  // to the flutter_runner.
  Future<int> findIsolatePort(String isolateName, List<int> ports) async {
597
    for (final int port in ports) {
598 599 600 601 602 603 604 605 606
      try {
        // Note: The square-bracket enclosure for using the IPv6 loopback
        // didn't appear to work, but when assigning to the IPv4 loopback device,
        // netstat shows that the local port is actually being used on the IPv6
        // loopback (::1).
        final Uri uri = Uri.parse('http://[$_ipv6Loopback]:$port');
        final VMService vmService = await VMService.connect(uri);
        await vmService.getVM();
        await vmService.refreshViews();
607
        for (final FlutterView flutterView in vmService.vm.views) {
608 609 610 611 612 613 614 615 616
          if (flutterView.uiIsolate == null) {
            continue;
          }
          final Uri address = flutterView.owner.vmService.httpAddress;
          if (flutterView.uiIsolate.name.contains(isolateName)) {
            return address.port;
          }
        }
      } on SocketException catch (err) {
617
        globals.printTrace('Failed to connect to $port: $err');
618 619 620 621 622
      }
    }
    throwToolExit('No ports found running $isolateName');
    return null;
  }
623

624 625 626
  FuchsiaIsolateDiscoveryProtocol getIsolateDiscoveryProtocol(String isolateName) {
    return FuchsiaIsolateDiscoveryProtocol(this, isolateName);
  }
627 628

  @override
629 630 631
  bool isSupportedForProject(FlutterProject flutterProject) {
    return flutterProject.fuchsia.existsSync();
  }
632 633 634 635 636

  @override
  Future<void> dispose() async {
    await _portForwarder?.dispose();
  }
637 638 639
}

class FuchsiaIsolateDiscoveryProtocol {
640 641 642
  FuchsiaIsolateDiscoveryProtocol(
    this._device,
    this._isolateName, [
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
    this._vmServiceConnector = _kDefaultFuchsiaIsolateDiscoveryConnector,
    this._pollOnce = false,
  ]);

  static const Duration _pollDuration = Duration(seconds: 10);
  final Map<int, VMService> _ports = <int, VMService>{};
  final FuchsiaDevice _device;
  final String _isolateName;
  final Completer<Uri> _foundUri = Completer<Uri>();
  final Future<VMService> Function(Uri) _vmServiceConnector;
  // whether to only poll once.
  final bool _pollOnce;
  Timer _pollingTimer;
  Status _status;

  FutureOr<Uri> get uri {
    if (_uri != null) {
      return _uri;
    }
662
    _status ??= globals.logger.startProgress(
663
      'Waiting for a connection from $_isolateName on ${_device.name}...',
664
      timeout: null, // could take an arbitrary amount of time
665
    );
666
    unawaited(_findIsolate());  // Completes the _foundUri Future.
667 668 669 670 671
    return _foundUri.future.then((Uri uri) {
      _uri = uri;
      return uri;
    });
  }
672

673 674 675 676 677 678 679 680 681 682 683 684 685 686
  Uri _uri;

  void dispose() {
    if (!_foundUri.isCompleted) {
      _status?.cancel();
      _status = null;
      _pollingTimer?.cancel();
      _pollingTimer = null;
      _foundUri.completeError(Exception('Did not complete'));
    }
  }

  Future<void> _findIsolate() async {
    final List<int> ports = await _device.servicePorts();
687
    for (final int port in ports) {
688 689 690 691 692 693 694 695 696 697
      VMService service;
      if (_ports.containsKey(port)) {
        service = _ports[port];
      } else {
        final int localPort = await _device.portForwarder.forward(port);
        try {
          final Uri uri = Uri.parse('http://[$_ipv6Loopback]:$localPort');
          service = await _vmServiceConnector(uri);
          _ports[port] = service;
        } on SocketException catch (err) {
698
          globals.printTrace('Failed to connect to $localPort: $err');
699 700 701 702 703
          continue;
        }
      }
      await service.getVM();
      await service.refreshViews();
704
      for (final FlutterView flutterView in service.vm.views) {
705 706 707 708 709
        if (flutterView.uiIsolate == null) {
          continue;
        }
        final Uri address = flutterView.owner.vmService.httpAddress;
        if (flutterView.uiIsolate.name.contains(_isolateName)) {
710
          _foundUri.complete(_device.ipv6
711 712
              ? Uri.parse('http://[$_ipv6Loopback]:${address.port}/')
              : Uri.parse('http://$_ipv4Loopback:${address.port}/'));
713 714 715 716 717 718 719 720 721 722 723 724
          _status.stop();
          return;
        }
      }
    }
    if (_pollOnce) {
      _foundUri.completeError(Exception('Max iterations exceeded'));
      _status.stop();
      return;
    }
    _pollingTimer = Timer(_pollDuration, _findIsolate);
  }
725 726 727 728 729 730 731 732 733
}

class _FuchsiaPortForwarder extends DevicePortForwarder {
  _FuchsiaPortForwarder(this.device);

  final FuchsiaDevice device;
  final Map<int, Process> _processes = <int, Process>{};

  @override
734
  Future<int> forward(int devicePort, {int hostPort}) async {
735
    hostPort ??= await globals.os.findFreePort();
736 737 738
    if (hostPort == 0) {
      throwToolExit('Failed to forward port $devicePort. No free host-side ports');
    }
739 740 741
    // Note: the provided command works around a bug in -N, see US-515
    // for more explanation.
    final List<String> command = <String>[
742 743 744 745 746 747 748 749 750
      'ssh',
      '-6',
      '-F',
      fuchsiaArtifacts.sshConfig.absolute.path,
      '-nNT',
      '-vvv',
      '-f',
      '-L',
      '$hostPort:$_ipv4Loopback:$devicePort',
751
      device.id, // Device's IP address.
752
      'true',
753
    ];
754
    final Process process = await globals.processManager.start(command);
755
    unawaited(process.exitCode.then((int exitCode) {
756 757 758
      if (exitCode != 0) {
        throwToolExit('Failed to forward port:$devicePort');
      }
759
    }));
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
    _processes[hostPort] = process;
    _forwardedPorts.add(ForwardedPort(hostPort, devicePort));
    return hostPort;
  }

  @override
  List<ForwardedPort> get forwardedPorts => _forwardedPorts;
  final List<ForwardedPort> _forwardedPorts = <ForwardedPort>[];

  @override
  Future<void> unforward(ForwardedPort forwardedPort) async {
    _forwardedPorts.remove(forwardedPort);
    final Process process = _processes.remove(forwardedPort.hostPort);
    process?.kill();
    final List<String> command = <String>[
775 776 777 778 779 780 781 782
      'ssh',
      '-F',
      fuchsiaArtifacts.sshConfig.absolute.path,
      '-O',
      'cancel',
      '-vvv',
      '-L',
      '${forwardedPort.hostPort}:$_ipv4Loopback:${forwardedPort.devicePort}',
783
      device.id, // Device's IP address.
784
    ];
785
    final ProcessResult result = await globals.processManager.run(command);
786
    if (result.exitCode != 0) {
787
      throwToolExit('Unforward command failed: $result');
788 789
    }
  }
790 791 792

  @override
  Future<void> dispose() async {
793 794 795
    final List<ForwardedPort> forwardedPortsCopy =
      List<ForwardedPort>.from(forwardedPorts);
    for (final ForwardedPort port in forwardedPortsCopy) {
796 797 798
      await unforward(port);
    }
  }
799
}