Add --machine support for flutter attach (#19077)

* Extract some of startApp into a reusable method

* Get basic attach --machine working

* Attach --machine tweaks

Move validation to validate method and create daemon early so we get the startup event before trying to get a connection.

* Bump daemon version so we know whether it's valid to flutter attach

* Tweak output text

* Swap package imports for relative

* Review tweaks (naming, formatting, typedefs)

* Separate arguments from process spawning

This will make calling attach easier

* Add a basic test for flutter attach --machine

* Fix crash if port unforward modifies the list of forwarded ports

* Add a no-op port forwarder for flutter-tester

* Switch to using BasicProject instead of our own inline code

* Fix expectation in test now we have a portForwarder

* Remove stale TODO (this is done)

* Tweak formatting

* Change some Completers to void to fix Dart 2 issues
This commit is contained in:
Danny Tuppeny
2018-07-19 13:38:29 +01:00
committed by GitHub
parent 442fc3cf06
commit ed9afbbc72
12 changed files with 204 additions and 67 deletions

View File

@@ -5,8 +5,10 @@
import 'dart:async';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../cache.dart';
import '../commands/daemon.dart';
import '../device.dart';
import '../globals.dart';
import '../protocol_discovery.dart';
@@ -35,16 +37,22 @@ final String ipv4Loopback = InternetAddress.loopbackIPv4.address;
class AttachCommand extends FlutterCommand {
AttachCommand({bool verboseHelp = false}) {
addBuildModeFlags(defaultToRelease: false);
argParser.addOption(
argParser
..addOption(
'debug-port',
help: 'Local port where the observatory is listening.',
);
argParser.addFlag(
'preview-dart-2',
defaultsTo: true,
hide: !verboseHelp,
help: 'Preview Dart 2.0 functionality.',
);
)
..addFlag(
'preview-dart-2',
defaultsTo: true,
hide: !verboseHelp,
help: 'Preview Dart 2.0 functionality.',
)..addFlag('machine',
hide: !verboseHelp,
negatable: false,
help: 'Handle machine structured JSON command input and provide output\n'
'and progress in machine friendly format.',
);
}
@override
@@ -64,6 +72,14 @@ class AttachCommand extends FlutterCommand {
return null;
}
@override
Future<Null> validateCommand() async {
super.validateCommand();
if (await findTargetDevice() == null)
throwToolExit(null);
observatoryPort;
}
@override
Future<Null> runCommand() async {
Cache.releaseLockEarly();
@@ -71,17 +87,24 @@ class AttachCommand extends FlutterCommand {
await _validateArguments();
final Device device = await findTargetDevice();
if (device == null)
throwToolExit(null);
final int devicePort = observatoryPort;
final Daemon daemon = argResults['machine']
? new Daemon(stdinCommandStream, stdoutCommandResponse,
notifyingLogger: new NotifyingLogger(), logToStdout: true)
: null;
Uri observatoryUri;
if (devicePort == null) {
ProtocolDiscovery observatoryDiscovery;
try {
observatoryDiscovery = new ProtocolDiscovery.observatory(
device.getLogReader(), portForwarder: device.portForwarder);
printStatus('Listening.');
device.getLogReader(),
portForwarder: device.portForwarder,
);
printStatus('Waiting for a connection from Flutter on ${device.name}...');
observatoryUri = await observatoryDiscovery.uri;
printStatus('Done.');
} finally {
await observatoryDiscovery?.cancel();
}
@@ -90,17 +113,33 @@ class AttachCommand extends FlutterCommand {
observatoryUri = Uri.parse('http://$ipv4Loopback:$localPort/');
}
try {
final FlutterDevice flutterDevice =
new FlutterDevice(device, trackWidgetCreation: false, previewDart2: argResults['preview-dart-2']);
final FlutterDevice flutterDevice = new FlutterDevice(device,
trackWidgetCreation: false, previewDart2: argResults['preview-dart-2']);
flutterDevice.observatoryUris = <Uri>[ observatoryUri ];
final HotRunner hotRunner = new HotRunner(
<FlutterDevice>[flutterDevice],
debuggingOptions: new DebuggingOptions.enabled(getBuildInfo()),
packagesFilePath: globalResults['packages'],
usesTerminalUI: daemon == null,
);
await hotRunner.attach();
if (daemon != null) {
AppInstance app;
try {
app = await daemon.appDomain.launch(hotRunner, hotRunner.attach,
device, null, true, fs.currentDirectory);
} catch (error) {
throwToolExit(error.toString());
}
final int result = await app.runner.waitForAppToFinish();
if (result != 0)
throwToolExit(null, exitCode: result);
} else {
await hotRunner.attach();
}
} finally {
device.portForwarder.forwardedPorts.forEach(device.portForwarder.unforward);
final List<ForwardedPort> ports = device.portForwarder.forwardedPorts.toList();
ports.forEach(device.portForwarder.unforward);
}
}

View File

@@ -28,7 +28,7 @@ import '../runner/flutter_command.dart';
import '../tester/flutter_tester.dart';
import '../vmservice.dart';
const String protocolVersion = '0.4.0';
const String protocolVersion = '0.4.1';
/// A server process command. This command will start up a long-lived server.
/// It reads JSON-RPC based commands from stdin, executes them, and returns
@@ -303,6 +303,11 @@ class DaemonDomain extends Domain {
}
}
typedef Future<void> _RunOrAttach({
Completer<DebugConnectionInfo> connectionInfoCompleter,
Completer<void> appStartedCompleter
});
/// This domain responds to methods like [start] and [stop].
///
/// It fires events for application start, stop, and stdout and stderr.
@@ -369,8 +374,29 @@ class AppDomain extends Domain {
ipv6: ipv6,
);
}
return launch(
runner,
({ Completer<DebugConnectionInfo> connectionInfoCompleter,
Completer<void> appStartedCompleter }) => runner.run(
connectionInfoCompleter: connectionInfoCompleter,
appStartedCompleter: appStartedCompleter,
route: route),
device,
projectDirectory,
enableHotReload,
cwd);
}
final AppInstance app = new AppInstance(_getNewAppId(), runner: runner, logToStdout: daemon.logToStdout);
Future<AppInstance> launch(
ResidentRunner runner,
_RunOrAttach runOrAttach,
Device device,
String projectDirectory,
bool enableHotReload,
Directory cwd) async {
final AppInstance app = new AppInstance(_getNewAppId(),
runner: runner, logToStdout: daemon.logToStdout);
_apps.add(app);
_sendAppEvent(app, 'start', <String, dynamic>{
'deviceId': device.id,
@@ -380,7 +406,7 @@ class AppDomain extends Domain {
Completer<DebugConnectionInfo> connectionInfoCompleter;
if (options.debuggingEnabled) {
if (runner.debuggingOptions.debuggingEnabled) {
connectionInfoCompleter = new Completer<DebugConnectionInfo>();
// We don't want to wait for this future to complete and callbacks won't fail.
// As it just writes to stdout.
@@ -394,20 +420,18 @@ class AppDomain extends Domain {
_sendAppEvent(app, 'debugPort', params);
});
}
final Completer<Null> appStartedCompleter = new Completer<Null>();
final Completer<void> appStartedCompleter = new Completer<void>();
// We don't want to wait for this future to complete and callbacks won't fail.
// As it just writes to stdout.
appStartedCompleter.future.then<Null>((Null value) { // ignore: unawaited_futures
appStartedCompleter.future.then<void>((_) { // ignore: unawaited_futures
_sendAppEvent(app, 'started');
});
await app._runInZone<Null>(this, () async {
try {
await runner.run(
connectionInfoCompleter: connectionInfoCompleter,
appStartedCompleter: appStartedCompleter,
route: route,
);
await runOrAttach(
connectionInfoCompleter: connectionInfoCompleter,
appStartedCompleter: appStartedCompleter);
_sendAppEvent(app, 'stop');
} catch (error, trace) {
_sendAppEvent(app, 'stop', <String, dynamic>{
@@ -419,7 +443,6 @@ class AppDomain extends Domain {
_apps.remove(app);
}
});
return app;
}

View File

@@ -391,7 +391,7 @@ class RunCommand extends RunCommandBase {
// need to know about analytics.
//
// Do not add more operations to the future.
final Completer<Null> appStartedTimeRecorder = new Completer<Null>.sync();
final Completer<void> appStartedTimeRecorder = new Completer<void>.sync();
// This callback can't throw.
appStartedTimeRecorder.future.then( // ignore: unawaited_futures
(_) { appStartedTime = clock.now(); }

View File

@@ -467,7 +467,7 @@ abstract class ResidentRunner {
/// Start the app and keep the process running during its lifetime.
Future<int> run({
Completer<DebugConnectionInfo> connectionInfoCompleter,
Completer<Null> appStartedCompleter,
Completer<void> appStartedCompleter,
String route,
bool shouldBuild = true
});

View File

@@ -35,7 +35,7 @@ class ColdRunner extends ResidentRunner {
@override
Future<int> run({
Completer<DebugConnectionInfo> connectionInfoCompleter,
Completer<Null> appStartedCompleter,
Completer<void> appStartedCompleter,
String route,
bool shouldBuild = true
}) async {

View File

@@ -149,7 +149,7 @@ class HotRunner extends ResidentRunner {
Future<int> attach({
Completer<DebugConnectionInfo> connectionInfoCompleter,
Completer<Null> appStartedCompleter,
Completer<void> appStartedCompleter,
String viewFilter,
}) async {
try {
@@ -235,7 +235,7 @@ class HotRunner extends ResidentRunner {
@override
Future<int> run({
Completer<DebugConnectionInfo> connectionInfoCompleter,
Completer<Null> appStartedCompleter,
Completer<void> appStartedCompleter,
String route,
bool shouldBuild = true
}) async {

View File

@@ -44,6 +44,7 @@ class FlutterTesterDevice extends Device {
FlutterTesterDevice(String deviceId) : super(deviceId);
Process _process;
final DevicePortForwarder _portForwarder = new _NoopPortForwarder();
@override
Future<bool> get isLocalEmulator async => false;
@@ -52,7 +53,7 @@ class FlutterTesterDevice extends Device {
String get name => 'Flutter test device';
@override
DevicePortForwarder get portForwarder => null;
DevicePortForwarder get portForwarder => _portForwarder;
@override
Future<String> get sdkNameAndVersion async {
@@ -233,3 +234,20 @@ class _FlutterTesterDeviceLogReader extends DeviceLogReader {
void addLine(String line) => _logLinesController.add(line);
}
/// A fake port forwarder that doesn't do anything. Used by flutter tester
/// where the VM is running on the same machine and does not need ports forwarding.
class _NoopPortForwarder extends DevicePortForwarder {
@override
Future<int> forward(int devicePort, {int hostPort}) {
if (hostPort != null && hostPort != devicePort)
throw 'Forwarding to a different port is not supported by flutter tester';
return new Future<int>.value(devicePort);
}
@override
List<ForwardedPort> get forwardedPorts => <ForwardedPort>[];
@override
Future<Null> unforward(ForwardedPort forwardedPort) => null;
}