-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
284 lines (253 loc) · 11.5 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using CpuCount;
using System.Linq;
namespace parallel_runner
{
public class Program
{
private static ReaderWriterLockSlim sProtectionMutex = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
private static Dictionary<Process, String> sProcessToName = new Dictionary<Process, String>();
private static int sMaxLength = 0;
private static string sVersion = "2.0.3";
static public void Main(string[] args)
{
bool printUsage = false;
bool useStdin = false;
String commandsFileName = null;
for (int i = 0; i < args.Length; i++)
{
String s = args[i].ToLower();
if (s[0] == '/')
{
s.Replace('/', '-');
}
if (s == "-v" || s == "-?" || s == "-version" || s == "--version")
{
printUsage = true;
}
if (s == "-file")
{
i++;
if (i < args.Length)
{
commandsFileName = args[i];
}
}
// Read from stdin
if (s == "-")
{
i++;
if (i < args.Length)
{
useStdin = true;
}
}
}
if (printUsage || ((String.IsNullOrEmpty(commandsFileName) || !File.Exists(commandsFileName) && !useStdin)))
{
Console.WriteLine("parallel_runner Version:{0}", sVersion);
Console.WriteLine(" Will run multiple command lines in parallel. Pass in a command file.");
Console.WriteLine(" Each line in the file is a command line to execute in parallel.");
Console.WriteLine(" There is also optionally a name for each process used when reporting.");
Console.WriteLine("Usage: ");
Console.WriteLine(" runner -file commandList.txt");
Console.WriteLine("File Format: ");
Console.WriteLine(": [name 1] : command1 args");
Console.WriteLine(": [name 2] : command2 args");
Console.WriteLine(": [name 3] : command3 args");
if(!printUsage)
Environment.ExitCode = 1;
return;
}
StreamReader processCommands;
if(useStdin)
processCommands = new StreamReader(Console.OpenStandardInput());
else
processCommands = new StreamReader(commandsFileName);
List<Process> processes = new List<Process>();
int numCPUs = Machine.GetPhysicalProcessorCount();
int numCores = Machine.GetPhysicalProcessorCores();
int numThreads = Environment.ProcessorCount;
Console.WriteLine("Num CPUs = {0}", numCPUs.ToString());
Console.WriteLine("Num CPU Cores = {0}", numCores.ToString());
Console.WriteLine("Num CPU Threads = {0}", numThreads.ToString());
while (!processCommands.EndOfStream)
{
//-------------------------------------------------------------
// Parse metadata and command line
//-------------------------------------------------------------
string processFile = null;
string processName = null;
string commandLine = processCommands.ReadLine().TrimStart();
// Empty line.
if (String.IsNullOrWhiteSpace(commandLine))
continue;
// Comments
if (commandLine.StartsWith("#") || commandLine.StartsWith("\\\\"))
continue;
if (commandLine.StartsWith(":"))
{
int endofName = commandLine.IndexOf(':', 1);
processName = commandLine.Substring(1, endofName - 1);
commandLine = commandLine.Remove(0, endofName + 1).TrimStart();
}
if (commandLine.StartsWith("\""))
{
int endofName = commandLine.IndexOf('\"', 1);
processFile = commandLine.Substring(1, endofName - 1);
commandLine = commandLine.Remove(0, endofName + 1).TrimStart();
}
else
{
int endofName = commandLine.IndexOf(' ', 1);
if (endofName >= 0)
{
processFile = commandLine.Substring(0, endofName - 0);
commandLine = commandLine.Remove(0, endofName + 0).TrimStart();
}
else
{
processFile = commandLine;
commandLine = "";
}
}
//-------------------------------------------------------------
// Build process description based on command line / metadata
//-------------------------------------------------------------
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo(processFile);
psi.Arguments = commandLine;
psi.CreateNoWindow = false;
psi.UseShellExecute = false;
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
p.OutputDataReceived += new DataReceivedEventHandler(StdOutEventHandler);
p.ErrorDataReceived += new DataReceivedEventHandler(StdErrEventHandler);
p.StartInfo = psi;
//-------------------------------------------------------------
// Add to List
//-------------------------------------------------------------
processes.Add(p);
String name = String.IsNullOrWhiteSpace(processName) ? p.Id.ToString() : processName;
sProcessToName.Add(p, name);
if (name.Length > sMaxLength)
{
sMaxLength = name.Length;
}
}
processCommands.Close();
Mutex ExceptionMutex = new Mutex();
System.Text.StringBuilder ExceptionInfo = new System.Text.StringBuilder();
//-------------------------------------------------------------
// Run Them!
//-------------------------------------------------------------
var options = new ParallelOptions()
{
// Limit parallelism to the number of core. C# will go even wider but
// this actually slows down progress most times... unless you have programs
// that block a LOT.
MaxDegreeOfParallelism = Math.Min(numCores, numThreads - 1)
};
Parallel.ForEach(processes, options, p =>
{
try
{
p.Start();
sProtectionMutex.EnterWriteLock();
Console.WriteLine("{0," + sMaxLength + "}:{1,8}-START", sProcessToName[p], p.StartTime.ToShortTimeString());
sProtectionMutex.ExitWriteLock();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
sProtectionMutex.EnterWriteLock();
Console.WriteLine("{0," + sMaxLength + "}:{1,8}-Exit Code:{2}", sProcessToName[p], p.ExitTime.ToShortTimeString(), p.ExitCode.ToString());
sProtectionMutex.ExitWriteLock();
}
catch (Exception e)
{
ExceptionMutex.WaitOne();
ExceptionInfo.AppendFormat("{0," + sMaxLength + "}:{1,8}-EXCEPTION:{2}", sProcessToName[p], DateTime.Now.ToShortTimeString(), e.ToString());
ExceptionInfo.AppendLine();
sProcessToName.Remove(p);
ExceptionMutex.ReleaseMutex();
}
} //close lambda expression
); //close method invocation
Console.WriteLine("");
Console.WriteLine("[All Operations Completed]");
Console.WriteLine("Summary:");
foreach (KeyValuePair<Process, String> p in sProcessToName.OrderBy(p => p.Key.ExitCode))
{
if (p.Key.ExitCode != 0)
{
Environment.ExitCode = 1;
BeginWriteError();
Console.Error.Write("{0," + sMaxLength + "}:{1,8}s ExitCode:{2}", p.Value, (p.Key.ExitTime - p.Key.StartTime).Seconds.ToString(), p.Key.ExitCode.ToString());
EndWriteError();
// This finishes off the color change
Console.Error.WriteLine();
}
else
{
Console.WriteLine("{0," + sMaxLength + "}:{1,8}s ExitCode:{2}", p.Value, (p.Key.ExitTime - p.Key.StartTime).Seconds.ToString(), p.Key.ExitCode.ToString());
}
}
if (ExceptionInfo.Length != 0)
{
Environment.ExitCode = 1;
BeginWriteError();
Console.Error.Write(ExceptionInfo);
EndWriteError();
}
}
static ConsoleColor sSavedBgColor = ConsoleColor.Black;
static ConsoleColor sSavedFgColor = ConsoleColor.White;
private static void BeginWriteError()
{
sSavedBgColor = Console.BackgroundColor;
sSavedFgColor = Console.ForegroundColor;
Console.BackgroundColor = ConsoleColor.DarkRed;
Console.ForegroundColor = ConsoleColor.White;
}
private static void EndWriteError()
{
Console.BackgroundColor = sSavedBgColor;
Console.ForegroundColor = sSavedFgColor;
}
private static void StdOutEventHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
Process p = (Process)sendingProcess;
if (!String.IsNullOrEmpty(outLine.Data))
{
sProtectionMutex.EnterWriteLock();
Console.Write("{0," + sMaxLength + "}:{1,8}-", sProcessToName[p], DateTime.Now.ToShortTimeString());
Console.WriteLine(outLine.Data);
sProtectionMutex.ExitWriteLock();
}
}
private static void StdErrEventHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
Process p = (Process)sendingProcess;
if (!String.IsNullOrEmpty(outLine.Data))
{
sProtectionMutex.EnterWriteLock();
Environment.ExitCode = 1;
BeginWriteError();
Console.Error.Write("{0," + sMaxLength + "}:{1,8}-", sProcessToName[p], DateTime.Now.ToShortTimeString());
Console.Error.Write(outLine.Data);
EndWriteError();
// This finishes off the color change
Console.Error.WriteLine();
sProtectionMutex.ExitWriteLock();
}
}
}
}