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

5 6
// @dart = 2.8

7 8
import 'dart:async';

9 10
import 'package:meta/meta.dart';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

155
/// Device discovery for Fuchsia devices.
156
class FuchsiaDevices extends PollingDeviceDiscovery {
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
  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;
172 173

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

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

  @override
180
  Future<List<Device>> pollingGetDevices({ Duration timeout }) async {
181
    if (!_fuchsiaWorkflow.canListDevices) {
182 183
      return <Device>[];
    }
184 185 186 187 188
    // TODO(omerlevran): Remove once soft transition is complete fxb/67602.
    final List<String> text = (await _fuchsiaSdk.listDevices(
      timeout: timeout,
      useDeviceFinder: _fuchsiaWorkflow.shouldUseDeviceFinder,
    ))?.split('\n');
189
    if (text == null || text.isEmpty) {
190 191
      return <Device>[];
    }
192 193 194 195 196 197 198 199
    final List<FuchsiaDevice> devices = <FuchsiaDevice>[];
    for (final String line in text) {
      final FuchsiaDevice device = await _parseDevice(line);
      if (device == null) {
        continue;
      }
      devices.add(device);
    }
200
    return devices;
201 202 203 204 205
  }

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

206 207
  Future<FuchsiaDevice> _parseDevice(String text) async {
    final String line = text.trim();
208
    // ['ip', 'device name']
209
    final List<String> words = line.split(' ');
210
    if (words.length < 2) {
211
      return null;
212
    }
213
    final String name = words[1];
214 215 216 217 218 219 220 221 222 223 224 225
    String resolvedHost;

    // TODO(omerlevran): Remove once soft transition is complete fxb/67602.
    if (_fuchsiaWorkflow.shouldUseDeviceFinder) {
      // TODO(omerlevran): Add support for resolve on the FuchsiaSdk Object.
      resolvedHost = await _fuchsiaSdk.fuchsiaDevFinder.resolve(
        name,
      );
    } else {
      // TODO(omerlevran): Add support for resolve on the FuchsiaSdk Object.
      resolvedHost = await _fuchsiaSdk.fuchsiaFfx.resolve(name);
    }
226
    if (resolvedHost == null) {
227 228
      _logger.printError('Failed to resolve host for Fuchsia device `$name`');
      return null;
229
    }
230
    return FuchsiaDevice(resolvedHost, name: name);
231 232 233
  }
}

234

235
class FuchsiaDevice extends Device {
236 237 238 239
  FuchsiaDevice(String id, {this.name}) : super(
      id,
      platformType: PlatformType.fuchsia,
      category: null,
240
      ephemeral: true,
241
  );
242 243

  @override
244 245 246 247
  bool get supportsHotReload => true;

  @override
  bool get supportsHotRestart => false;
248

249
  @override
250
  bool get supportsFlutterExit => false;
251

252 253 254 255
  @override
  final String name;

  @override
256
  Future<bool> get isLocalEmulator async => false;
257

258 259 260
  @override
  Future<String> get emulatorId async => null;

261 262 263 264
  @override
  bool get supportsStartPaused => false;

  @override
265 266 267 268
  Future<bool> isAppInstalled(
    ApplicationPackage app, {
    String userIdentifier,
  }) async => false;
269 270

  @override
271
  Future<bool> isLatestBuildInstalled(ApplicationPackage app) async => false;
272 273

  @override
274 275 276 277
  Future<bool> installApp(
    ApplicationPackage app, {
    String userIdentifier,
  }) => Future<bool>.value(false);
278 279

  @override
280 281 282 283
  Future<bool> uninstallApp(
    ApplicationPackage app, {
    String userIdentifier,
  }) async => false;
284 285 286 287

  @override
  bool isSupported() => true;

288 289 290
  @override
  bool supportsRuntimeMode(BuildMode buildMode) => buildMode != BuildMode.jitRelease;

291 292
  @override
  Future<LaunchResult> startApp(
293
    covariant FuchsiaApp package, {
294 295 296 297
    String mainPath,
    String route,
    DebuggingOptions debuggingOptions,
    Map<String, dynamic> platformArgs,
298 299
    bool prebuiltApplication = false,
    bool ipv6 = false,
300
    String userIdentifier,
301 302 303
  }) async {
    if (!prebuiltApplication) {
      await buildFuchsia(fuchsiaProject: FlutterProject.current().fuchsia,
304
                         targetPlatform: await targetPlatform,
305 306 307 308 309
                         target: mainPath,
                         buildInfo: debuggingOptions.buildInfo);
    }
    // Stop the app if it's currently running.
    await stopApp(package);
310
    final String host = await hostAddress;
311
    // Find out who the device thinks we are.
312
    final int port = await globals.os.findFreePort();
313
    if (port == 0) {
314
      globals.printError('Failed to find a free port');
315 316
      return LaunchResult.failed();
    }
317 318 319

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

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

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

      // Serve the application's package.
362 363 364
      final File farArchive = package.farArchive(
          debuggingOptions.buildInfo.mode);
      if (!await fuchsiaPackageServer.addPackage(farArchive)) {
365
        globals.printError('Failed to add package to the package server');
366 367 368
        return LaunchResult.failed();
      }

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

380 381
      // Teach the package controller about the package server.
      if (!await fuchsiaDeviceTools.amberCtl.addRepoCfg(this, fuchsiaPackageServer)) {
382
        globals.printError('Failed to teach amber about the package server');
383 384 385 386
        return LaunchResult.failed();
      }
      serverRegistered = true;

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

408 409 410
      // Tell the package controller to prefetch the app.
      if (!await fuchsiaDeviceTools.amberCtl.pkgCtlResolve(
          this, fuchsiaPackageServer, appName)) {
411
        globals.printError('Failed to get pkgctl to prefetch the package');
412 413 414 415 416
        return LaunchResult.failed();
      }

      // Ensure tiles_ctl is started, and start the app.
      if (!await FuchsiaTilesCtl.ensureStarted(this)) {
417
        globals.printError('Failed to ensure that tiles is started on the device');
418 419 420 421
        return LaunchResult.failed();
      }

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

446
    if (debuggingOptions.buildInfo.mode.isRelease) {
447
      globals.printTrace('App successfully started in a release mode.');
448 449
      return LaunchResult.succeeded();
    }
450
    globals.printTrace('App started in a non-release mode. Setting up vmservice connection.');
451 452 453

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

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

478 479 480
  TargetPlatform _targetPlatform;

  Future<TargetPlatform> _queryTargetPlatform() async {
481 482 483 484 485 486 487
    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;
    }
488 489
    final RunResult result = await shell('uname -m');
    if (result.exitCode != 0) {
490
      globals.printError('Could not determine Fuchsia target platform type:\n$result\n'
491
                 'Defaulting to arm64.');
492
      return defaultTargetPlatform;
493 494 495 496 497 498 499 500
    }
    final String machine = result.stdout.trim();
    switch (machine) {
      case 'aarch64':
        return TargetPlatform.fuchsia_arm64;
      case 'x86_64':
        return TargetPlatform.fuchsia_x64;
      default:
501
        globals.printError('Unknown Fuchsia target platform "$machine". '
502
                   'Defaulting to arm64.');
503
        return defaultTargetPlatform;
504 505 506
    }
  }

507
  @override
508
  bool get supportsScreenshot => isFuchsiaSupportedPlatform(globals.platform);
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531

  @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'
          );
        }
532
      } on Exception catch (e) {
533
        globals.printError(
534
          'Failed to delete screenshot.ppm from the device: $e'
535 536 537 538 539
        );
      }
    }
  }

540
  @override
541
  Future<TargetPlatform> get targetPlatform async => _targetPlatform ??= await _queryTargetPlatform();
542 543

  @override
544
  Future<String> get sdkNameAndVersion async {
545 546 547 548 549 550
    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;
    }
551 552 553
    const String versionPath = '/pkgfs/packages/build-info/0/data/version';
    final RunResult catResult = await shell('cat $versionPath');
    if (catResult.exitCode != 0) {
554
      globals.printTrace('Failed to cat $versionPath: ${catResult.stderr}');
555
      return defaultName;
556 557 558
    }
    final String version = catResult.stdout.trim();
    if (version.isEmpty) {
559
      globals.printTrace('$versionPath was empty');
560
      return defaultName;
561 562 563
    }
    return 'Fuchsia $version';
  }
564 565

  @override
566 567 568 569 570
  DeviceLogReader getLogReader({
    ApplicationPackage app,
    bool includePastLogs = false,
  }) {
    assert(!includePastLogs, 'Past log reading not supported on Fuchsia.');
571
    return _logReader ??= _FuchsiaLogReader(this, globals.systemClock, app);
572
  }
573
  _FuchsiaLogReader _logReader;
574 575

  @override
576 577
  DevicePortForwarder get portForwarder =>
      _portForwarder ??= _FuchsiaPortForwarder(this);
578 579 580 581 582 583
  DevicePortForwarder _portForwarder;

  @visibleForTesting
  set portForwarder(DevicePortForwarder forwarder) {
    _portForwarder = forwarder;
  }
584 585

  @override
586
  void clearLogs() {}
587

588 589 590 591
  bool _ipv6;

  /// [true] if the current host address is IPv6.
  bool get ipv6 => _ipv6 ??= isIPv6Address(id);
592 593 594 595 596 597 598

  /// Return the address that the device should use to communicate with the
  /// host.
  Future<String> get hostAddress async {
    if (_cachedHostAddress != null) {
      return _cachedHostAddress;
    }
599
    final RunResult result = await shell(r'echo $SSH_CONNECTION');
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
    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;
618

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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