Skip to content
This repository was archived by the owner on Nov 1, 2020. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 35 additions & 28 deletions tests/src/tools/ReadyToRun.SuperIlc/CompileDirectoryCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;

Expand All @@ -13,6 +14,9 @@ class CompileDirectoryCommand
{
public static int CompileDirectory(DirectoryInfo toolDirectory, DirectoryInfo inputDirectory, DirectoryInfo outputDirectory, bool crossgen, bool cpaot, DirectoryInfo[] referencePath)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();

if (toolDirectory == null)
{
Console.WriteLine("--tool-directory is a required argument.");
Expand All @@ -27,8 +31,7 @@ public static int CompileDirectory(DirectoryInfo toolDirectory, DirectoryInfo in

if (outputDirectory == null)
{
Console.WriteLine("--output-directory is a required argument.");
return 1;
outputDirectory = inputDirectory;
}

if (OutputPathIsParentOfInputPath(inputDirectory, outputDirectory))
Expand All @@ -47,56 +50,64 @@ public static int CompileDirectory(DirectoryInfo toolDirectory, DirectoryInfo in
runner = new CrossgenRunner(toolDirectory.ToString(), inputDirectory.ToString(), outputDirectory.ToString(), referencePath?.Select(x => x.ToString())?.ToList());
}

if (outputDirectory.Exists)
string runnerOutputPath = runner.GetOutputPath();
if (Directory.Exists(runnerOutputPath))
{
try
{
outputDirectory.Delete(recursive: true);
Directory.Delete(runnerOutputPath, recursive: true);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Could you update the error message in the catch to refer to runnerOutputPath instead of the now potentially incorrect outputDirectory?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, will do!

}
catch (Exception ex) when (
ex is UnauthorizedAccessException
|| ex is DirectoryNotFoundException
|| ex is IOException
)
{
Console.WriteLine($"Error: Could not delete output folder {outputDirectory.FullName}. {ex.Message}");
Console.WriteLine($"Error: Could not delete output folder {runnerOutputPath}. {ex.Message}");
return 1;
}
}

outputDirectory.Create();
Directory.CreateDirectory(runnerOutputPath);

bool success = true;
List<string> failedCompilationAssemblies = new List<string>();
int successfulCompileCount = 0;
List<ProcessInfo> compilationsToRun = new List<ProcessInfo>();

// Copy unmanaged files (runtime, native dependencies, resources, etc)
foreach (string file in Directory.EnumerateFiles(inputDirectory.FullName))
{
if (ComputeManagedAssemblies.IsManaged(file))
{
// Compile managed code
if (runner.CompileAssembly(file))
{
++successfulCompileCount;
}
else
{
success = false;
failedCompilationAssemblies.Add(file);

// On compile failure, pass through the input IL assembly so the output is still usable
File.Copy(file, Path.Combine(outputDirectory.FullName, Path.GetFileName(file)));
}
ProcessInfo compilationToRun = runner.CompilationProcess(file);
compilationToRun.InputFileName = file;
compilationsToRun.Add(compilationToRun);
}
else
{
// Copy through all other files
File.Copy(file, Path.Combine(outputDirectory.FullName, Path.GetFileName(file)));
File.Copy(file, Path.Combine(runnerOutputPath, Path.GetFileName(file)));
}
}

ParallelRunner.Run(compilationsToRun);

bool success = true;
List<string> failedCompilationAssemblies = new List<string>();
int successfulCompileCount = 0;

foreach (ProcessInfo processInfo in compilationsToRun)
{
if (processInfo.Succeeded)
{
successfulCompileCount++;
}
else
{
File.Copy(processInfo.InputFileName, Path.Combine(runnerOutputPath, Path.GetFileName(processInfo.InputFileName)));
failedCompilationAssemblies.Add(processInfo.InputFileName);
}
}

Console.WriteLine($"Compiled {successfulCompileCount}/{successfulCompileCount + failedCompilationAssemblies.Count} assemblies.");
Console.WriteLine($"Compiled {successfulCompileCount}/{successfulCompileCount + failedCompilationAssemblies.Count} assemblies in {stopwatch.ElapsedMilliseconds} msecs.");

if (failedCompilationAssemblies.Count > 0)
{
Expand All @@ -112,17 +123,13 @@ ex is UnauthorizedAccessException

static bool OutputPathIsParentOfInputPath(DirectoryInfo inputPath, DirectoryInfo outputPath)
{
if (inputPath == outputPath)
return true;

DirectoryInfo parentInfo = inputPath.Parent;
while (parentInfo != null)
{
if (parentInfo == outputPath)
return true;

parentInfo = parentInfo.Parent;

}

return false;
Expand Down
53 changes: 19 additions & 34 deletions tests/src/tools/ReadyToRun.SuperIlc/CompilerRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,49 +25,30 @@ public CompilerRunner(string compilerFolder, string inputFolder, string outputFo
protected abstract string CompilerFileName {get;}
protected abstract IEnumerable<string> BuildCommandLineArguments(string assemblyFileName, string outputFileName);

public bool CompileAssembly(string assemblyFileName)
public ProcessInfo CompilationProcess(string assemblyFileName)
{
CreateOutputFolder();

string outputFileName = GetOutputFileName(assemblyFileName);
string responseFile = GetResponseFileName(assemblyFileName);
var commandLineArgs = BuildCommandLineArguments(assemblyFileName, outputFileName);
CreateResponseFile(responseFile, commandLineArgs);

using (var process = new Process())
{
process.StartInfo.FileName = Path.Combine(_compilerPath, CompilerFileName);
process.StartInfo.Arguments = $"@{responseFile}";
process.StartInfo.UseShellExecute = false;

process.Start();

process.OutputDataReceived += delegate (object sender, DataReceivedEventArgs args)
{
Console.WriteLine(args.Data);
};

process.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs args)
{
Console.WriteLine(args.Data);
};

process.WaitForExit();
ProcessInfo processInfo = new ProcessInfo();
processInfo.ProcessPath = Path.Combine(_compilerPath, CompilerFileName);
processInfo.Arguments = $"@{responseFile}";
processInfo.UseShellExecute = false;
processInfo.LogPath = Path.ChangeExtension(outputFileName, ".log");

if (process.ExitCode != 0)
{
Console.WriteLine($"Compilation of {Path.GetFileName(assemblyFileName)} failed with exit code {process.ExitCode}");
return false;
}
}

return true;
return processInfo;
}

protected void CreateOutputFolder()
{
if (!Directory.Exists(_outputPath))
string outputPath = GetOutputPath();
if (!Directory.Exists(outputPath))
{
Directory.CreateDirectory(_outputPath);
Directory.CreateDirectory(outputPath);
}
}

Expand All @@ -82,9 +63,13 @@ protected void CreateResponseFile(string responseFile, IEnumerable<string> comma
}
}

public string GetOutputPath() =>
Path.Combine(_outputPath, Path.GetFileNameWithoutExtension(CompilerFileName));

// <input>\a.dll -> <output>\a.dll
protected string GetOutputFileName(string assemblyFileName) =>
Path.Combine(_outputPath, $"{Path.GetFileName(assemblyFileName)}");
protected string GetResponseFileName(string assemblyFileName) =>
Path.Combine(_outputPath, $"{Path.GetFileNameWithoutExtension(assemblyFileName)}.{Path.GetFileNameWithoutExtension(CompilerFileName)}.rsp");
public string GetOutputFileName(string fileName) =>
Path.Combine(GetOutputPath(), $"{Path.GetFileName(fileName)}");

public string GetResponseFileName(string assemblyFileName) =>
Path.Combine(GetOutputPath(), Path.GetFileNameWithoutExtension(assemblyFileName) + ".rsp");
}
164 changes: 164 additions & 0 deletions tests/src/tools/ReadyToRun.SuperIlc/ParallelRunner.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

/// <summary>
/// Execute a given number of mutually independent build subprocesses represented by an array of
/// command lines with a given degree of parallelization.
/// </summary>
public sealed class ParallelRunner
{
/// <summary>
/// Helper class for launching mutually independent build subprocesses in parallel.
/// It supports launching the processes and optionally redirecting their standard and
/// error output streams to prevent them from interleaving in the final build output log.
/// Multiple instances of this class representing the individual running processes
/// can exist at the same time.
/// </summmary>
class ProcessSlot
{
/// <summary>
/// Process slot index (used for diagnostic purposes)
/// </summary>
readonly int _slotIndex;

/// <summary>
/// Event used to report that a process has exited
/// </summary>
readonly AutoResetEvent _processExitEvent;

/// <summary>
/// Process object
/// </summary>
ProcessRunner _processRunner;

/// <summary>
/// Constructor stores global slot parameters and initializes the slot state machine
/// </summary>
/// <param name="slotIndex">Process slot index used for diagnostic purposes</param>
/// <param name="processExitEvent">Event used to report process exit</param>
public ProcessSlot(int slotIndex, AutoResetEvent processExitEvent)
{
_slotIndex = slotIndex;
_processExitEvent = processExitEvent;
}

/// <summary>
/// Launch a new process.
/// </summary>
/// <param name="processInfo">application to execute</param>
/// <param name="processIndex">Numeric index used to prefix messages pertaining to this process in the console output</param>
public void Launch(ProcessInfo processInfo, int processIndex)
{
Debug.Assert(_processRunner == null);
Console.WriteLine($"{processIndex}: launching: {processInfo.ProcessPath} {processInfo.Arguments}");

_processRunner = new ProcessRunner(processInfo, processIndex, _processExitEvent);
}

public bool IsAvailable()
{
if (_processRunner == null)
{
return true;
}
if (!_processRunner.IsAvailable())
{
return false;
}
_processRunner.Dispose();
_processRunner = null;
return true;
}
}

/// <summary>
/// Execute a given set of mutually independent build commands with the default
/// degree of parallelism.
/// </summary>
/// <param name="processesToRun">Processes to execute in parallel</param>
public static void Run(IEnumerable<ProcessInfo> processesToRun)
{
Run(processesToRun, degreeOfParallelism: Environment.ProcessorCount);
}

/// <summary>
/// Execute a given set of mutually independent build commands with given degree of
/// parallelism.
/// </summary>
/// <param name="processesToRun">Processes to execute in parallel</param>
/// <param name="degreeOfParallelism">Maximum number of processes to execute in parallel</param>
public static void Run(IEnumerable<ProcessInfo> processesToRun, int degreeOfParallelism)
{
int processCount = processesToRun.Count();
if (processCount < degreeOfParallelism)
{
// We never need a higher DOP than the number of process to execute
degreeOfParallelism = processCount;
}

using (AutoResetEvent processExitEvent = new AutoResetEvent(initialState: false))
{
ProcessSlot[] processSlots = new ProcessSlot[degreeOfParallelism];
for (int index = 0; index < degreeOfParallelism; index++)
{
processSlots[index] = new ProcessSlot(index, processExitEvent);
}

int processIndex = 0;
foreach (ProcessInfo processInfo in processesToRun)
{
// Allocate a process slot, potentially waiting on the exit event
// when all slots are busy (running)
ProcessSlot freeSlot = null;
do
{
foreach (ProcessSlot slot in processSlots)
{
if (slot.IsAvailable())
{
freeSlot = slot;
break;
}
}
if (freeSlot == null)
{
// All slots are busy - wait for a process to finish
processExitEvent.WaitOne();
}
}
while (freeSlot == null);

freeSlot.Launch(processInfo, ++processIndex);
}

// We have launched all the commands, now wait for all processes to finish
bool activeProcessesExist;
do
{
activeProcessesExist = false;
foreach (ProcessSlot slot in processSlots)
{
if (!slot.IsAvailable())
{
activeProcessesExist = true;
}
}
if (activeProcessesExist)
{
processExitEvent.WaitOne();
}
}
while (activeProcessesExist);
}
}
}
Loading