chrome.dart 16.7 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:process/process.dart';
9 10 11 12 13
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart';

import '../base/common.dart';
import '../base/file_system.dart';
import '../base/io.dart';
14 15
import '../base/logger.dart';
import '../base/os.dart';
16
import '../base/platform.dart';
17 18
import '../convert.dart';

19
/// An environment variable used to override the location of Google Chrome.
20 21
const String kChromeEnvironment = 'CHROME_EXECUTABLE';

22 23 24
/// An environment variable used to override the location of Microsoft Edge.
const String kEdgeEnvironment = 'EDGE_ENVIRONMENT';

25 26 27 28 29 30 31
/// The expected executable name on linux.
const String kLinuxExecutable = 'google-chrome';

/// The expected executable name on macOS.
const String kMacOSExecutable =
    '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';

32
/// The expected Chrome executable name on Windows.
33 34
const String kWindowsExecutable = r'Google\Chrome\Application\chrome.exe';

35 36 37
/// The expected Edge executable name on Windows.
const String kWindowsEdgeExecutable = r'Microsoft\Edge\Application\msedge.exe';

38 39 40 41 42 43 44 45 46 47 48 49
/// Used by [ChromiumLauncher] to detect a glibc bug and retry launching the
/// browser.
///
/// Once every few thousands of launches we hit this glibc bug:
///
/// https://sourceware.org/bugzilla/show_bug.cgi?id=19329.
///
/// When this happens Chrome spits out something like the following then exits with code 127:
///
///     Inconsistency detected by ld.so: ../elf/dl-tls.c: 493: _dl_allocate_tls_init: Assertion `listp->slotinfo[cnt].gen <= GL(dl_tls_generation)' failed!
const String _kGlibcError = 'Inconsistency detected by ld.so';

50 51
typedef BrowserFinder = String Function(Platform, FileSystem);

52 53 54
/// Find the chrome executable on the current platform.
///
/// Does not verify whether the executable exists.
55 56
String findChromeExecutable(Platform platform, FileSystem fileSystem) {
  if (platform.environment.containsKey(kChromeEnvironment)) {
57
    return platform.environment[kChromeEnvironment]!;
58
  }
59
  if (platform.isLinux) {
60 61
    return kLinuxExecutable;
  }
62
  if (platform.isMacOS) {
63 64
    return kMacOSExecutable;
  }
65 66 67
  if (platform.isWindows) {
    /// The possible locations where the chrome executable can be located on windows.
    final List<String> kWindowsPrefixes = <String>[
68 69 70 71 72 73
      if (platform.environment.containsKey('LOCALAPPDATA'))
        platform.environment['LOCALAPPDATA']!,
      if (platform.environment.containsKey('PROGRAMFILES'))
        platform.environment['PROGRAMFILES']!,
      if (platform.environment.containsKey('PROGRAMFILES(X86)'))
        platform.environment['PROGRAMFILES(X86)']!,
74
    ];
75 76 77 78
    final String windowsPrefix = kWindowsPrefixes.firstWhere((String prefix) {
      if (prefix == null) {
        return false;
      }
79 80
      final String path = fileSystem.path.join(prefix, kWindowsExecutable);
      return fileSystem.file(path).existsSync();
81
    }, orElse: () => '.');
82
    return fileSystem.path.join(windowsPrefix, kWindowsExecutable);
83
  }
84
  throwToolExit('Platform ${platform.operatingSystem} is not supported.');
85 86
}

87 88 89 90 91
/// Find the Microsoft Edge executable on the current platform.
///
/// Does not verify whether the executable exists.
String findEdgeExecutable(Platform platform, FileSystem fileSystem) {
  if (platform.environment.containsKey(kEdgeEnvironment)) {
92
    return platform.environment[kEdgeEnvironment]!;
93 94 95 96
  }
  if (platform.isWindows) {
    /// The possible locations where the Edge executable can be located on windows.
    final List<String> kWindowsPrefixes = <String>[
97 98 99 100 101 102
      if (platform.environment.containsKey('LOCALAPPDATA'))
        platform.environment['LOCALAPPDATA']!,
      if (platform.environment.containsKey('PROGRAMFILES'))
        platform.environment['PROGRAMFILES']!,
      if (platform.environment.containsKey('PROGRAMFILES(X86)'))
        platform.environment['PROGRAMFILES(X86)']!,
103 104 105 106 107 108 109 110 111 112 113 114
    ];
    final String windowsPrefix = kWindowsPrefixes.firstWhere((String prefix) {
      if (prefix == null) {
        return false;
      }
      final String path = fileSystem.path.join(prefix, kWindowsEdgeExecutable);
      return fileSystem.file(path).existsSync();
    }, orElse: () => '.');
    return fileSystem.path.join(windowsPrefix, kWindowsEdgeExecutable);
  }
  // Not yet supported for macOS and Linux.
  return '';
115 116
}

117 118 119
/// A launcher for Chromium browsers with devtools configured.
class ChromiumLauncher {
  ChromiumLauncher({
120 121 122 123 124 125
    required FileSystem fileSystem,
    required Platform platform,
    required ProcessManager processManager,
    required OperatingSystemUtils operatingSystemUtils,
    required BrowserFinder browserFinder,
    required Logger logger,
126 127 128 129
  }) : _fileSystem = fileSystem,
       _platform = platform,
       _processManager = processManager,
       _operatingSystemUtils = operatingSystemUtils,
130
       _browserFinder = browserFinder,
131
       _logger = logger;
132 133 134 135 136

  final FileSystem _fileSystem;
  final Platform _platform;
  final ProcessManager _processManager;
  final OperatingSystemUtils _operatingSystemUtils;
137
  final BrowserFinder _browserFinder;
138
  final Logger _logger;
139

140
  bool get hasChromeInstance => currentCompleter.isCompleted;
141 142

  @visibleForTesting
143
  Completer<Chromium> currentCompleter = Completer<Chromium>();
144

145
  /// Whether we can locate the chrome executable.
146 147
  bool canFindExecutable() {
    final String chrome = _browserFinder(_platform, _fileSystem);
148 149 150 151 152
    try {
      return _processManager.canRun(chrome);
    } on ArgumentError {
      return false;
    }
153 154
  }

155 156 157 158
  /// The executable this launcher will use.
  String findExecutable() =>  _browserFinder(_platform, _fileSystem);

  /// Launch a Chromium browser to a particular `host` page.
159
  ///
160 161
  /// [headless] defaults to false, and controls whether we open a headless or
  /// a "headfull" browser.
162
  ///
163
  /// [debugPort] is Chrome's debugging protocol port. If null, a random free
164 165
  /// port is picked automatically.
  ///
166
  /// [skipCheck] does not attempt to make a devtools connection before returning.
167 168
  Future<Chromium> launch(String url, {
    bool headless = false,
169
    int? debugPort,
170
    bool skipCheck = false,
171
    Directory? cacheDir,
172
  }) async {
173
    if (currentCompleter.isCompleted) {
174 175 176
      throwToolExit('Only one instance of chrome can be started.');
    }

177
    final String chromeExecutable = _browserFinder(_platform, _fileSystem);
178

179 180
    if (_logger.isVerbose && !_platform.isWindows) {
      // Note: --version is not supported on windows.
181 182 183 184
      final ProcessResult versionResult = await _processManager.run(<String>[chromeExecutable, '--version']);
      _logger.printTrace('Using ${versionResult.stdout}');
    }

185 186
    final Directory userDataDir = _fileSystem.systemTempDirectory
      .createTempSync('flutter_tools_chrome_device.');
187 188 189 190

    if (cacheDir != null) {
      // Seed data dir with previous state.
      _restoreUserSessionInformation(cacheDir, userDataDir);
191 192
    }

193
    final int port = debugPort ?? await _operatingSystemUtils.findFreePort();
194 195 196 197
    final List<String> args = <String>[
      chromeExecutable,
      // Using a tmp directory ensures that a new instance of chrome launches
      // allowing for the remote debug port to be enabled.
198
      '--user-data-dir=${userDataDir.path}',
199 200 201 202 203 204 205 206 207 208 209 210
      '--remote-debugging-port=$port',
      // When the DevTools has focus we don't want to slow down the application.
      '--disable-background-timer-throttling',
      // Since we are using a temp profile, disable features that slow the
      // Chrome launch.
      '--disable-extensions',
      '--disable-popup-blocking',
      '--bwsi',
      '--no-first-run',
      '--no-default-browser-check',
      '--disable-default-apps',
      '--disable-translate',
211
      if (headless)
212 213 214 215 216 217
        ...<String>[
          '--headless',
          '--disable-gpu',
          '--no-sandbox',
          '--window-size=2400,1800',
        ],
218 219
      url,
    ];
220

221
    final Process? process = await _spawnChromiumProcess(args, chromeExecutable);
222 223

    // When the process exits, copy the user settings back to the provided data-dir.
224
    if (process != null && cacheDir != null) {
225 226 227 228
      unawaited(process.exitCode.whenComplete(() {
        _cacheUserSessionInformation(userDataDir, cacheDir);
      }));
    }
229
    return _connect(Chromium(
230 231
      port,
      ChromeConnection('localhost', port),
232
      url: url,
233
      process: process,
234
      chromiumLauncher: this,
235
    ), skipCheck);
236 237
  }

238 239 240 241 242 243 244 245 246 247 248 249
  Future<Process?> _spawnChromiumProcess(List<String> args, String chromeExecutable) async {
    if (_operatingSystemUtils.hostPlatform == HostPlatform.darwin_arm) {
      final ProcessResult result = _processManager.runSync(<String>['file', chromeExecutable]);
      // Check if ARM Chrome is installed.
      // Mach-O 64-bit executable arm64
      if ((result.stdout as String).contains('arm64')) {
        _logger.printTrace('Found ARM Chrome installation at $chromeExecutable, forcing native launch.');
        // If so, force Chrome to launch natively.
        args.insertAll(0, <String>['/usr/bin/arch', '-arm64']);
      }
    }

250 251
    // Keep attempting to launch the browser until one of:
    // - Chrome launched successfully, in which case we just return from the loop.
252 253 254
    // - The tool reached the maximum retry count, in which case we throw ToolExit.
    const int kMaxRetries = 3;
    int retry = 0;
255 256 257 258 259 260 261 262 263 264 265 266 267
    while (true) {
      final Process process = await _processManager.start(args);

      process.stdout
        .transform(utf8.decoder)
        .transform(const LineSplitter())
        .listen((String line) {
          _logger.printTrace('[CHROME]: $line');
        });

      // Wait until the DevTools are listening before trying to connect. This is
      // only required for flutter_test --platform=chrome and not flutter run.
      bool hitGlibcBug = false;
268
      bool shouldRetry = false;
269
      final List<String> errors = <String>[];
270 271 272 273
      await process.stderr
        .transform(utf8.decoder)
        .transform(const LineSplitter())
        .map((String line) {
274 275
          _logger.printTrace('[CHROME]: $line');
          errors.add('[CHROME]:$line');
276 277
          if (line.contains(_kGlibcError)) {
            hitGlibcBug = true;
278
            shouldRetry = true;
279 280 281 282 283 284 285 286 287
          }
          return line;
        })
        .firstWhere((String line) => line.startsWith('DevTools listening'), orElse: () {
          if (hitGlibcBug) {
            _logger.printTrace(
              'Encountered glibc bug https://sourceware.org/bugzilla/show_bug.cgi?id=19329. '
              'Will try launching browser again.',
            );
288 289
            // Return value unused.
            return '';
290
          }
291
          if (retry >= kMaxRetries) {
292 293
            errors.forEach(_logger.printError);
            _logger.printError('Failed to launch browser after $kMaxRetries tries. Command used to launch it: ${args.join(' ')}');
294 295 296 297 298 299 300 301
            throw ToolExit(
              'Failed to launch browser. Make sure you are using an up-to-date '
              'Chrome or Edge. Otherwise, consider using -d web-server instead '
              'and filing an issue at https://github.com/flutter/flutter/issues.',
            );
          }
          shouldRetry = true;
          return '';
302 303
        });

304
      if (!hitGlibcBug && !shouldRetry) {
305 306
        return process;
      }
307
      retry += 1;
308 309 310 311 312 313

      // A precaution that avoids accumulating browser processes, in case the
      // glibc bug doesn't cause the browser to quit and we keep looping and
      // launching more processes.
      unawaited(process.exitCode.timeout(const Duration(seconds: 1), onTimeout: () {
        process.kill();
314 315
        // sigterm
        return 15;
316 317 318 319
      }));
    }
  }

320 321 322 323
  // This is a directory which Chrome uses to store cookies, preferences and
  // other session data.
  String get _chromeDefaultPath => _fileSystem.path.join('Default');

324 325 326 327 328 329 330 331 332
  // This is a JSON file which contains configuration from the browser session,
  // such as window position. It is located under the Chrome data-dir folder.
  String get _preferencesPath => _fileSystem.path.join('Default', 'preferences');

  /// Copy Chrome user information from a Chrome session into a per-project
  /// cache.
  ///
  /// Note: more detailed docs of the Chrome user preferences store exists here:
  /// https://www.chromium.org/developers/design-documents/preferences.
333 334 335 336 337 338 339
  ///
  /// This intentionally skips the Cache, Code Cache, and GPUCache directories.
  /// While we're not sure exactly what is in them, this constitutes nearly 1 GB
  /// of data for a fresh flutter run and adds significant overhead to all startups.
  /// For workflows that may require this data, using the start-paused flag and
  /// dart debug extension with a user controlled browser profile will lead to a
  /// better experience.
340
  void _cacheUserSessionInformation(Directory userDataDir, Directory cacheDir) {
341
    final Directory targetChromeDefault = _fileSystem.directory(_fileSystem.path.join(cacheDir.path, _chromeDefaultPath));
342 343 344
    final Directory sourceChromeDefault = _fileSystem.directory(_fileSystem.path.join(userDataDir.path, _chromeDefaultPath));
    if (sourceChromeDefault.existsSync()) {
      targetChromeDefault.createSync(recursive: true);
345
      try {
346 347 348 349 350
        copyDirectory(
          sourceChromeDefault,
          targetChromeDefault,
          shouldCopyDirectory: _isNotCacheDirectory
        );
351 352 353 354 355
      } on FileSystemException catch (err) {
        // This is a best-effort update. Display the message in case the failure is relevant.
        // one possible example is a file lock due to multiple running chrome instances.
        _logger.printError('Failed to save Chrome preferences: $err');
      }
356
    }
357

358
    final File targetPreferencesFile = _fileSystem.file(_fileSystem.path.join(cacheDir.path, _preferencesPath));
359 360 361 362 363 364 365 366 367
    final File sourcePreferencesFile = _fileSystem.file(_fileSystem.path.join(userDataDir.path, _preferencesPath));

    if (sourcePreferencesFile.existsSync()) {
       targetPreferencesFile.parent.createSync(recursive: true);
       // If the file contains a crash string, remove it to hide the popup on next run.
       final String contents = sourcePreferencesFile.readAsStringSync();
       targetPreferencesFile.writeAsStringSync(contents
           .replaceFirst('"exit_type":"Crashed"', '"exit_type":"Normal"'));
    }
368 369 370 371 372
  }

  /// Restore Chrome user information from a per-project cache into Chrome's
  /// user data directory.
  void _restoreUserSessionInformation(Directory cacheDir, Directory userDataDir) {
373
    final Directory sourceChromeDefault = _fileSystem.directory(_fileSystem.path.join(cacheDir.path, _chromeDefaultPath));
374
    final Directory targetChromeDefault = _fileSystem.directory(_fileSystem.path.join(userDataDir.path, _chromeDefaultPath));
375 376 377
    try {
      if (sourceChromeDefault.existsSync()) {
        targetChromeDefault.createSync(recursive: true);
378 379 380 381 382
        copyDirectory(
          sourceChromeDefault,
          targetChromeDefault,
          shouldCopyDirectory: _isNotCacheDirectory,
        );
383 384 385
      }
    } on FileSystemException catch (err) {
      _logger.printError('Failed to restore Chrome preferences: $err');
386 387 388
    }
  }

389 390 391 392 393 394 395
  // Cache, Code Cache, and GPUCache are nearly 1GB of data
  bool _isNotCacheDirectory(Directory directory) {
    return !directory.path.endsWith('Cache') &&
           !directory.path.endsWith('Code Cache') &&
           !directory.path.endsWith('GPUCache');
  }

396
  Future<Chromium> _connect(Chromium chrome, bool skipCheck) async {
397 398
    // The connection is lazy. Try a simple call to make sure the provided
    // connection is valid.
399 400
    if (!skipCheck) {
      try {
401 402
        await chrome.chromeConnection.getTab(
          (ChromeTab tab) => true, retryFor: const Duration(seconds: 2));
403 404
      } on Exception catch (error, stackTrace) {
        _logger.printError('$error', stackTrace: stackTrace);
405 406
        await chrome.close();
        throwToolExit(
407
            'Unable to connect to Chrome debug port: ${chrome.debugPort}\n $error');
408
      }
409
    }
410
    currentCompleter.complete(chrome);
411 412 413
    return chrome;
  }

414
  Future<Chromium> get connectedInstance => currentCompleter.future;
415 416
}

417 418
/// A class for managing an instance of a Chromium browser.
class Chromium {
419
  Chromium(
420 421
    this.debugPort,
    this.chromeConnection, {
422
    this.url,
423 424
    Process? process,
    required ChromiumLauncher chromiumLauncher,
425 426
  })  : _process = process,
        _chromiumLauncher = chromiumLauncher;
427

428
  final String? url;
429
  final int debugPort;
430
  final Process? _process;
431
  final ChromeConnection chromeConnection;
432
  final ChromiumLauncher _chromiumLauncher;
433

434
  Future<int?> get onExit async => _process?.exitCode;
435

436
  Future<void> close() async {
437
    if (_chromiumLauncher.hasChromeInstance) {
438
      _chromiumLauncher.currentCompleter = Completer<Chromium>();
439 440
    }
    chromeConnection.close();
441
    _process?.kill();
442 443 444
    await _process?.exitCode;
  }
}