fuchsia_device.dart 28.1 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
import 'package:meta/meta.dart';
8
import 'package:vm_service/vm_service.dart' as vm_service;
9

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

27 28 29 30
import 'amber_ctl.dart';
import 'application_package.dart';
import 'fuchsia_build.dart';
import 'fuchsia_pm.dart';
31 32
import 'fuchsia_sdk.dart';
import 'fuchsia_workflow.dart';
33 34 35 36 37 38 39 40 41 42 43 44 45 46
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();
}

47 48 49
final String _ipv4Loopback = InternetAddress.loopbackIPv4.address;
final String _ipv6Loopback = InternetAddress.loopbackIPv6.address;

50
// Enables testing the fuchsia isolate discovery
51 52
Future<vm_service.VmService> _kDefaultFuchsiaIsolateDiscoveryConnector(Uri uri) {
  return connectToVmService(uri);
53 54
}

55 56 57
Future<void> _kDefaultDartDevelopmentServiceStarter(
  Device device,
  Uri observatoryUri,
58
  bool disableServiceAuthCodes,
59
) async {
60 61 62 63 64 65
  await device.dds.startDartDevelopmentService(
    observatoryUri,
    0,
    true,
    disableServiceAuthCodes,
  );
66 67
}

68 69
/// Read the log for a particular device.
class _FuchsiaLogReader extends DeviceLogReader {
70
  _FuchsiaLogReader(this._device, this._systemClock, [this._app]);
71

72 73
  // \S matches non-whitespace characters.
  static final RegExp _flutterLogOutput = RegExp(r'INFO: \S+\(flutter\): ');
74

75 76
  final FuchsiaDevice _device;
  final ApplicationPackage _app;
77
  final SystemClock _systemClock;
78

79 80
  @override
  String get name => _device.name;
81 82 83 84

  Stream<String> _logLines;
  @override
  Stream<String> get logLines {
85 86
    final Stream<String> logStream = fuchsiaSdk.syslogs(_device.id);
    _logLines ??= _processLogs(logStream);
87 88 89
    return _logLines;
  }

90
  Stream<String> _processLogs(Stream<String> lines) {
91 92 93
    if (lines == null) {
      return null;
    }
94 95
    // Get the starting time of the log processor to filter logs from before
    // the process attached.
96
    final DateTime startTime = _systemClock.now();
97 98 99
    // Determine if line comes from flutter, and optionally whether it matches
    // the correct fuchsia module.
    final RegExp matchRegExp = _app == null
100
        ? _flutterLogOutput
101
        : RegExp('INFO: ${_app.name}(\\.cmx)?\\(flutter\\): ');
102 103
    return Stream<String>.eventTransformed(
      lines,
104
      (EventSink<String> output) => _FuchsiaLogSink(output, matchRegExp, startTime),
105
    );
106 107
  }

108 109
  @override
  String toString() => name;
110 111 112 113 114 115

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

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
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;
    }
139 140
    _outputSink.add(
        '[${logTime.toLocal()}] Flutter: ${line.split(_matchRegExp).last}');
141 142 143
  }

  @override
144
  void addError(Object error, [StackTrace stackTrace]) {
145 146 147 148
    _outputSink.addError(error, stackTrace);
  }

  @override
149 150 151
  void close() {
    _outputSink.close();
  }
152 153
}

154
/// Device discovery for Fuchsia devices.
155
class FuchsiaDevices extends PollingDeviceDiscovery {
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
  FuchsiaDevices({
    @required Platform platform,
    @required FuchsiaWorkflow fuchsiaWorkflow,
    @required FuchsiaSdk fuchsiaSdk,
    @required Logger logger,
  }) : _platform = platform,
       _fuchsiaWorkflow = fuchsiaWorkflow,
       _fuchsiaSdk = fuchsiaSdk,
       _logger = logger,
       super('Fuchsia devices');

  final Platform _platform;
  final FuchsiaWorkflow _fuchsiaWorkflow;
  final FuchsiaSdk _fuchsiaSdk;
  final Logger _logger;
171 172

  @override
173
  bool get supportsPlatform => isFuchsiaSupportedPlatform(_platform);
174 175

  @override
176
  bool get canListAnything => _fuchsiaWorkflow.canListDevices;
177 178

  @override
179
  Future<List<Device>> pollingGetDevices({ Duration timeout }) async {
180
    if (!_fuchsiaWorkflow.canListDevices) {
181 182
      return <Device>[];
    }
183 184
    final List<String> text = (await _fuchsiaSdk.listDevices(timeout: timeout))
      ?.split('\n');
185
    if (text == null || text.isEmpty) {
186 187
      return <Device>[];
    }
188 189 190 191 192 193 194 195
    final List<FuchsiaDevice> devices = <FuchsiaDevice>[];
    for (final String line in text) {
      final FuchsiaDevice device = await _parseDevice(line);
      if (device == null) {
        continue;
      }
      devices.add(device);
    }
196
    return devices;
197 198 199 200 201
  }

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

202 203
  Future<FuchsiaDevice> _parseDevice(String text) async {
    final String line = text.trim();
204
    // ['ip', 'device name']
205
    final List<String> words = line.split(' ');
206
    if (words.length < 2) {
207
      return null;
208
    }
209
    final String name = words[1];
210
    final String resolvedHost = await _fuchsiaSdk.fuchsiaDevFinder.resolve(
211 212 213 214
      name,
      local: false,
    );
    if (resolvedHost == null) {
215 216
      _logger.printError('Failed to resolve host for Fuchsia device `$name`');
      return null;
217
    }
218
    return FuchsiaDevice(resolvedHost, name: name);
219 220 221
  }
}

222

223
class FuchsiaDevice extends Device {
224 225 226 227
  FuchsiaDevice(String id, {this.name}) : super(
      id,
      platformType: PlatformType.fuchsia,
      category: null,
228
      ephemeral: true,
229
  );
230 231

  @override
232 233 234 235
  bool get supportsHotReload => true;

  @override
  bool get supportsHotRestart => false;
236

237
  @override
238
  bool get supportsFlutterExit => false;
239

240 241 242 243
  @override
  final String name;

  @override
244
  Future<bool> get isLocalEmulator async => false;
245

246 247 248
  @override
  Future<String> get emulatorId async => null;

249 250 251 252
  @override
  bool get supportsStartPaused => false;

  @override
253 254 255 256
  Future<bool> isAppInstalled(
    ApplicationPackage app, {
    String userIdentifier,
  }) async => false;
257 258

  @override
259
  Future<bool> isLatestBuildInstalled(ApplicationPackage app) async => false;
260 261

  @override
262 263 264 265
  Future<bool> installApp(
    ApplicationPackage app, {
    String userIdentifier,
  }) => Future<bool>.value(false);
266 267

  @override
268 269 270 271
  Future<bool> uninstallApp(
    ApplicationPackage app, {
    String userIdentifier,
  }) async => false;
272 273 274 275

  @override
  bool isSupported() => true;

276 277 278
  @override
  bool supportsRuntimeMode(BuildMode buildMode) => buildMode != BuildMode.jitRelease;

279 280
  @override
  Future<LaunchResult> startApp(
281
    covariant FuchsiaApp package, {
282 283 284 285
    String mainPath,
    String route,
    DebuggingOptions debuggingOptions,
    Map<String, dynamic> platformArgs,
286 287
    bool prebuiltApplication = false,
    bool ipv6 = false,
288
    String userIdentifier,
289 290 291
  }) async {
    if (!prebuiltApplication) {
      await buildFuchsia(fuchsiaProject: FlutterProject.current().fuchsia,
292
                         targetPlatform: await targetPlatform,
293 294 295 296 297
                         target: mainPath,
                         buildInfo: debuggingOptions.buildInfo);
    }
    // Stop the app if it's currently running.
    await stopApp(package);
298 299 300 301
    final String host = await fuchsiaSdk.fuchsiaDevFinder.resolve(
      name,
      local: true,
    );
302
    if (host == null) {
303
      globals.printError('Failed to resolve host for Fuchsia device');
304 305
      return LaunchResult.failed();
    }
306
    // Find out who the device thinks we are.
307
    final int port = await globals.os.findFreePort();
308
    if (port == 0) {
309
      globals.printError('Failed to find a free port');
310 311
      return LaunchResult.failed();
    }
312 313 314

    // Try Start with a fresh package repo in case one was left over from a
    // previous run.
315
    final Directory packageRepo =
316
        globals.fs.directory(globals.fs.path.join(getFuchsiaBuildDirectory(), '.pkg-repo'));
317 318 319 320 321
    try {
      if (packageRepo.existsSync()) {
        packageRepo.deleteSync(recursive: true);
      }
      packageRepo.createSync(recursive: true);
322
    } on Exception catch (e) {
323
      globals.printError('Failed to create Fuchsia package repo directory '
324 325 326
                 'at ${packageRepo.path}: $e');
      return LaunchResult.failed();
    }
327 328

    final String appName = FlutterProject.current().manifest.appName;
329
    final Status status = globals.logger.startProgress(
330
      'Starting Fuchsia application $appName...',
331 332 333 334
    );
    FuchsiaPackageServer fuchsiaPackageServer;
    bool serverRegistered = false;
    try {
335 336 337 338
      // 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')) {
339
        globals.printError('Failed to get amber to prefetch tiles');
340 341 342
        return LaunchResult.failed();
      }
      if (!await fuchsiaDeviceTools.amberCtl.getUp(this, 'tiles_ctl')) {
343
        globals.printError('Failed to get amber to prefetch tiles_ctl');
344 345 346
        return LaunchResult.failed();
      }

347
      // Start up a package server.
348
      const String packageServerName = FuchsiaPackageServer.toolHost;
349 350
      fuchsiaPackageServer = FuchsiaPackageServer(
          packageRepo.path, packageServerName, host, port);
351
      if (!await fuchsiaPackageServer.start()) {
352
        globals.printError('Failed to start the Fuchsia package server');
353 354
        return LaunchResult.failed();
      }
355 356

      // Serve the application's package.
357 358 359
      final File farArchive = package.farArchive(
          debuggingOptions.buildInfo.mode);
      if (!await fuchsiaPackageServer.addPackage(farArchive)) {
360
        globals.printError('Failed to add package to the package server');
361 362 363
        return LaunchResult.failed();
      }

364
      // Serve the flutter_runner.
365
      final File flutterRunnerArchive = globals.fs.file(globals.artifacts.getArtifactPath(
366
        Artifact.fuchsiaFlutterRunner,
367 368 369 370
        platform: await targetPlatform,
        mode: debuggingOptions.buildInfo.mode,
      ));
      if (!await fuchsiaPackageServer.addPackage(flutterRunnerArchive)) {
371
        globals.printError('Failed to add flutter_runner package to the package server');
372 373 374
        return LaunchResult.failed();
      }

375 376
      // Teach the package controller about the package server.
      if (!await fuchsiaDeviceTools.amberCtl.addRepoCfg(this, fuchsiaPackageServer)) {
377
        globals.printError('Failed to teach amber about the package server');
378 379 380 381
        return LaunchResult.failed();
      }
      serverRegistered = true;

382
      // Tell the package controller to prefetch the flutter_runner.
383 384 385 386 387 388 389 390 391 392 393 394 395
      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';
        }
396 397 398
      }
      if (!await fuchsiaDeviceTools.amberCtl.pkgCtlResolve(
          this, fuchsiaPackageServer, flutterRunnerName)) {
399
        globals.printError('Failed to get pkgctl to prefetch the flutter_runner');
400 401 402
        return LaunchResult.failed();
      }

403 404 405
      // Tell the package controller to prefetch the app.
      if (!await fuchsiaDeviceTools.amberCtl.pkgCtlResolve(
          this, fuchsiaPackageServer, appName)) {
406
        globals.printError('Failed to get pkgctl to prefetch the package');
407 408 409 410 411
        return LaunchResult.failed();
      }

      // Ensure tiles_ctl is started, and start the app.
      if (!await FuchsiaTilesCtl.ensureStarted(this)) {
412
        globals.printError('Failed to ensure that tiles is started on the device');
413 414 415 416
        return LaunchResult.failed();
      }

      // Instruct tiles_ctl to start the app.
417
      final String fuchsiaUrl = 'fuchsia-pkg://$packageServerName/$appName#meta/$appName.cmx';
418
      if (!await fuchsiaDeviceTools.tilesCtl.add(this, fuchsiaUrl, <String>[])) {
419
        globals.printError('Failed to add the app to tiles');
420 421 422
        return LaunchResult.failed();
      }
    } finally {
423 424
      // Try to un-teach the package controller about the package server if
      // needed.
425
      if (serverRegistered) {
426
        await fuchsiaDeviceTools.amberCtl.pkgCtlRepoRemove(this, fuchsiaPackageServer);
427 428
      }
      // Shutdown the package server and delete the package repo;
429
      globals.printTrace("Shutting down the tool's package server.");
430
      fuchsiaPackageServer?.stop();
431
      globals.printTrace("Removing the tool's package repo: at ${packageRepo.path}");
432 433
      try {
        packageRepo.deleteSync(recursive: true);
434
      } on Exception catch (e) {
435
        globals.printError('Failed to remove Fuchsia package repo directory '
436 437
                   'at ${packageRepo.path}: $e.');
      }
438 439 440
      status.cancel();
    }

441
    if (debuggingOptions.buildInfo.mode.isRelease) {
442
      globals.printTrace('App successfully started in a release mode.');
443 444
      return LaunchResult.succeeded();
    }
445
    globals.printTrace('App started in a non-release mode. Setting up vmservice connection.');
446 447 448

    // In a debug or profile build, try to find the observatory uri.
    final FuchsiaIsolateDiscoveryProtocol discovery =
449
      getIsolateDiscoveryProtocol(appName);
450 451 452 453 454 455 456
    try {
      final Uri observatoryUri = await discovery.uri;
      return LaunchResult.succeeded(observatoryUri: observatoryUri);
    } finally {
      discovery.dispose();
    }
  }
457 458

  @override
459 460 461 462
  Future<bool> stopApp(
    covariant FuchsiaApp app, {
    String userIdentifier,
  }) async {
463 464
    final int appKey = await FuchsiaTilesCtl.findAppKey(this, app.id);
    if (appKey != -1) {
465
      if (!await fuchsiaDeviceTools.tilesCtl.remove(this, appKey)) {
466
        globals.printError('tiles_ctl remove on ${app.id} failed.');
467 468 469 470
        return false;
      }
    }
    return true;
471 472
  }

473 474 475
  TargetPlatform _targetPlatform;

  Future<TargetPlatform> _queryTargetPlatform() async {
476 477 478 479 480 481 482
    const TargetPlatform defaultTargetPlatform = TargetPlatform.fuchsia_arm64;
    if (!globals.fuchsiaArtifacts.hasSshConfig) {
      globals.printTrace('Could not determine Fuchsia target platform because '
                 'Fuchsia ssh configuration is missing.\n'
                 'Defaulting to arm64.');
      return defaultTargetPlatform;
    }
483 484
    final RunResult result = await shell('uname -m');
    if (result.exitCode != 0) {
485
      globals.printError('Could not determine Fuchsia target platform type:\n$result\n'
486
                 'Defaulting to arm64.');
487
      return defaultTargetPlatform;
488 489 490 491 492 493 494 495
    }
    final String machine = result.stdout.trim();
    switch (machine) {
      case 'aarch64':
        return TargetPlatform.fuchsia_arm64;
      case 'x86_64':
        return TargetPlatform.fuchsia_x64;
      default:
496
        globals.printError('Unknown Fuchsia target platform "$machine". '
497
                   'Defaulting to arm64.');
498
        return defaultTargetPlatform;
499 500 501
    }
  }

502
  @override
503
  bool get supportsScreenshot => isFuchsiaSupportedPlatform(globals.platform);
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526

  @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'
          );
        }
527
      } on Exception catch (e) {
528
        globals.printError(
529
          'Failed to delete screenshot.ppm from the device: $e'
530 531 532 533 534
        );
      }
    }
  }

535
  @override
536
  Future<TargetPlatform> get targetPlatform async => _targetPlatform ??= await _queryTargetPlatform();
537 538

  @override
539
  Future<String> get sdkNameAndVersion async {
540 541 542 543 544 545
    const String defaultName = 'Fuchsia';
    if (!globals.fuchsiaArtifacts.hasSshConfig) {
      globals.printTrace('Could not determine Fuchsia sdk name or version '
                 'because Fuchsia ssh configuration is missing.');
      return defaultName;
    }
546 547 548
    const String versionPath = '/pkgfs/packages/build-info/0/data/version';
    final RunResult catResult = await shell('cat $versionPath');
    if (catResult.exitCode != 0) {
549
      globals.printTrace('Failed to cat $versionPath: ${catResult.stderr}');
550
      return defaultName;
551 552 553
    }
    final String version = catResult.stdout.trim();
    if (version.isEmpty) {
554
      globals.printTrace('$versionPath was empty');
555
      return defaultName;
556 557 558
    }
    return 'Fuchsia $version';
  }
559 560

  @override
561 562 563 564 565
  DeviceLogReader getLogReader({
    ApplicationPackage app,
    bool includePastLogs = false,
  }) {
    assert(!includePastLogs, 'Past log reading not supported on Fuchsia.');
566
    return _logReader ??= _FuchsiaLogReader(this, globals.systemClock, app);
567
  }
568
  _FuchsiaLogReader _logReader;
569 570

  @override
571 572
  DevicePortForwarder get portForwarder =>
      _portForwarder ??= _FuchsiaPortForwarder(this);
573 574 575 576 577 578
  DevicePortForwarder _portForwarder;

  @visibleForTesting
  set portForwarder(DevicePortForwarder forwarder) {
    _portForwarder = forwarder;
  }
579 580

  @override
581
  void clearLogs() {}
582

583 584 585 586
  bool _ipv6;

  /// [true] if the current host address is IPv6.
  bool get ipv6 => _ipv6 ??= isIPv6Address(id);
587 588 589 590 591 592 593

  /// Return the address that the device should use to communicate with the
  /// host.
  Future<String> get hostAddress async {
    if (_cachedHostAddress != null) {
      return _cachedHostAddress;
    }
594
    final RunResult result = await shell(r'echo $SSH_CONNECTION');
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
    void fail() {
      throwToolExit('Failed to get local address, aborting.\n$result');
    }
    if (result.exitCode != 0) {
      fail();
    }
    final List<String> splitResult = result.stdout.split(' ');
    if (splitResult.isEmpty) {
      fail();
    }
    final String addr = splitResult[0].replaceAll('%', '%25');
    if (addr.isEmpty) {
      fail();
    }
    return _cachedHostAddress = addr;
  }

  String _cachedHostAddress;
613

614 615
  /// List the ports currently running a dart observatory.
  Future<List<int>> servicePorts() async {
616 617 618
    const String findCommand = 'find /hub -name vmservice-port';
    final RunResult findResult = await shell(findCommand);
    if (findResult.exitCode != 0) {
619
      throwToolExit("'$findCommand' on device $name failed. stderr: '${findResult.stderr}'");
620 621 622
      return null;
    }
    final String findOutput = findResult.stdout;
623
    if (findOutput.trim() == '') {
624 625
      throwToolExit(
          'No Dart Observatories found. Are you running a debug build?');
626 627 628
      return null;
    }
    final List<int> ports = <int>[];
629
    for (final String path in findOutput.split('\n')) {
630 631 632
      if (path == '') {
        continue;
      }
633 634 635
      final String lsCommand = 'ls $path';
      final RunResult lsResult = await shell(lsCommand);
      if (lsResult.exitCode != 0) {
636
        throwToolExit("'$lsCommand' on device $name failed");
637 638 639
        return null;
      }
      final String lsOutput = lsResult.stdout;
640
      for (final String line in lsOutput.split('\n')) {
641 642 643 644 645 646 647 648 649 650
        if (line == '') {
          continue;
        }
        final int port = int.tryParse(line);
        if (port != null) {
          ports.add(port);
        }
      }
    }
    return ports;
651 652 653
  }

  /// Run `command` on the Fuchsia device shell.
654
  Future<RunResult> shell(String command) async {
655
    if (globals.fuchsiaArtifacts.sshConfig == null) {
656 657 658
      throwToolExit('Cannot interact with device. No ssh config.\n'
                    'Try setting FUCHSIA_SSH_CONFIG or FUCHSIA_BUILD_DIR.');
    }
659
    return await globals.processUtils.run(<String>[
660 661
      'ssh',
      '-F',
662
      globals.fuchsiaArtifacts.sshConfig.absolute.path,
663
      id, // Device's IP address.
664
      command,
665
    ]);
666 667
  }

668 669
  /// Transfer the file [origin] from the device to [destination].
  Future<RunResult> scp(String origin, String destination) async {
670
    if (globals.fuchsiaArtifacts.sshConfig == null) {
671 672 673
      throwToolExit('Cannot interact with device. No ssh config.\n'
                    'Try setting FUCHSIA_SSH_CONFIG or FUCHSIA_BUILD_DIR.');
    }
674
    return await globals.processUtils.run(<String>[
675 676
      'scp',
      '-F',
677
      globals.fuchsiaArtifacts.sshConfig.absolute.path,
678 679 680 681 682
      '$id:$origin',
      destination,
    ]);
  }

683 684 685 686 687 688 689 690
  /// 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 {
691
    for (final int port in ports) {
692 693 694 695 696 697
      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');
698
        final vm_service.VmService vmService = await connectToVmService(uri);
699 700
        final List<FlutterView> flutterViews = await vmService.getFlutterViews();
        for (final FlutterView flutterView in flutterViews) {
701 702 703 704
          if (flutterView.uiIsolate == null) {
            continue;
          }
          if (flutterView.uiIsolate.name.contains(isolateName)) {
705
            return vmService.httpAddress.port;
706 707 708
          }
        }
      } on SocketException catch (err) {
709
        globals.printTrace('Failed to connect to $port: $err');
710 711 712 713 714
      }
    }
    throwToolExit('No ports found running $isolateName');
    return null;
  }
715

716 717 718
  FuchsiaIsolateDiscoveryProtocol getIsolateDiscoveryProtocol(String isolateName) {
    return FuchsiaIsolateDiscoveryProtocol(this, isolateName);
  }
719 720

  @override
721 722 723
  bool isSupportedForProject(FlutterProject flutterProject) {
    return flutterProject.fuchsia.existsSync();
  }
724 725 726 727 728

  @override
  Future<void> dispose() async {
    await _portForwarder?.dispose();
  }
729 730 731
}

class FuchsiaIsolateDiscoveryProtocol {
732 733 734
  FuchsiaIsolateDiscoveryProtocol(
    this._device,
    this._isolateName, [
735
    this._vmServiceConnector = _kDefaultFuchsiaIsolateDiscoveryConnector,
736
    this._ddsStarter = _kDefaultDartDevelopmentServiceStarter,
737 738 739 740
    this._pollOnce = false,
  ]);

  static const Duration _pollDuration = Duration(seconds: 10);
741
  final Map<int, vm_service.VmService> _ports = <int, vm_service.VmService>{};
742 743 744
  final FuchsiaDevice _device;
  final String _isolateName;
  final Completer<Uri> _foundUri = Completer<Uri>();
745
  final Future<vm_service.VmService> Function(Uri) _vmServiceConnector;
746
  final Future<void> Function(Device, Uri, bool) _ddsStarter;
747 748 749 750 751 752 753 754 755
  // whether to only poll once.
  final bool _pollOnce;
  Timer _pollingTimer;
  Status _status;

  FutureOr<Uri> get uri {
    if (_uri != null) {
      return _uri;
    }
756
    _status ??= globals.logger.startProgress(
757 758
      'Waiting for a connection from $_isolateName on ${_device.name}...',
    );
759
    unawaited(_findIsolate());  // Completes the _foundUri Future.
760 761 762 763 764
    return _foundUri.future.then((Uri uri) {
      _uri = uri;
      return uri;
    });
  }
765

766 767 768 769 770 771 772 773 774 775 776 777 778 779
  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();
780
    for (final int port in ports) {
781
      vm_service.VmService service;
782 783 784 785 786 787
      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');
788 789
          await _ddsStarter(_device, uri, true);
          service = await _vmServiceConnector(_device.dds.uri);
790 791
          _ports[port] = service;
        } on SocketException catch (err) {
792
          globals.printTrace('Failed to connect to $localPort: $err');
793 794 795
          continue;
        }
      }
796 797
      final List<FlutterView> flutterViews = await service.getFlutterViews();
      for (final FlutterView flutterView in flutterViews) {
798 799 800 801
        if (flutterView.uiIsolate == null) {
          continue;
        }
        if (flutterView.uiIsolate.name.contains(_isolateName)) {
802
          _foundUri.complete(_device.ipv6
803 804
              ? Uri.parse('http://[$_ipv6Loopback]:${service.httpAddress.port}/')
              : Uri.parse('http://$_ipv4Loopback:${service.httpAddress.port}/'));
805 806 807 808 809 810 811 812 813 814 815 816
          _status.stop();
          return;
        }
      }
    }
    if (_pollOnce) {
      _foundUri.completeError(Exception('Max iterations exceeded'));
      _status.stop();
      return;
    }
    _pollingTimer = Timer(_pollDuration, _findIsolate);
  }
817 818 819 820 821 822 823 824 825
}

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

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

  @override
826
  Future<int> forward(int devicePort, {int hostPort}) async {
827
    hostPort ??= await globals.os.findFreePort();
828 829 830
    if (hostPort == 0) {
      throwToolExit('Failed to forward port $devicePort. No free host-side ports');
    }
831 832 833
    // Note: the provided command works around a bug in -N, see US-515
    // for more explanation.
    final List<String> command = <String>[
834 835 836
      'ssh',
      '-6',
      '-F',
837
      globals.fuchsiaArtifacts.sshConfig.absolute.path,
838 839 840 841 842
      '-nNT',
      '-vvv',
      '-f',
      '-L',
      '$hostPort:$_ipv4Loopback:$devicePort',
843
      device.id, // Device's IP address.
844
      'true',
845
    ];
846
    final Process process = await globals.processManager.start(command);
847
    unawaited(process.exitCode.then((int exitCode) {
848 849 850
      if (exitCode != 0) {
        throwToolExit('Failed to forward port:$devicePort');
      }
851
    }));
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
    _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>[
867 868
      'ssh',
      '-F',
869
      globals.fuchsiaArtifacts.sshConfig.absolute.path,
870 871 872 873 874
      '-O',
      'cancel',
      '-vvv',
      '-L',
      '${forwardedPort.hostPort}:$_ipv4Loopback:${forwardedPort.devicePort}',
875
      device.id, // Device's IP address.
876
    ];
877
    final ProcessResult result = await globals.processManager.run(command);
878
    if (result.exitCode != 0) {
879 880 881 882 883
      throwToolExit(
        'Unforward command failed:\n'
        'stdout: ${result.stdout}\n'
        'stderr: ${result.stderr}'
      );
884 885
    }
  }
886 887 888

  @override
  Future<void> dispose() async {
889
    final List<ForwardedPort> forwardedPortsCopy =
890
      List<ForwardedPort>.of(forwardedPorts);
891
    for (final ForwardedPort port in forwardedPortsCopy) {
892 893 894
      await unforward(port);
    }
  }
895
}