process.dart 17.3 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:process/process.dart';
8

9
import '../convert.dart';
10
import 'common.dart';
11
import 'io.dart';
12
import 'logger.dart';
13

14
typedef StringConverter = String? Function(String string);
15 16

/// A function that will be run before the VM exits.
17
typedef ShutdownHook = FutureOr<dynamic> Function();
Devon Carew's avatar
Devon Carew committed
18

19
// TODO(ianh): We have way too many ways to run subprocesses in this project.
20 21 22 23
// Convert most of these into one or more lightweight wrappers around the
// [ProcessManager] API using named parameters for the various options.
// See [here](https://github.com/flutter/flutter/pull/14535#discussion_r167041161)
// for more details.
24

25 26
abstract class ShutdownHooks {
  factory ShutdownHooks({
27
    required Logger logger,
28 29 30 31 32 33
  }) => _DefaultShutdownHooks(
    logger: logger,
  );

  /// Registers a [ShutdownHook] to be executed before the VM exits.
  void addShutdownHook(
34 35
    ShutdownHook shutdownHook
  );
36 37 38 39 40 41 42 43 44

  /// Runs all registered shutdown hooks and returns a future that completes when
  /// all such hooks have finished.
  ///
  /// Shutdown hooks will be run in groups by their [ShutdownStage]. All shutdown
  /// hooks within a given stage will be started in parallel and will be
  /// guaranteed to run to completion before shutdown hooks in the next stage are
  /// started.
  Future<void> runShutdownHooks();
45 46
}

47 48
class _DefaultShutdownHooks implements ShutdownHooks {
  _DefaultShutdownHooks({
49
    required Logger logger,
50 51 52
  }) : _logger = logger;

  final Logger _logger;
53
  final List<ShutdownHook> _shutdownHooks = <ShutdownHook>[];
54 55 56 57 58

  bool _shutdownHooksRunning = false;

  @override
  void addShutdownHook(
59 60
    ShutdownHook shutdownHook
  ) {
61
    assert(!_shutdownHooksRunning);
62
    _shutdownHooks.add(shutdownHook);
63 64 65 66 67 68 69
  }

  @override
  Future<void> runShutdownHooks() async {
    _logger.printTrace('Running shutdown hooks');
    _shutdownHooksRunning = true;
    try {
70 71 72 73 74
      final List<Future<dynamic>> futures = <Future<dynamic>>[];
      for (final ShutdownHook shutdownHook in _shutdownHooks) {
        final FutureOr<dynamic> result = shutdownHook();
        if (result is Future<dynamic>) {
          futures.add(result);
75 76
        }
      }
77
      await Future.wait<dynamic>(futures);
78 79
    } finally {
      _shutdownHooksRunning = false;
80
    }
81
    _logger.printTrace('Shutdown hooks complete');
82
  }
83 84
}

85
class ProcessExit implements Exception {
86
  ProcessExit(this.exitCode, {this.immediate = false});
87

88
  final bool immediate;
89 90
  final int exitCode;

Hixie's avatar
Hixie committed
91
  String get message => 'ProcessExit: $exitCode';
92 93

  @override
94 95
  String toString() => message;
}
96 97

class RunResult {
98 99 100
  RunResult(this.processResult, this._command)
    : assert(_command != null),
      assert(_command.isNotEmpty);
101 102 103

  final ProcessResult processResult;

104 105
  final List<String> _command;

106
  int get exitCode => processResult.exitCode;
107 108
  String get stdout => processResult.stdout as String;
  String get stderr => processResult.stderr as String;
109 110 111

  @override
  String toString() {
112
    final StringBuffer out = StringBuffer();
113 114
    if (stdout.isNotEmpty) {
      out.writeln(stdout);
115
    }
116 117
    if (stderr.isNotEmpty) {
      out.writeln(stderr);
118
    }
119 120
    return out.toString().trimRight();
  }
121

122 123
  /// Throws a [ProcessException] with the given `message`.
  void throwException(String message) {
124
    throw ProcessException(
125 126 127 128 129 130
      _command.first,
      _command.skip(1).toList(),
      message,
      exitCode,
    );
  }
131
}
132 133 134 135

typedef RunResultChecker = bool Function(int);

abstract class ProcessUtils {
136
  factory ProcessUtils({
137 138
    required ProcessManager processManager,
    required Logger logger,
139 140 141 142
  }) => _DefaultProcessUtils(
    processManager: processManager,
    logger: logger,
  );
143 144 145 146 147 148

  /// Spawns a child process to run the command [cmd].
  ///
  /// When [throwOnError] is `true`, if the child process finishes with a non-zero
  /// exit code, a [ProcessException] is thrown.
  ///
149
  /// If [throwOnError] is `true`, and [allowedFailures] is supplied,
150
  /// a [ProcessException] is only thrown on a non-zero exit code if
151
  /// [allowedFailures] returns false when passed the exit code.
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
  ///
  /// When [workingDirectory] is set, it is the working directory of the child
  /// process.
  ///
  /// When [allowReentrantFlutter] is set to `true`, the child process is
  /// permitted to call the Flutter tool. By default it is not.
  ///
  /// When [environment] is supplied, it is used as the environment for the child
  /// process.
  ///
  /// When [timeout] is supplied, [runAsync] will kill the child process and
  /// throw a [ProcessException] when it doesn't finish in time.
  ///
  /// If [timeout] is supplied, the command will be retried [timeoutRetries] times
  /// if it times out.
  Future<RunResult> run(
    List<String> cmd, {
    bool throwOnError = false,
170 171
    RunResultChecker? allowedFailures,
    String? workingDirectory,
172
    bool allowReentrantFlutter = false,
173 174
    Map<String, String>? environment,
    Duration? timeout,
175 176 177 178 179 180 181
    int timeoutRetries = 0,
  });

  /// Run the command and block waiting for its result.
  RunResult runSync(
    List<String> cmd, {
    bool throwOnError = false,
182
    bool verboseExceptions = false,
183
    RunResultChecker? allowedFailures,
184
    bool hideStdout = false,
185 186
    String? workingDirectory,
    Map<String, String>? environment,
187
    bool allowReentrantFlutter = false,
188
    Encoding encoding = systemEncoding,
189 190 191 192 193 194
  });

  /// This runs the command in the background from the specified working
  /// directory. Completes when the process has been started.
  Future<Process> start(
    List<String> cmd, {
195
    String? workingDirectory,
196
    bool allowReentrantFlutter = false,
197
    Map<String, String>? environment,
198 199 200 201 202 203 204 205 206 207
  });

  /// This runs the command and streams stdout/stderr from the child process to
  /// this process' stdout/stderr. Completes with the process's exit code.
  ///
  /// If [filter] is null, no lines are removed.
  ///
  /// If [filter] is non-null, all lines that do not match it are removed. If
  /// [mapFunction] is present, all lines that match [filter] are also forwarded
  /// to [mapFunction] for further processing.
208 209 210
  ///
  /// If [stdoutErrorMatcher] is non-null, matching lines from stdout will be
  /// treated as errors, just as if they had been logged to stderr instead.
211 212
  Future<int> stream(
    List<String> cmd, {
213
    String? workingDirectory,
214 215 216
    bool allowReentrantFlutter = false,
    String prefix = '',
    bool trace = false,
217 218 219 220
    RegExp? filter,
    RegExp? stdoutErrorMatcher,
    StringConverter? mapFunction,
    Map<String, String>? environment,
221 222 223 224
  });

  bool exitsHappySync(
    List<String> cli, {
225
    Map<String, String>? environment,
226 227 228 229
  });

  Future<bool> exitsHappy(
    List<String> cli, {
230
    Map<String, String>? environment,
231 232 233 234
  });
}

class _DefaultProcessUtils implements ProcessUtils {
235
  _DefaultProcessUtils({
236 237
    required ProcessManager processManager,
    required Logger logger,
238 239 240 241 242 243 244
  }) : _processManager = processManager,
      _logger = logger;

  final ProcessManager _processManager;

  final Logger _logger;

245 246 247 248
  @override
  Future<RunResult> run(
    List<String> cmd, {
    bool throwOnError = false,
249 250
    RunResultChecker? allowedFailures,
    String? workingDirectory,
251
    bool allowReentrantFlutter = false,
252 253
    Map<String, String>? environment,
    Duration? timeout,
254 255 256 257 258 259 260 261 262 263 264
    int timeoutRetries = 0,
  }) async {
    if (cmd == null || cmd.isEmpty) {
      throw ArgumentError('cmd must be a non-empty list');
    }
    if (timeoutRetries < 0) {
      throw ArgumentError('timeoutRetries must be non-negative');
    }
    _traceCommand(cmd, workingDirectory: workingDirectory);

    // When there is no timeout, there's no need to kill a running process, so
265
    // we can just use _processManager.run().
266
    if (timeout == null) {
267
      final ProcessResult results = await _processManager.run(
268 269 270 271 272
        cmd,
        workingDirectory: workingDirectory,
        environment: _environment(allowReentrantFlutter, environment),
      );
      final RunResult runResult = RunResult(results, cmd);
273
      _logger.printTrace(runResult.toString());
274
      if (throwOnError && runResult.exitCode != 0 &&
275
          (allowedFailures == null || !allowedFailures(runResult.exitCode))) {
276 277 278 279 280 281
        runResult.throwException('Process exited abnormally:\n$runResult');
      }
      return runResult;
    }

    // When there is a timeout, we have to kill the running process, so we have
282
    // to use _processManager.start() through _runCommand() above.
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    while (true) {
      assert(timeoutRetries >= 0);
      timeoutRetries = timeoutRetries - 1;

      final Process process = await start(
          cmd,
          workingDirectory: workingDirectory,
          allowReentrantFlutter: allowReentrantFlutter,
          environment: environment,
      );

      final StringBuffer stdoutBuffer = StringBuffer();
      final StringBuffer stderrBuffer = StringBuffer();
      final Future<void> stdoutFuture = process.stdout
          .transform<String>(const Utf8Decoder(reportErrors: false))
          .listen(stdoutBuffer.write)
          .asFuture<void>(null);
      final Future<void> stderrFuture = process.stderr
          .transform<String>(const Utf8Decoder(reportErrors: false))
          .listen(stderrBuffer.write)
          .asFuture<void>(null);

305 306
      int? exitCode;
      exitCode = await process.exitCode.then<int?>((int x) => x).timeout(timeout, onTimeout: () {
307
        // The process timed out. Kill it.
308
        _processManager.killPid(process.pid);
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
        return null;
      });

      String stdoutString;
      String stderrString;
      try {
        Future<void> stdioFuture =
            Future.wait<void>(<Future<void>>[stdoutFuture, stderrFuture]);
        if (exitCode == null) {
          // If we had to kill the process for a timeout, only wait a short time
          // for the stdio streams to drain in case killing the process didn't
          // work.
          stdioFuture = stdioFuture.timeout(const Duration(seconds: 1));
        }
        await stdioFuture;
324
      } on Exception {
325 326 327 328 329 330 331 332 333 334 335 336
        // Ignore errors on the process' stdout and stderr streams. Just capture
        // whatever we got, and use the exit code
      }
      stdoutString = stdoutBuffer.toString();
      stderrString = stderrBuffer.toString();

      final ProcessResult result = ProcessResult(
          process.pid, exitCode ?? -1, stdoutString, stderrString);
      final RunResult runResult = RunResult(result, cmd);

      // If the process did not timeout. We are done.
      if (exitCode != null) {
337
        _logger.printTrace(runResult.toString());
338
        if (throwOnError && runResult.exitCode != 0 &&
339
            (allowedFailures == null || !allowedFailures(exitCode))) {
340 341 342 343 344 345 346 347 348 349 350
          runResult.throwException('Process exited abnormally:\n$runResult');
        }
        return runResult;
      }

      // If we are out of timeoutRetries, throw a ProcessException.
      if (timeoutRetries < 0) {
        runResult.throwException('Process timed out:\n$runResult');
      }

      // Log the timeout with a trace message in verbose mode.
351 352 353 354
      _logger.printTrace(
        'Process "${cmd[0]}" timed out. $timeoutRetries attempts left:\n'
        '$runResult',
      );
355 356 357 358 359 360 361 362 363
    }

    // Unreachable.
  }

  @override
  RunResult runSync(
    List<String> cmd, {
    bool throwOnError = false,
364
    bool verboseExceptions = false,
365
    RunResultChecker? allowedFailures,
366
    bool hideStdout = false,
367 368
    String? workingDirectory,
    Map<String, String>? environment,
369
    bool allowReentrantFlutter = false,
370
    Encoding encoding = systemEncoding,
371 372
  }) {
    _traceCommand(cmd, workingDirectory: workingDirectory);
373
    final ProcessResult results = _processManager.runSync(
374 375 376
      cmd,
      workingDirectory: workingDirectory,
      environment: _environment(allowReentrantFlutter, environment),
377 378
      stderrEncoding: encoding,
      stdoutEncoding: encoding,
379 380 381
    );
    final RunResult runResult = RunResult(results, cmd);

382
    _logger.printTrace('Exit code ${runResult.exitCode} from: ${cmd.join(' ')}');
383 384

    bool failedExitCode = runResult.exitCode != 0;
385 386
    if (allowedFailures != null && failedExitCode) {
      failedExitCode = !allowedFailures(runResult.exitCode);
387 388 389 390
    }

    if (runResult.stdout.isNotEmpty && !hideStdout) {
      if (failedExitCode && throwOnError) {
391
        _logger.printStatus(runResult.stdout.trim());
392
      } else {
393
        _logger.printTrace(runResult.stdout.trim());
394 395 396 397 398
      }
    }

    if (runResult.stderr.isNotEmpty) {
      if (failedExitCode && throwOnError) {
399
        _logger.printError(runResult.stderr.trim());
400
      } else {
401
        _logger.printTrace(runResult.stderr.trim());
402 403 404 405
      }
    }

    if (failedExitCode && throwOnError) {
406 407 408 409 410 411
      String message = 'The command failed';
      if (verboseExceptions) {
        message = 'The command failed\nStdout:\n${runResult.stdout}\n'
            'Stderr:\n${runResult.stderr}';
      }
      runResult.throwException(message);
412 413 414 415 416 417 418 419
    }

    return runResult;
  }

  @override
  Future<Process> start(
    List<String> cmd, {
420
    String? workingDirectory,
421
    bool allowReentrantFlutter = false,
422
    Map<String, String>? environment,
423 424
  }) {
    _traceCommand(cmd, workingDirectory: workingDirectory);
425
    return _processManager.start(
426 427 428 429 430 431 432 433 434
      cmd,
      workingDirectory: workingDirectory,
      environment: _environment(allowReentrantFlutter, environment),
    );
  }

  @override
  Future<int> stream(
    List<String> cmd, {
435
    String? workingDirectory,
436 437 438
    bool allowReentrantFlutter = false,
    String prefix = '',
    bool trace = false,
439 440 441 442
    RegExp? filter,
    RegExp? stdoutErrorMatcher,
    StringConverter? mapFunction,
    Map<String, String>? environment,
443 444 445 446 447 448 449 450 451 452 453 454
  }) async {
    final Process process = await start(
      cmd,
      workingDirectory: workingDirectory,
      allowReentrantFlutter: allowReentrantFlutter,
      environment: environment,
    );
    final StreamSubscription<String> stdoutSubscription = process.stdout
      .transform<String>(utf8.decoder)
      .transform<String>(const LineSplitter())
      .where((String line) => filter == null || filter.hasMatch(line))
      .listen((String line) {
455
        String? mappedLine = line;
456
        if (mapFunction != null) {
457
          mappedLine = mapFunction(line);
458
        }
459 460 461
        if (mappedLine != null) {
          final String message = '$prefix$mappedLine';
          if (stdoutErrorMatcher?.hasMatch(mappedLine) == true) {
462 463
            _logger.printError(message, wrap: false);
          } else if (trace) {
464
            _logger.printTrace(message);
465
          } else {
466
            _logger.printStatus(message, wrap: false);
467
          }
468 469 470 471 472 473 474
        }
      });
    final StreamSubscription<String> stderrSubscription = process.stderr
      .transform<String>(utf8.decoder)
      .transform<String>(const LineSplitter())
      .where((String line) => filter == null || filter.hasMatch(line))
      .listen((String line) {
475
        String? mappedLine = line;
476
        if (mapFunction != null) {
477
          mappedLine = mapFunction(line);
478
        }
479 480
        if (mappedLine != null) {
          _logger.printError('$prefix$mappedLine', wrap: false);
481
        }
482 483 484 485
      });

    // Wait for stdout to be fully processed
    // because process.exitCode may complete first causing flaky tests.
486
    await Future.wait<void>(<Future<void>>[
487 488 489 490
      stdoutSubscription.asFuture<void>(),
      stderrSubscription.asFuture<void>(),
    ]);

491 492 493 494 495 496 497
    // The streams as futures have already completed, so waiting for the
    // potentially async stream cancellation to complete likely has no benefit.
    // Further, some Stream implementations commonly used in tests don't
    // complete the Future returned here, which causes tests using
    // mocks/FakeAsync to fail when these Futures are awaited.
    unawaited(stdoutSubscription.cancel());
    unawaited(stderrSubscription.cancel());
498

499
    return process.exitCode;
500 501 502 503 504
  }

  @override
  bool exitsHappySync(
    List<String> cli, {
505
    Map<String, String>? environment,
506 507
  }) {
    _traceCommand(cli);
508 509 510 511 512
    if (!_processManager.canRun(cli.first)) {
      _logger.printTrace('$cli either does not exist or is not executable.');
      return false;
    }

513
    try {
514
      return _processManager.runSync(cli, environment: environment).exitCode == 0;
515
    } on Exception catch (error) {
516
      _logger.printTrace('$cli failed with $error');
517 518 519 520 521 522 523
      return false;
    }
  }

  @override
  Future<bool> exitsHappy(
    List<String> cli, {
524
    Map<String, String>? environment,
525 526
  }) async {
    _traceCommand(cli);
527 528 529 530 531
    if (!_processManager.canRun(cli.first)) {
      _logger.printTrace('$cli either does not exist or is not executable.');
      return false;
    }

532
    try {
533
      return (await _processManager.run(cli, environment: environment)).exitCode == 0;
534
    } on Exception catch (error) {
535
      _logger.printTrace('$cli failed with $error');
536 537 538 539
      return false;
    }
  }

540 541
  Map<String, String>? _environment(bool allowReentrantFlutter, [
    Map<String, String>? environment,
542 543
  ]) {
    if (allowReentrantFlutter) {
544
      if (environment == null) {
545
        environment = <String, String>{'FLUTTER_ALREADY_LOCKED': 'true'};
546
      } else {
547
        environment['FLUTTER_ALREADY_LOCKED'] = 'true';
548
      }
549 550 551 552 553
    }

    return environment;
  }

554
  void _traceCommand(List<String> args, { String? workingDirectory }) {
555 556
    final String argsText = args.join(' ');
    if (workingDirectory == null) {
557
      _logger.printTrace('executing: $argsText');
558
    } else {
559
      _logger.printTrace('executing: [$workingDirectory/] $argsText');
560 561 562
    }
  }
}