runner.dart 5.49 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8
// 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';
import 'dart:io';

9
import 'package:path/path.dart' as path;
10 11 12
import 'package:vm_service_client/vm_service_client.dart';

import 'package:flutter_devicelab/framework/utils.dart';
13 14 15 16 17 18

/// Runs a task in a separate Dart VM and collects the result using the VM
/// service protocol.
///
/// [taskName] is the name of the task. The corresponding task executable is
/// expected to be found under `bin/tasks`.
19 20 21
///
/// Running the task in [silent] mode will suppress standard output from task
/// processes and only print standard errors.
22 23 24 25 26 27
Future<Map<String, dynamic>> runTask(
  String taskName, {
  bool silent = false,
  String localEngine,
  String localEngineSrcPath,
}) async {
28
  final String taskExecutable = 'bin/tasks/$taskName.dart';
29 30 31 32

  if (!file(taskExecutable).existsSync())
    throw 'Executable Dart file not found: $taskExecutable';

33
  final Process runner = await startProcess(dartBin, <String>[
34
    '--enable-vm-service=0', // zero causes the system to choose a free port
35
    '--no-pause-isolates-on-exit',
36 37
    if (localEngine != null) '-DlocalEngine=$localEngine',
    if (localEngineSrcPath != null) '-DlocalEngineSrcPath=$localEngineSrcPath',
38 39 40 41 42
    taskExecutable,
  ]);

  bool runnerFinished = false;

43
  runner.exitCode.whenComplete(() {
44 45 46
    runnerFinished = true;
  });

47
  final Completer<Uri> uri = Completer<Uri>();
48

49
  final StreamSubscription<String> stdoutSub = runner.stdout
50 51
      .transform<String>(const Utf8Decoder())
      .transform<String>(const LineSplitter())
52
      .listen((String line) {
53
    if (!uri.isCompleted) {
54 55
      final Uri serviceUri = parseServiceUri(line, prefix: 'Observatory listening on ');
      if (serviceUri != null)
56
        uri.complete(serviceUri);
57
    }
58 59 60
    if (!silent) {
      stdout.writeln('[$taskName] [STDOUT] $line');
    }
61 62
  });

63
  final StreamSubscription<String> stderrSub = runner.stderr
64 65
      .transform<String>(const Utf8Decoder())
      .transform<String>(const LineSplitter())
66 67 68 69 70
      .listen((String line) {
    stderr.writeln('[$taskName] [STDERR] $line');
  });

  try {
71
    final VMIsolateRef isolate = await _connectToRunnerIsolate(await uri.future);
72
    final Map<String, dynamic> taskResult = await isolate.invokeExtension('ext.cocoonRunTask') as Map<String, dynamic>;
73
    await runner.exitCode;
74 75 76
    return taskResult;
  } finally {
    if (!runnerFinished)
77
      runner.kill(ProcessSignal.sigkill);
78
    await cleanupSystem();
79 80 81 82 83
    await stdoutSub.cancel();
    await stderrSub.cancel();
  }
}

84
Future<VMIsolateRef> _connectToRunnerIsolate(Uri vmServiceUri) async {
85
  final List<String> pathSegments = <String>[
86
    // Add authentication code.
87 88 89
    if (vmServiceUri.pathSegments.isNotEmpty) vmServiceUri.pathSegments[0],
    'ws',
  ];
90 91
  final String url = vmServiceUri.replace(scheme: 'ws', pathSegments:
      pathSegments).toString();
92
  final Stopwatch stopwatch = Stopwatch()..start();
93 94 95 96 97 98 99

  while (true) {
    try {
      // Make sure VM server is up by successfully opening and closing a socket.
      await (await WebSocket.connect(url)).close();

      // Look up the isolate.
100
      final VMServiceClient client = VMServiceClient.connect(url);
101
      final VM vm = await client.getVM();
102
      final VMIsolateRef isolate = vm.isolates.single;
103
      final String response = await isolate.invokeExtension('ext.cocoonRunnerReady') as String;
104
      if (response != 'ready')
105
        throw 'not ready yet';
106
      return isolate;
107
    } catch (error) {
108 109 110
      if (stopwatch.elapsed > const Duration(seconds: 10))
        print('VM service still not ready after ${stopwatch.elapsed}: $error\nContinuing to retry...');
      await Future<void>.delayed(const Duration(milliseconds: 50));
111 112 113
    }
  }
}
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

Future<void> cleanupSystem() async {
  print('\n\nCleaning up system after task...');
  final String javaHome = await findJavaHome();
  if (javaHome != null) {
    // To shut gradle down, we have to call "gradlew --stop".
    // To call gradlew, we need to have a gradle-wrapper.properties file along
    // with a shell script, a .jar file, etc. We get these from various places
    // as you see in the code below, and we save them all into a temporary dir
    // which we can then delete after.
    // All the steps below are somewhat tolerant of errors, because it doesn't
    // really matter if this succeeds every time or not.
    print('\nTelling Gradle to shut down (JAVA_HOME=$javaHome)');
    final String gradlewBinaryName = Platform.isWindows ? 'gradlew.bat' : 'gradlew';
    final Directory tempDir = Directory.systemTemp.createTempSync('flutter_devicelab_shutdown_gradle.');
129
    recursiveCopy(Directory(path.join(flutterDirectory.path, 'bin', 'cache', 'artifacts', 'gradle_wrapper')), tempDir);
130
    copy(File(path.join(path.join(flutterDirectory.path, 'packages', 'flutter_tools'), 'templates', 'app', 'android.tmpl', 'gradle', 'wrapper', 'gradle-wrapper.properties')), Directory(path.join(tempDir.path, 'gradle', 'wrapper')));
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
    if (!Platform.isWindows) {
      await exec(
        'chmod',
        <String>['a+x', path.join(tempDir.path, gradlewBinaryName)],
        canFail: true,
      );
    }
    await exec(
      path.join(tempDir.path, gradlewBinaryName),
      <String>['--stop'],
      environment: <String, String>{ 'JAVA_HOME': javaHome },
      workingDirectory: tempDir.path,
      canFail: true,
    );
    rmTree(tempDir);
    print('\n');
  } else {
    print('Could not determine JAVA_HOME; not shutting down Gradle.');
  }
150
}