fuchsia_reload.dart 9.32 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:math';

import '../base/common.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/platform.dart';
12
import '../cache.dart';
13 14 15 16 17 18
import '../device.dart';
import '../flx.dart' as flx;
import '../fuchsia/fuchsia_device.dart';
import '../globals.dart';
import '../run_hot.dart';
import '../runner/flutter_command.dart';
19
import '../vmservice.dart';
20 21 22 23 24 25 26 27 28 29 30

// Usage:
// With e.g. flutter_gallery already running, a HotRunner can be attached to it
// with:
// $ flutter fuchsia_reload -f ~/fuchsia -a 192.168.1.39 \
//       -g //lib/flutter/examples/flutter_gallery:flutter_gallery

class FuchsiaReloadCommand extends FlutterCommand {
  String _fuchsiaRoot;
  String _projectRoot;
  String _projectName;
31
  String _binaryName;
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
  String _fuchsiaProjectPath;
  String _target;
  String _address;
  String _dotPackagesPath;

  @override
  final String name = 'fuchsia_reload';

  @override
  final String description = 'Hot reload on Fuchsia.';

  FuchsiaReloadCommand() {
    addBuildModeFlags(defaultToRelease: false);
    argParser.addOption('address',
      abbr: 'a',
      help: 'Fuchsia device network name or address.');
    argParser.addOption('build-type',
      abbr: 'b',
      defaultsTo: 'release-x86-64',
      help: 'Fuchsia build type, e.g. release-x86-64.');
    argParser.addOption('fuchsia-root',
      abbr: 'f',
      defaultsTo: platform.environment['FUCHSIA_ROOT'],
      help: 'Path to Fuchsia source tree.');
    argParser.addOption('gn-target',
      abbr: 'g',
      help: 'GN target of the application, e.g //path/to/app:app');
59 60 61
    argParser.addOption('name-override',
      abbr: 'n',
      help: 'On-device name of the application binary');
62 63 64 65 66 67 68 69 70
    argParser.addOption('target',
      abbr: 't',
      defaultsTo: flx.defaultMainPath,
      help: 'Target app path / main entry-point file. '
            'Relative to --gn-target path, e.g. lib/main.dart');
  }

  @override
  Future<Null> runCommand() async {
71 72
    Cache.releaseLockEarly();

73 74 75 76 77 78 79 80
    _validateArguments();

    // Find the network ports used on the device by VM service instances.
    final List<int> servicePorts = await _getServicePorts();
    if (servicePorts.length == 0) {
      throwToolExit("Couldn't find any running Observatory instances.");
    }
    for (int port in servicePorts) {
81
      printTrace("Fuchsia service port: $port");
82 83
    }

84
    // Check that there are running VM services on the returned
85
    // ports, and find the Isolates that are running the target app.
86
    final String isolateName = "$_binaryName\$main";
87 88
    final List<int> targetPorts = await _filterPorts(servicePorts, isolateName);
    if (targetPorts.length == 0) {
89
      throwToolExit("No VMs found running $_binaryName");
90 91
    }
    for (int port in targetPorts) {
92
      printTrace("Found $_binaryName at $port");
93
    }
94 95 96

    // Set up a device and hot runner and attach the hot runner to the first
    // vm service we found.
97 98 99
    final int firstPort = targetPorts[0];
    final String fullAddress = "$_address:$firstPort";
    final FuchsiaDevice device = new FuchsiaDevice(fullAddress);
100 101 102 103 104 105
    final HotRunner hotRunner = new HotRunner(
        device,
        debuggingOptions: new DebuggingOptions.enabled(getBuildMode()),
        target: _target,
        projectRootPath: _fuchsiaProjectPath,
        packagesFilePath: _dotPackagesPath);
106
    final Uri observatoryUri = Uri.parse("http://$fullAddress");
107
    printStatus("Connecting to $_binaryName at $observatoryUri");
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    await hotRunner.attach(observatoryUri, isolateFilter: isolateName);
  }

  // Find ports where there is a view isolate with the given name
  Future<List<int>> _filterPorts(List<int> ports, String isolateFilter) async {
    final List<int> result = new List<int>();
    for (int port in ports) {
      final String addr = "http://$_address:$port";
      final Uri uri = Uri.parse(addr);
      final VMService vmService = VMService.connect(uri);
      await vmService.getVM();
      await vmService.waitForViews();
      if (vmService.vm.firstView == null) {
        printTrace("Found no views at $addr");
        continue;
      }
      for (FlutterView v in vmService.vm.views) {
        printTrace("At $addr, found view: ${v.uiIsolate.name}");
        if (v.uiIsolate.name.indexOf(isolateFilter) == 0) {
          result.add(port);
        }
      }
    }
    return result;
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
  }

  void _validateArguments() {
    _fuchsiaRoot = argResults['fuchsia-root'];
    if (_fuchsiaRoot == null) {
      throwToolExit(
          "Please give the location of the Fuchsia tree with --fuchsia-root");
    }
    if (!_directoryExists(_fuchsiaRoot)) {
      throwToolExit("Specified --fuchsia-root '$_fuchsiaRoot' does not exist");
    }

    _address = argResults['address'];
    if (_address == null) {
      throwToolExit(
          "Give the address of the device running Fuchsia with --address");
    }

    final List<String> gnTarget = _extractPathAndName(argResults['gn-target']);
    _projectRoot = gnTarget[0];
    _projectName = gnTarget[1];
    _fuchsiaProjectPath = "$_fuchsiaRoot/$_projectRoot";
    if (!_directoryExists(_fuchsiaProjectPath)) {
      throwToolExit(
          "Target does not exist in the Fuchsia tree: $_fuchsiaProjectPath");
    }

    final String relativeTarget = argResults['target'];
    if (relativeTarget == null) {
      throwToolExit('Give the application entry point with --target');
    }
    _target = "$_fuchsiaProjectPath/$relativeTarget";
    if (!_fileExists(_target)) {
      throwToolExit("Couldn't find application entry point at $_target");
    }

    final String buildType = argResults['build-type'];
    if (buildType == null) {
      throwToolExit("Give the build type with --build-type");
    }
    final String packagesFileName = "${_projectName}_dart_package.packages";
    _dotPackagesPath =
        "$_fuchsiaRoot/out/$buildType/gen/$_projectRoot/$packagesFileName";
    if (!_fileExists(_dotPackagesPath)) {
      throwToolExit("Couldn't find .packages file at $_dotPackagesPath");
    }
178 179 180 181 182 183 184

    final String nameOverride = argResults['name-override'];
    if (nameOverride == null) {
      _binaryName = _projectName;
    } else {
      _binaryName = nameOverride;
    }
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
  }

  List<String> _extractPathAndName(String gnTarget) {
    final String errorMessage =
        "fuchsia_reload --target '$gnTarget' should have the form: "
        "'//path/to/app:name'";
    // Separate strings like //path/to/target:app into [path/to/target, app]
    final int lastColon = gnTarget.lastIndexOf(':');
    if (lastColon < 0) {
      throwToolExit(errorMessage);
    }
    final String name = gnTarget.substring(lastColon + 1);
    // Skip '//' and chop off after :
    if ((gnTarget.length < 3) || (gnTarget[0] != '/') || (gnTarget[1] != '/')) {
      throwToolExit(errorMessage);
    }
    final String path = gnTarget.substring(2, lastColon);
    return <String>[path, name];
  }

  Future<List<int>> _getServicePorts() async {
    final FuchsiaDeviceCommandRunner runner =
        new FuchsiaDeviceCommandRunner(_fuchsiaRoot);
    final List<String> lsOutput = await runner.run("ls /tmp/dart.services");
    final List<int> ports = new List<int>();
    for (String s in lsOutput) {
      final String trimmed = s.trim();
      final int lastSpace = trimmed.lastIndexOf(' ');
      final String lastWord = trimmed.substring(lastSpace + 1);
      if ((lastWord != '.') && (lastWord != '..')) {
        final int value = int.parse(lastWord, onError: (_) => null);
        if (value != null) {
          ports.add(value);
        }
      }
    }
    return ports;
  }

  bool _directoryExists(String path) {
    final Directory d = fs.directory(path);
    return d.existsSync();
  }

  bool _fileExists(String path) {
    final File f = fs.file(path);
    return f.existsSync();
  }
}


// TODO(zra): When Fuchsia has ssh, this should be changed to use that instead.
class FuchsiaDeviceCommandRunner {
  final String _fuchsiaRoot;
  final Random _rng = new Random(new DateTime.now().millisecondsSinceEpoch);

  FuchsiaDeviceCommandRunner(this._fuchsiaRoot);

  Future<List<String>> run(String command) async {
    final int tag = _rng.nextInt(999999);
    const String kNetRunCommand = "out/build-magenta/tools/netruncmd";
    final String netruncmd = fs.path.join(_fuchsiaRoot, kNetRunCommand);
    const String kNetCP = "out/build-magenta/tools/netcp";
    final String netcp = fs.path.join(_fuchsiaRoot, kNetCP);
    final String remoteStdout = "/tmp/netruncmd.$tag";
    final String localStdout = "${fs.systemTempDirectory.path}/netruncmd.$tag";
    final String redirectedCommand = "$command > $remoteStdout";
    // Run the command with output directed to a tmp file.
    ProcessResult result =
        await Process.run(netruncmd, <String>[":", redirectedCommand]);
    if (result.exitCode != 0) {
      return null;
    }
    // Copy that file to the local filesystem.
    result = await Process.run(netcp, <String>[":$remoteStdout", localStdout]);
    // Try to delete the remote file. Don't care about the result;
    Process.run(netruncmd, <String>[":", "rm $remoteStdout"]);
    if (result.exitCode != 0) {
      return null;
    }
    // Read the local file.
    final File f = fs.file(localStdout);
    List<String> lines;
    try {
      lines = await f.readAsLines();
    } finally {
      f.delete();
    }
    return lines;
  }
}