attach.dart 20.4 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:vm_service/vm_service.dart';
8

9
import '../android/android_device.dart';
10
import '../base/common.dart';
11
import '../base/file_system.dart';
12
import '../base/io.dart';
13 14 15 16
import '../base/logger.dart';
import '../base/platform.dart';
import '../base/signals.dart';
import '../base/terminal.dart';
17
import '../build_info.dart';
18
import '../commands/daemon.dart';
19
import '../compile.dart';
20
import '../daemon.dart';
21
import '../device.dart';
22
import '../device_port_forwarder.dart';
23
import '../fuchsia/fuchsia_device.dart';
24 25
import '../ios/devices.dart';
import '../ios/simulators.dart';
26
import '../macos/macos_ipad_device.dart';
27
import '../mdns_discovery.dart';
28
import '../project.dart';
29 30
import '../protocol_discovery.dart';
import '../resident_runner.dart';
31
import '../run_cold.dart';
32 33
import '../run_hot.dart';
import '../runner/flutter_command.dart';
34
import '../runner/flutter_command_runner.dart';
35
import '../vmservice.dart';
36 37 38 39 40 41 42

/// A Flutter-command that attaches to applications that have been launched
/// without `flutter run`.
///
/// With an application already running, a HotRunner can be attached to it
/// with:
/// ```
43
/// $ flutter attach --debug-url http://127.0.0.1:12345/QqL7EFEDNG0=/
44 45 46 47 48
/// ```
///
/// If `--disable-service-auth-codes` was provided to the application at startup
/// time, a HotRunner can be attached with just a port:
/// ```
49 50 51 52 53 54 55 56
/// $ flutter attach --debug-port 12345
/// ```
///
/// Alternatively, the attach command can start listening and scan for new
/// programs that become active:
/// ```
/// $ flutter attach
/// ```
57
/// As soon as a new VM Service is detected the command attaches to it and
58
/// enables hot reloading.
59 60 61
///
/// To attach to a flutter mod running on a fuchsia device, `--module` must
/// also be provided.
62
class AttachCommand extends FlutterCommand {
63 64 65 66 67 68 69 70 71 72
  AttachCommand({
    bool verboseHelp = false,
    HotRunnerFactory? hotRunnerFactory,
    required Stdio stdio,
    required Logger logger,
    required Terminal terminal,
    required Signals signals,
    required Platform platform,
    required ProcessInfo processInfo,
    required FileSystem fileSystem,
73 74 75 76 77 78 79 80
  }) : _hotRunnerFactory = hotRunnerFactory ?? HotRunnerFactory(),
       _stdio = stdio,
       _logger = logger,
       _terminal = terminal,
       _signals = signals,
       _platform = platform,
       _processInfo = processInfo,
       _fileSystem = fileSystem {
81
    addBuildModeFlags(verboseHelp: verboseHelp, defaultToRelease: false, excludeRelease: true);
82
    usesTargetOption();
83 84
    usesPortOptions(verboseHelp: verboseHelp);
    usesIpv6Flag(verboseHelp: verboseHelp);
85
    usesFilesystemOptions(hide: !verboseHelp);
86
    usesFuchsiaOptions(hide: !verboseHelp);
87
    usesDartDefineOption();
88
    usesDeviceUserOption();
89
    addEnableExperimentation(hide: !verboseHelp);
90
    addNullSafetyModeOptions(hide: !verboseHelp);
91
    usesInitializeFromDillOption(hide: !verboseHelp);
92 93
    argParser
      ..addOption(
94
        'debug-port',
95
        hide: !verboseHelp,
96
        help: '(deprecated) Device port where the Dart VM Service is listening. Requires '
97 98
              '"--disable-service-auth-codes" to also be provided to the Flutter '
              'application at launch, otherwise this command will fail to connect to '
99
              'the application. In general, "--debug-url" should be used instead.',
100
      )..addOption(
101 102
        'debug-url',
        aliases: <String>[ 'debug-uri' ], // supported for historical reasons
103
        help: 'The URL at which the Dart VM Service is listening.',
104 105
      )..addOption(
        'app-id',
106
        help: 'The package name (Android) or bundle identifier (iOS) for the app. '
107
              'This can be specified to avoid being prompted if multiple Dart VM Service ports '
108 109 110 111 112 113
              'are advertised.\n'
              'If you have multiple devices or emulators running, you should include the '
              'device hostname as well, e.g. "com.example.myApp@my-iphone".\n'
              'This parameter is case-insensitive.',
      )..addOption(
        'pid-file',
114
        help: 'Specify a file to write the process ID to. '
115
              'You can send SIGUSR1 to trigger a hot reload '
116 117 118 119 120 121 122
              'and SIGUSR2 to trigger a hot restart. '
              'The file is created when the signal handlers '
              'are hooked and deleted when they are removed.',
      )..addFlag(
        'report-ready',
        help: 'Print "ready" to the console after handling a keyboard command.\n'
              'This is primarily useful for tests and other automation, but consider '
123
              'using "--machine" instead.',
124
        hide: !verboseHelp,
125 126 127
      )..addOption(
        'project-root',
        hide: !verboseHelp,
128
        help: 'Normally used only in run target.',
129
      )..addFlag('machine',
130 131 132
        hide: !verboseHelp,
        negatable: false,
        help: 'Handle machine structured JSON command input and provide output '
133
              'and progress in machine-friendly format.',
134
      );
135
    usesTrackWidgetCreation(verboseHelp: verboseHelp);
136
    addDdsOptions(verboseHelp: verboseHelp);
137
    addDevToolsOptions(verboseHelp: verboseHelp);
138
    addServeObservatoryOptions(verboseHelp: verboseHelp);
139
    usesDeviceTimeoutOption();
140
    usesDeviceConnectionOption();
141 142
  }

143 144 145 146 147 148 149 150
  final HotRunnerFactory _hotRunnerFactory;
  final Stdio _stdio;
  final Logger _logger;
  final Terminal _terminal;
  final Signals _signals;
  final Platform _platform;
  final ProcessInfo _processInfo;
  final FileSystem _fileSystem;
151

152 153 154 155
  @override
  final String name = 'attach';

  @override
156
  final String description = r'''
157
Attach to a running app.
158

159 160 161 162
For attaching to Android or iOS devices, simply using `flutter attach` is
usually sufficient. The tool will search for a running Flutter app or module,
if available. Otherwise, the tool will wait for the next Flutter app or module
to launch before attaching.
163

164
For Fuchsia, the module name must be provided, e.g. `$flutter attach
165 166
--module=mod_name`. This can be called either before or after the application
is started.
167

168
If the app or module is already running and the specific vmService port is
169
known, it can be explicitly provided to attach via the command-line, e.g.
170
`$ flutter attach --debug-port 12345`''';
171

172 173 174
  @override
  final String category = FlutterCommandCategory.tools;

175 176 177
  @override
  bool get refreshWirelessDevices => true;

178 179
  int? get debugPort {
    if (argResults!['debug-port'] == null) {
180
      return null;
181
    }
182
    try {
183
      return int.parse(stringArg('debug-port')!);
184
    } on Exception catch (error) {
185 186 187 188
      throwToolExit('Invalid port for `--debug-port`: $error');
    }
  }

189
  Uri? get debugUri {
190 191
    final String? debugUrl = stringArg('debug-url');
    if (debugUrl == null) {
192 193
      return null;
    }
194
    final Uri? uri = Uri.tryParse(debugUrl);
195
    if (uri == null) {
196
      throwToolExit('Invalid `--debug-url`: $debugUrl');
197
    }
198
    if (!uri.hasPort) {
199
      throwToolExit('Port not specified for `--debug-url`: $uri');
200 201 202 203
    }
    return uri;
  }

204
  bool get serveObservatory => boolArg('serve-observatory');
205

206
  String? get appId {
207
    return stringArg('app-id');
208 209
  }

210
  String? get userIdentifier => stringArg(FlutterOptions.kDeviceUser);
211

212
  @override
213
  Future<void> validateCommand() async {
214 215 216
    // ARM macOS as an iOS target is hidden, except for attach.
    MacOSDesignedForIPadDevices.allowDiscovery = true;

217
    await super.validateCommand();
218 219 220

    final Device? targetDevice = await findTargetDevice();
    if (targetDevice == null) {
221
      throwToolExit(null);
222
    }
223

224
    debugPort;
225
    // Allow --ipv6 for iOS devices even if --debug-port and --debug-url
226
    // are unknown.
227 228 229 230
    if (!_isIOSDevice(targetDevice) &&
        debugPort == null &&
        debugUri == null &&
        argResults!.wasParsed(FlutterCommand.ipv6Flag)) {
231
      throwToolExit(
232
        'When the --debug-port or --debug-url is unknown, this command determines '
233 234 235
        'the value of --ipv6 on its own.',
      );
    }
236
    if (debugPort == null && debugUri == null && argResults!.wasParsed(FlutterCommand.vmServicePortOption)) {
237
      throwToolExit(
238
        'When the --debug-port or --debug-url is unknown, this command does not use '
239
        'the value of --vm-service-port.',
240 241
      );
    }
242 243
    if (debugPort != null && debugUri != null) {
      throwToolExit(
244
        'Either --debug-port or --debug-url can be provided, not both.');
245
    }
246 247

    if (userIdentifier != null) {
248
      final Device? device = await findTargetDevice();
249 250 251 252
      if (device is! AndroidDevice) {
        throwToolExit('--${FlutterOptions.kDeviceUser} is only supported for Android');
      }
    }
253 254
  }

255
  @override
256
  Future<FlutterCommandResult> runCommand() async {
257 258
    await _validateArguments();

259 260 261 262 263
    final Device? device = await findTargetDevice();

    if (device == null) {
      throwToolExit('Did not find any valid target devices.');
    }
264

265
    await _attachToDevice(device);
266

267
    return FlutterCommandResult.success();
268 269 270 271
  }

  Future<void> _attachToDevice(Device device) async {
    final FlutterProject flutterProject = FlutterProject.current();
272

273
    final Daemon? daemon = boolArg('machine')
274
      ? Daemon(
275
          DaemonConnection(
276 277
            daemonStreams: DaemonStreams.fromStdio(_stdio, logger: _logger),
            logger: _logger,
278
          ),
279
          notifyingLogger: (_logger is NotifyingLogger)
280
            ? _logger
281
            : NotifyingLogger(verbose: _logger.isVerbose, parent: _logger),
282 283
          logToStdout: true,
        )
284 285
      : null;

286
    Stream<Uri>? vmServiceUri;
287
    bool usesIpv6 = ipv6!;
288 289 290
    final String ipv6Loopback = InternetAddress.loopbackIPv6.address;
    final String ipv4Loopback = InternetAddress.loopbackIPv4.address;
    final String hostname = usesIpv6 ? ipv6Loopback : ipv4Loopback;
291
    final bool isWirelessIOSDevice = (device is IOSDevice) && device.isWirelesslyConnected;
292

293
    if ((debugPort == null && debugUri == null) || isWirelessIOSDevice) {
294
      if (device is FuchsiaDevice) {
295
        final String? module = stringArg('module');
296
        if (module == null) {
297
          throwToolExit("'--module' is required for attaching to a Fuchsia device");
298
        }
299
        usesIpv6 = device.ipv6;
300
        FuchsiaIsolateDiscoveryProtocol? isolateDiscoveryProtocol;
301
        try {
302
          isolateDiscoveryProtocol = device.getIsolateDiscoveryProtocol(module);
303
          vmServiceUri = Stream<Uri>.value(await isolateDiscoveryProtocol.uri).asBroadcastStream();
304
        } on Exception {
305
          isolateDiscoveryProtocol?.dispose();
306
          final List<ForwardedPort> ports = device.portForwarder.forwardedPorts.toList();
307
          for (final ForwardedPort port in ports) {
308 309
            await device.portForwarder.unforward(port);
          }
310
          rethrow;
311
        }
312
      } else if (_isIOSDevice(device)) {
313 314 315
        // Protocol Discovery relies on logging. On iOS earlier than 13, logging is gathered using syslog.
        // syslog is not available for iOS 13+. For iOS 13+, Protocol Discovery gathers logs from the VMService.
        // Since we don't have access to the VMService yet, Protocol Discovery cannot be used for iOS 13+.
316
        // Also, wireless devices must be found using mDNS and cannot use Protocol Discovery.
317 318
        final bool compatibleWithProtocolDiscovery = (device is IOSDevice) &&
          device.majorSdkVersion < IOSDeviceLogReader.minimumUniversalLoggingSdkVersion &&
319
          !isWirelessIOSDevice;
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349

        _logger.printStatus('Waiting for a connection from Flutter on ${device.name}...');
        final Status discoveryStatus = _logger.startSpinner(
          timeout: const Duration(seconds: 30),
          slowWarningCallback: () {
            // If relying on mDNS to find Dart VM Service, remind the user to allow local network permissions.
            if (!compatibleWithProtocolDiscovery) {
              return 'The Dart VM Service was not discovered after 30 seconds. This is taking much longer than expected...\n\n'
                'Click "Allow" to the prompt asking if you would like to find and connect devices on your local network. '
                'If you selected "Don\'t Allow", you can turn it on in Settings > Your App Name > Local Network. '
                "If you don't see your app in the Settings, uninstall the app and rerun to see the prompt again.\n";
            }

            return 'The Dart VM Service was not discovered after 30 seconds. This is taking much longer than expected...\n';
          },
        );

        int? devicePort;
        if (debugPort != null) {
          devicePort = debugPort;
        } else if (debugUri != null) {
          devicePort = debugUri?.port;
        } else if (deviceVmservicePort != null) {
          devicePort = deviceVmservicePort;
        }

        final Future<Uri?> mDNSDiscoveryFuture = MDnsVmServiceDiscovery.instance!.getVMServiceUriForAttach(
          appId,
          device,
          usesIpv6: usesIpv6,
350
          useDeviceIPAsHost: isWirelessIOSDevice,
351 352 353 354 355
          deviceVmservicePort: devicePort,
        );

        Future<Uri?>? protocolDiscoveryFuture;
        if (compatibleWithProtocolDiscovery) {
356
          final ProtocolDiscovery vmServiceDiscovery = ProtocolDiscovery.vmService(
357 358 359 360 361 362
            device.getLogReader(),
            portForwarder: device.portForwarder,
            ipv6: ipv6!,
            devicePort: devicePort,
            hostPort: hostVmservicePort,
            logger: _logger,
363
          );
364 365 366 367 368 369 370 371 372 373 374 375 376
          protocolDiscoveryFuture = vmServiceDiscovery.uri;
        }

        final Uri? foundUrl;
        if (protocolDiscoveryFuture == null) {
          foundUrl = await mDNSDiscoveryFuture;
        } else {
          foundUrl = await Future.any(
            <Future<Uri?>>[mDNSDiscoveryFuture, protocolDiscoveryFuture]
          );
        }
        discoveryStatus.stop();

377
        vmServiceUri = foundUrl == null
378
          ? null
379
          : Stream<Uri>.value(foundUrl).asBroadcastStream();
380 381
      }
      // If MDNS discovery fails or we're not on iOS, fallback to ProtocolDiscovery.
382 383 384
      if (vmServiceUri == null) {
        final ProtocolDiscovery vmServiceDiscovery =
          ProtocolDiscovery.vmService(
385 386 387
            // If it's an Android device, attaching relies on past log searching
            // to find the service protocol.
            await device.getLogReader(includePastLogs: device is AndroidDevice),
388
            portForwarder: device.portForwarder,
389
            ipv6: ipv6!,
390 391
            devicePort: deviceVmservicePort,
            hostPort: hostVmservicePort,
392
            logger: _logger,
393
          );
394
        _logger.printStatus('Waiting for a connection from Flutter on ${device.name}...');
395
        vmServiceUri = vmServiceDiscovery.uris;
396 397
      }
    } else {
398
      vmServiceUri = Stream<Uri>
399
        .fromFuture(
400
          buildVMServiceUri(
401 402
            device,
            debugUri?.host ?? hostname,
403
            debugPort ?? debugUri!.port,
404 405
            hostVmservicePort,
            debugUri?.path,
406
          )
407 408 409
        ).asBroadcastStream();
    }

410
    _terminal.usesTerminalUi = daemon == null;
411

412
    try {
413
      int? result;
414
      if (daemon != null) {
415
        final ResidentRunner runner = await createResidentRunner(
416
          vmServiceUris: vmServiceUri,
417 418 419
          device: device,
          flutterProject: flutterProject,
          usesIpv6: usesIpv6,
420
        );
421
        late AppInstance app;
422
        try {
423 424
          app = await daemon.appDomain.launch(
            runner,
425 426
            ({Completer<DebugConnectionInfo>? connectionInfoCompleter,
              Completer<void>? appStartedCompleter}) {
427 428 429 430
              return runner.attach(
                connectionInfoCompleter: connectionInfoCompleter,
                appStartedCompleter: appStartedCompleter,
                allowExistingDdsInstance: true,
431
                enableDevTools: boolArg(FlutterCommand.kEnableDevTools),
432 433
              );
            },
434 435 436
            device,
            null,
            true,
437
            _fileSystem.currentDirectory,
438
            LaunchMode.attach,
439
            _logger as AppRunLogger,
440
          );
441
        } on Exception catch (error) {
442 443
          throwToolExit(error.toString());
        }
444
        result = await app.runner!.waitForAppToFinish();
445 446 447
        return;
      }
      while (true) {
448
        final ResidentRunner runner = await createResidentRunner(
449
          vmServiceUris: vmServiceUri,
450 451 452
          device: device,
          flutterProject: flutterProject,
          usesIpv6: usesIpv6,
453
        );
454
        final Completer<void> onAppStart = Completer<void>.sync();
455
        TerminalHandler? terminalHandler;
456
        unawaited(onAppStart.future.whenComplete(() {
457 458
          terminalHandler = TerminalHandler(
            runner,
459 460 461 462
            logger: _logger,
            terminal: _terminal,
            signals: _signals,
            processInfo: _processInfo,
463 464
            reportReady: boolArg('report-ready'),
            pidFile: stringArg('pid-file'),
465
          )
466 467
            ..registerSignalHandlers()
            ..setupTerminal();
468 469 470
        }));
        result = await runner.attach(
          appStartedCompleter: onAppStart,
471
          allowExistingDdsInstance: true,
472
          enableDevTools: boolArg(FlutterCommand.kEnableDevTools),
473
        );
474 475 476 477
        if (result != 0) {
          throwToolExit(null, exitCode: result);
        }
        terminalHandler?.stop();
478
        assert(result != null);
479
        if (runner.exited || !runner.isWaitingForVmService) {
480 481
          break;
        }
482
        _logger.printStatus('Waiting for a new connection from Flutter on ${device.name}...');
483
      }
484 485 486 487 488
    } on RPCError catch (err) {
      if (err.code == RPCErrorCodes.kServiceDisappeared) {
        throwToolExit('Lost connection to device.');
      }
      rethrow;
489
    } finally {
490
      final List<ForwardedPort> ports = device.portForwarder!.forwardedPorts.toList();
491
      for (final ForwardedPort port in ports) {
492
        await device.portForwarder!.unforward(port);
493
      }
494 495 496 497 498 499 500
      // However we exited from the runner, ensure the terminal has line mode
      // and echo mode enabled before we return the user to the shell.
      try {
        _terminal.singleCharMode = false;
      } on StdinException {
        // Do nothing, if the STDIN handle is no longer available, there is nothing actionable for us to do at this point
      }
501 502 503
    }
  }

504
  Future<ResidentRunner> createResidentRunner({
505
    required Stream<Uri> vmServiceUris,
506 507 508
    required Device device,
    required FlutterProject flutterProject,
    required bool usesIpv6,
509
  }) async {
510
    final BuildInfo buildInfo = await getBuildInfo();
511 512 513

    final FlutterDevice flutterDevice = await FlutterDevice.create(
      device,
514
      target: targetFile,
515
      targetModel: TargetModel(stringArg('target-model')!),
516
      buildInfo: buildInfo,
517
      userIdentifier: userIdentifier,
518
      platform: _platform,
519
    );
520
    flutterDevice.vmServiceUris = vmServiceUris;
521
    final List<FlutterDevice> flutterDevices =  <FlutterDevice>[flutterDevice];
522 523
    final DebuggingOptions debuggingOptions = DebuggingOptions.enabled(
      buildInfo,
524
      enableDds: enableDds,
525
      ddsPort: ddsPort,
526
      devToolsServerAddress: devToolsServerAddress,
527
      serveObservatory: serveObservatory,
528
      usingCISystem: usingCISystem,
529
    );
530

531
    return buildInfo.isDebug
532
      ? _hotRunnerFactory.build(
533 534 535
          flutterDevices,
          target: targetFile,
          debuggingOptions: debuggingOptions,
536
          packagesFilePath: globalResults![FlutterGlobalOptions.kPackagesOption] as String?,
537 538
          projectRootPath: stringArg('project-root'),
          dillOutputPath: stringArg('output-dill'),
539 540 541 542 543 544 545 546 547 548 549
          ipv6: usesIpv6,
          flutterProject: flutterProject,
        )
      : ColdRunner(
          flutterDevices,
          target: targetFile,
          debuggingOptions: debuggingOptions,
          ipv6: usesIpv6,
        );
  }

550
  Future<void> _validateArguments() async { }
551 552 553 554 555 556

  bool _isIOSDevice(Device device) {
    return (device is IOSDevice) ||
        (device is IOSSimulator) ||
        (device is MacOSDesignedForIPadDevice);
  }
557
}
558 559

class HotRunnerFactory {
560
  HotRunner build(
561
    List<FlutterDevice> devices, {
562 563
    required String target,
    required DebuggingOptions debuggingOptions,
564
    bool benchmarkMode = false,
565
    File? applicationBinary,
566
    bool hostIsIde = false,
567 568 569
    String? projectRootPath,
    String? packagesFilePath,
    String? dillOutputPath,
570 571
    bool stayResident = true,
    bool ipv6 = false,
572
    FlutterProject? flutterProject,
573
  }) => HotRunner(
574 575 576 577 578 579 580 581 582 583 584
    devices,
    target: target,
    debuggingOptions: debuggingOptions,
    benchmarkMode: benchmarkMode,
    applicationBinary: applicationBinary,
    hostIsIde: hostIsIde,
    projectRootPath: projectRootPath,
    dillOutputPath: dillOutputPath,
    stayResident: stayResident,
    ipv6: ipv6,
  );
585
}