process.dart 11.3 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:convert';

8
import '../globals.dart';
9
import 'file_system.dart';
10
import 'io.dart';
11
import 'process_manager.dart';
12
import 'utils.dart';
13

Devon Carew's avatar
Devon Carew committed
14
typedef String StringConverter(String string);
15 16

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

19 20
// TODO(ianh): We have way too many ways to run subprocesses in this project.

21 22 23 24 25 26 27 28 29
/// The stage in which a [ShutdownHook] will be run. 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.
class ShutdownStage implements Comparable<ShutdownStage> {
  const ShutdownStage._(this._priority);

  /// The stage priority. Smaller values will be run before larger values.
  final int _priority;

30 31 32 33
  /// The stage before the invocation recording (if one exists) is serialized
  /// to disk. Tasks performed during this stage *will* be recorded.
  static const ShutdownStage STILL_RECORDING = const ShutdownStage._(1);

34 35 36
  /// The stage during which the invocation recording (if one exists) will be
  /// serialized to disk. Invocations performed after this stage will not be
  /// recorded.
37
  static const ShutdownStage SERIALIZE_RECORDING = const ShutdownStage._(2);
38 39 40

  /// The stage during which a serialized recording will be refined (e.g.
  /// cleansed for tests, zipped up for bug reporting purposes, etc.).
41
  static const ShutdownStage POST_PROCESS_RECORDING = const ShutdownStage._(3);
42 43

  /// The stage during which temporary files and directories will be deleted.
44
  static const ShutdownStage CLEANUP = const ShutdownStage._(4);
45 46 47 48 49 50

  @override
  int compareTo(ShutdownStage other) => _priority.compareTo(other._priority);
}

Map<ShutdownStage, List<ShutdownHook>> _shutdownHooks = <ShutdownStage, List<ShutdownHook>>{};
51
bool _shutdownHooksRunning = false;
52 53 54 55 56 57 58 59 60 61

/// Registers a [ShutdownHook] to be executed before the VM exits.
///
/// If [stage] is specified, the shutdown hook will be run during the specified
/// stage. By default, the shutdown hook will be run during the
/// [ShutdownStage.CLEANUP] stage.
void addShutdownHook(
  ShutdownHook shutdownHook, [
  ShutdownStage stage = ShutdownStage.CLEANUP,
]) {
62
  assert(!_shutdownHooksRunning);
63
  _shutdownHooks.putIfAbsent(stage, () => <ShutdownHook>[]).add(shutdownHook);
64 65
}

66 67 68 69 70 71 72
/// 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.
73
Future<Null> runShutdownHooks() async {
74 75
  _shutdownHooksRunning = true;
  try {
76
    for (ShutdownStage stage in _shutdownHooks.keys.toList()..sort()) {
77 78
      final List<ShutdownHook> hooks = _shutdownHooks.remove(stage);
      final List<Future<dynamic>> futures = <Future<dynamic>>[];
79 80 81 82
      for (ShutdownHook shutdownHook in hooks)
        futures.add(shutdownHook());
      await Future.wait<dynamic>(futures);
    }
83 84 85 86
  } finally {
    _shutdownHooksRunning = false;
  }
  assert(_shutdownHooks.isEmpty);
87 88
}

89 90 91 92 93 94 95 96 97
Map<String, String> _environment(bool allowReentrantFlutter, [Map<String, String> environment]) {
  if (allowReentrantFlutter) {
    if (environment == null)
      environment = <String, String>{ 'FLUTTER_ALREADY_LOCKED': 'true' };
    else
      environment['FLUTTER_ALREADY_LOCKED'] = 'true';
  }

  return environment;
98 99
}

100 101
/// This runs the command in the background from the specified working
/// directory. Completes when the process has been started.
102 103
Future<Process> runCommand(List<String> cmd, {
  String workingDirectory,
104 105
  bool allowReentrantFlutter: false,
  Map<String, String> environment
106
}) {
107
  _traceCommand(cmd, workingDirectory: workingDirectory);
108
  return processManager.start(
109
    cmd,
110
    workingDirectory: workingDirectory,
111
    environment: _environment(allowReentrantFlutter, environment),
112 113 114
  );
}

115
/// This runs the command and streams stdout/stderr from the child process to
116
/// this process' stdout/stderr. Completes with the process's exit code.
117
Future<int> runCommandAndStreamOutput(List<String> cmd, {
Devon Carew's avatar
Devon Carew committed
118
  String workingDirectory,
119
  bool allowReentrantFlutter: false,
120
  String prefix: '',
121
  bool trace: false,
122
  RegExp filter,
123 124
  StringConverter mapFunction,
  Map<String, String> environment
125
}) async {
126
  final Process process = await runCommand(
127 128
    cmd,
    workingDirectory: workingDirectory,
129 130
    allowReentrantFlutter: allowReentrantFlutter,
    environment: environment
131
  );
132
  final StreamSubscription<String> stdoutSubscription = process.stdout
133 134 135 136
    .transform(UTF8.decoder)
    .transform(const LineSplitter())
    .where((String line) => filter == null ? true : filter.hasMatch(line))
    .listen((String line) {
Devon Carew's avatar
Devon Carew committed
137 138
      if (mapFunction != null)
        line = mapFunction(line);
139
      if (line != null) {
140
        final String message = '$prefix$line';
141 142 143 144 145
        if (trace)
          printTrace(message);
        else
          printStatus(message);
      }
146
    });
147
  final StreamSubscription<String> stderrSubscription = process.stderr
148 149 150 151
    .transform(UTF8.decoder)
    .transform(const LineSplitter())
    .where((String line) => filter == null ? true : filter.hasMatch(line))
    .listen((String line) {
Devon Carew's avatar
Devon Carew committed
152 153 154 155
      if (mapFunction != null)
        line = mapFunction(line);
      if (line != null)
        printError('$prefix$line');
156
    });
157 158 159

  // Wait for stdout to be fully processed
  // because process.exitCode may complete first causing flaky tests.
160
  await waitGroup<Null>(<Future<Null>>[
161 162 163
    stdoutSubscription.asFuture<Null>(),
    stderrSubscription.asFuture<Null>(),
  ]);
164 165 166 167 168

  await waitGroup<Null>(<Future<Null>>[
    stdoutSubscription.cancel(),
    stderrSubscription.cancel(),
  ]);
169

Hixie's avatar
Hixie committed
170
  return await process.exitCode;
171
}
172

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
/// Runs the [command] interactively, connecting the stdin/stdout/stderr
/// streams of this process to those of the child process. Completes with
/// the exit code of the child process.
Future<int> runInteractively(List<String> command, {
  String workingDirectory,
  bool allowReentrantFlutter: false,
  Map<String, String> environment
}) async {
  final Process process = await runCommand(
    command,
    workingDirectory: workingDirectory,
    allowReentrantFlutter: allowReentrantFlutter,
    environment: environment,
  );
  process.stdin.addStream(stdin);
  // Wait for stdout and stderr to be fully processed, because process.exitCode
  // may complete first.
  Future.wait<dynamic>(<Future<dynamic>>[
    stdout.addStream(process.stdout),
    stderr.addStream(process.stderr),
  ]);
  return await process.exitCode;
}

Ian Hickson's avatar
Ian Hickson committed
197
Future<Null> runAndKill(List<String> cmd, Duration timeout) {
198
  final Future<Process> proc = runDetached(cmd);
Ian Hickson's avatar
Ian Hickson committed
199
  return new Future<Null>.delayed(timeout, () async {
200
    printTrace('Intentionally killing ${cmd[0]}');
201
    processManager.killPid((await proc).pid);
202 203 204
  });
}

Hixie's avatar
Hixie committed
205
Future<Process> runDetached(List<String> cmd) {
206
  _traceCommand(cmd);
207
  final Future<Process> proc = processManager.start(
208 209
    cmd,
    mode: ProcessStartMode.DETACHED,
Devon Carew's avatar
Devon Carew committed
210
  );
211
  return proc;
212
}
213

214 215
Future<RunResult> runAsync(List<String> cmd, {
  String workingDirectory,
216 217
  bool allowReentrantFlutter: false,
  Map<String, String> environment
218
}) async {
219
  _traceCommand(cmd, workingDirectory: workingDirectory);
220
  final ProcessResult results = await processManager.run(
221
    cmd,
222
    workingDirectory: workingDirectory,
223
    environment: _environment(allowReentrantFlutter, environment),
224
  );
225
  final RunResult runResults = new RunResult(results);
226 227 228 229
  printTrace(runResults.toString());
  return runResults;
}

230 231 232 233 234 235 236 237 238 239 240 241
Future<RunResult> runCheckedAsync(List<String> cmd, {
  String workingDirectory,
  bool allowReentrantFlutter: false,
  Map<String, String> environment
}) async {
  final RunResult result = await runAsync(
      cmd,
      workingDirectory: workingDirectory,
      allowReentrantFlutter: allowReentrantFlutter,
      environment: environment
  );
  if (result.exitCode != 0)
242
    throw 'Exit code ${result.exitCode} from: ${cmd.join(' ')}:\n$result';
243 244 245
  return result;
}

246
bool exitsHappy(List<String> cli) {
247
  _traceCommand(cli);
248
  try {
249
    return processManager.runSync(cli).exitCode == 0;
250 251 252 253 254
  } catch (error) {
    return false;
  }
}

255 256 257 258 259 260 261 262 263
Future<bool> exitsHappyAsync(List<String> cli) async {
  _traceCommand(cli);
  try {
    return (await processManager.run(cli)).exitCode == 0;
  } catch (error) {
    return false;
  }
}

264 265 266 267 268
/// Run cmd and return stdout.
///
/// Throws an error if cmd exits with a non-zero value.
String runCheckedSync(List<String> cmd, {
  String workingDirectory,
269 270
  bool allowReentrantFlutter: false,
  bool hideStdout: false,
271
  Map<String, String> environment,
272 273 274 275 276
}) {
  return _runWithLoggingSync(
    cmd,
    workingDirectory: workingDirectory,
    allowReentrantFlutter: allowReentrantFlutter,
277
    hideStdout: hideStdout,
278
    checked: true,
279
    noisyErrors: true,
280
    environment: environment,
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
  );
}

/// Run cmd and return stdout.
String runSync(List<String> cmd, {
  String workingDirectory,
  bool allowReentrantFlutter: false
}) {
  return _runWithLoggingSync(
    cmd,
    workingDirectory: workingDirectory,
    allowReentrantFlutter: allowReentrantFlutter
  );
}

296
void _traceCommand(List<String> args, { String workingDirectory }) {
297
  final String argsText = args.join(' ');
298 299 300
  if (workingDirectory == null)
    printTrace(argsText);
  else
301
    printTrace('[$workingDirectory${fs.path.separator}] $argsText');
302 303
}

304 305
String _runWithLoggingSync(List<String> cmd, {
  bool checked: false,
Devon Carew's avatar
Devon Carew committed
306
  bool noisyErrors: false,
307
  bool throwStandardErrorOnError: false,
Devon Carew's avatar
Devon Carew committed
308
  String workingDirectory,
309 310
  bool allowReentrantFlutter: false,
  bool hideStdout: false,
311
  Map<String, String> environment,
312
}) {
313
  _traceCommand(cmd, workingDirectory: workingDirectory);
314
  final ProcessResult results = processManager.runSync(
315
    cmd,
316
    workingDirectory: workingDirectory,
317
    environment: _environment(allowReentrantFlutter, environment),
318
  );
Devon Carew's avatar
Devon Carew committed
319 320 321

  printTrace('Exit code ${results.exitCode} from: ${cmd.join(' ')}');

322
  if (results.stdout.isNotEmpty && !hideStdout) {
Devon Carew's avatar
Devon Carew committed
323 324 325 326 327 328
    if (results.exitCode != 0 && noisyErrors)
      printStatus(results.stdout.trim());
    else
      printTrace(results.stdout.trim());
  }

329
  if (results.exitCode != 0) {
Devon Carew's avatar
Devon Carew committed
330 331
    if (results.stderr.isNotEmpty) {
      if (noisyErrors)
Devon Carew's avatar
Devon Carew committed
332
        printError(results.stderr.trim());
Devon Carew's avatar
Devon Carew committed
333 334
      else
        printTrace(results.stderr.trim());
Devon Carew's avatar
Devon Carew committed
335
    }
Devon Carew's avatar
Devon Carew committed
336

337 338 339
    if (throwStandardErrorOnError)
      throw results.stderr.trim();

340
    if (checked)
Devon Carew's avatar
Devon Carew committed
341
      throw 'Exit code ${results.exitCode} from: ${cmd.join(' ')}';
342
  }
Devon Carew's avatar
Devon Carew committed
343

344
  return results.stdout.trim();
345
}
346 347

class ProcessExit implements Exception {
348
  ProcessExit(this.exitCode, {this.immediate: false});
349

350
  final bool immediate;
351 352
  final int exitCode;

Hixie's avatar
Hixie committed
353
  String get message => 'ProcessExit: $exitCode';
354 355

  @override
356 357
  String toString() => message;
}
358 359 360 361 362 363 364

class RunResult {
  RunResult(this.processResult);

  final ProcessResult processResult;

  int get exitCode => processResult.exitCode;
365 366
  String get stdout => processResult.stdout;
  String get stderr => processResult.stderr;
367 368 369

  @override
  String toString() {
370
    final StringBuffer out = new StringBuffer();
371 372 373 374 375 376 377
    if (processResult.stdout.isNotEmpty)
      out.writeln(processResult.stdout);
    if (processResult.stderr.isNotEmpty)
      out.writeln(processResult.stderr);
    return out.toString().trimRight();
  }
}