1 | using System.Diagnostics;
|
---|
2 | using System.IO;
|
---|
3 | using System.Threading.Tasks;
|
---|
4 | using HeuristicLab.PluginInfrastructure.Exceptions;
|
---|
5 |
|
---|
6 | namespace HeuristicLab.PluginInfrastructure {
|
---|
7 | /// <summary>
|
---|
8 | /// IRunner for isolation with docker.
|
---|
9 | /// </summary>
|
---|
10 | public class DockerRunnerHost : RunnerHost {
|
---|
11 | #region Constants
|
---|
12 | private readonly static string Docker = "docker";
|
---|
13 | private readonly static string ContainerStartup = "container run -i --rm ";
|
---|
14 | private readonly static string MountingLinux = @"--mount type=bind,source=/c/Users/,target=/Users ";
|
---|
15 | private readonly static string MountingWindows = @"--mount type=bind,source=C:\Users\,target=C:\Users\ ";
|
---|
16 | private readonly static string LinuxImage = "." + Path.DirectorySeparatorChar + "DockerLinuxBuild" + Path.DirectorySeparatorChar + "Dockerfile";
|
---|
17 | private readonly static string WindowsImage = "." + Path.DirectorySeparatorChar + "DockerWindowsBuild" + Path.DirectorySeparatorChar + "Dockerfile";
|
---|
18 | private readonly static string Image = "heuristiclab33:latest";
|
---|
19 | private readonly static string DockerExceptionMessage = "Docker is not running!";
|
---|
20 | #endregion
|
---|
21 |
|
---|
22 | #region Constructors
|
---|
23 | public DockerRunnerHost()
|
---|
24 | : base(Docker, ContainerStartup + GetTargetOSMounting() + Image, null, null, null) {
|
---|
25 | }
|
---|
26 | #endregion
|
---|
27 |
|
---|
28 | #region Helper
|
---|
29 |
|
---|
30 | private static string GetTargetOSMounting() {
|
---|
31 | Task<bool> win = Task.Run(() => BuildImage(WindowsImage));
|
---|
32 | Task<bool> lin = Task.Run(() => BuildImage(LinuxImage));
|
---|
33 | if (win.Result) return MountingWindows;
|
---|
34 | else if (lin.Result) return MountingLinux;
|
---|
35 | else throw new DockerException(DockerExceptionMessage);
|
---|
36 | }
|
---|
37 |
|
---|
38 | private static bool BuildImage(string pathToDockerfile) {
|
---|
39 | var process = new Process {
|
---|
40 | StartInfo = new ProcessStartInfo {
|
---|
41 | FileName = Docker,
|
---|
42 | Arguments = "image build -t " + Image +
|
---|
43 | " -f " + Path.GetFullPath(pathToDockerfile) +
|
---|
44 | " .",
|
---|
45 | UseShellExecute = false,
|
---|
46 | RedirectStandardOutput = true,
|
---|
47 | RedirectStandardInput = false,
|
---|
48 | RedirectStandardError = true,
|
---|
49 | CreateNoWindow = false
|
---|
50 | },
|
---|
51 | EnableRaisingEvents = false
|
---|
52 | };
|
---|
53 | process.Start();
|
---|
54 | process.BeginOutputReadLine();
|
---|
55 | process.BeginErrorReadLine();
|
---|
56 | process.WaitForExit();
|
---|
57 | return process.ExitCode == 0;
|
---|
58 | }
|
---|
59 | #endregion
|
---|
60 | }
|
---|
61 | }
|
---|