process.dart 17.2 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 'io.dart';
11
import 'logger.dart';
12

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

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

18
// TODO(ianh): We have way too many ways to run subprocesses in this project.
19 20 21 22
// 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.
23

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

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

  /// 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();
44 45
}

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

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

  bool _shutdownHooksRunning = false;

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

  @override
  Future<void> runShutdownHooks() async {
    _logger.printTrace('Running shutdown hooks');
    _shutdownHooksRunning = true;
    try {
69 70 71 72 73
      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);
74 75
        }
      }
76
      await Future.wait<dynamic>(futures);
77 78
    } finally {
      _shutdownHooksRunning = false;
79
    }
80
    _logger.printTrace('Shutdown hooks complete');
81
  }
82 83
}

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

87
  final bool immediate;
88 89
  final int exitCode;

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

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

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

  final ProcessResult processResult;

103 104
  final List<String> _command;

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

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

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

typedef RunResultChecker = bool Function(int);

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

  /// 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.
  ///
148
  /// If [throwOnError] is `true`, and [allowedFailures] is supplied,
149
  /// a [ProcessException] is only thrown on a non-zero exit code if
150
  /// [allowedFailures] returns false when passed the exit code.
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
  ///
  /// 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,
169 170
    RunResultChecker? allowedFailures,
    String? workingDirectory,
171
    bool allowReentrantFlutter = false,
172 173
    Map<String, String>? environment,
    Duration? timeout,
174 175 176 177 178 179 180
    int timeoutRetries = 0,
  });

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

  /// 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, {
194
    String? workingDirectory,
195
    bool allowReentrantFlutter = false,
196
    Map<String, String>? environment,
197 198 199 200 201 202 203 204 205 206
  });

  /// 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.
207 208 209
  ///
  /// If [stdoutErrorMatcher] is non-null, matching lines from stdout will be
  /// treated as errors, just as if they had been logged to stderr instead.
210 211
  Future<int> stream(
    List<String> cmd, {
212
    String? workingDirectory,
213 214 215
    bool allowReentrantFlutter = false,
    String prefix = '',
    bool trace = false,
216 217 218 219
    RegExp? filter,
    RegExp? stdoutErrorMatcher,
    StringConverter? mapFunction,
    Map<String, String>? environment,
220 221 222 223
  });

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

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

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

  final ProcessManager _processManager;

  final Logger _logger;

244 245 246 247
  @override
  Future<RunResult> run(
    List<String> cmd, {
    bool throwOnError = false,
248 249
    RunResultChecker? allowedFailures,
    String? workingDirectory,
250
    bool allowReentrantFlutter = false,
251 252
    Map<String, String>? environment,
    Duration? timeout,
253 254 255 256 257 258 259 260 261 262 263
    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
264
    // we can just use _processManager.run().
265
    if (timeout == null) {
266
      final ProcessResult results = await _processManager.run(
267 268 269 270 271
        cmd,
        workingDirectory: workingDirectory,
        environment: _environment(allowReentrantFlutter, environment),
      );
      final RunResult runResult = RunResult(results, cmd);
272
      _logger.printTrace(runResult.toString());
273
      if (throwOnError && runResult.exitCode != 0 &&
274
          (allowedFailures == null || !allowedFailures(runResult.exitCode))) {
275 276 277 278 279 280
        runResult.throwException('Process exited abnormally:\n$runResult');
      }
      return runResult;
    }

    // When there is a timeout, we have to kill the running process, so we have
281
    // to use _processManager.start() through _runCommand() above.
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    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)
298
          .asFuture<void>();
299 300 301
      final Future<void> stderrFuture = process.stderr
          .transform<String>(const Utf8Decoder(reportErrors: false))
          .listen(stderrBuffer.write)
302
          .asFuture<void>();
303

304 305
      int? exitCode;
      exitCode = await process.exitCode.then<int?>((int x) => x).timeout(timeout, onTimeout: () {
306
        // The process timed out. Kill it.
307
        _processManager.killPid(process.pid);
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
        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;
323
      } on Exception {
324 325 326 327 328 329 330 331 332 333 334 335
        // 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) {
336
        _logger.printTrace(runResult.toString());
337
        if (throwOnError && runResult.exitCode != 0 &&
338
            (allowedFailures == null || !allowedFailures(exitCode))) {
339 340 341 342 343 344 345 346 347 348 349
          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.
350 351 352 353
      _logger.printTrace(
        'Process "${cmd[0]}" timed out. $timeoutRetries attempts left:\n'
        '$runResult',
      );
354 355 356 357 358 359 360 361 362
    }

    // Unreachable.
  }

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

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

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

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

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

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

    return runResult;
  }

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

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

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

490 491 492 493 494 495 496
    // 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());
497

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

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

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

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

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

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

    return environment;
  }

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