-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathInvokeParallelCommand.cs
More file actions
365 lines (324 loc) · 9.85 KB
/
Copy pathInvokeParallelCommand.cs
File metadata and controls
365 lines (324 loc) · 9.85 KB
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading;
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable AutoPropertyCanBeMadeGetOnly.Global
// ReSharper disable MemberCanBePrivate.Global
namespace PSParallel
{
[Alias("ipa")]
[Cmdlet("Invoke", "Parallel", DefaultParameterSetName = "Progress")]
public sealed class InvokeParallelCommand : PSCmdlet, IDisposable
{
[Parameter(Mandatory = true, Position = 0)]
public ScriptBlock ScriptBlock { get; set; }
[Parameter(ParameterSetName = "Progress")]
[Alias("ppi")]
public int ParentProgressId { get; set; } = -1;
[Parameter(ParameterSetName = "Progress")]
[Alias("pi")]
public int ProgressId { get; set; } = 1000;
[Parameter(ParameterSetName = "Progress")]
[Alias("pa")]
[ValidateNotNullOrEmpty]
public string ProgressActivity { get; set; } = "Invoke-Parallel";
[Parameter]
[ValidateRange(1, 128)]
public int ThrottleLimit { get; set; } = 32;
[Parameter]
[AllowNull]
[Alias("iss")]
public InitialSessionState InitialSessionState { get; set; }
[Parameter(ValueFromPipeline = true, Mandatory = true)]
public PSObject InputObject { get; set; }
[Parameter(ParameterSetName = "NoProgress")]
public SwitchParameter NoProgress { get; set; }
private readonly CancellationTokenSource _cancelationTokenSource = new CancellationTokenSource();
internal PowershellPool PowershellPool;
private static InitialSessionState GetSessionState(SessionState sessionState)
{
var initialSessionState = InitialSessionState.CreateDefault2();
CaptureVariables(sessionState, initialSessionState);
CaptureFunctions(sessionState, initialSessionState);
return initialSessionState;
}
private static IEnumerable<FunctionInfo> GetFunctions(SessionState sessionState)
{
try
{
var functionDrive = sessionState.InvokeProvider.Item.Get("function:");
return (Dictionary<string, FunctionInfo>.ValueCollection)functionDrive[0].BaseObject;
}
catch (DriveNotFoundException)
{
return new FunctionInfo[] { };
}
}
private static IEnumerable<PSVariable> GetVariables(SessionState sessionState)
{
try
{
string[] noTouchVariables = { "null", "true", "false", "Error" };
var variables = sessionState.InvokeProvider.Item.Get("Variable:");
var psVariables = (IEnumerable<PSVariable>)variables[0].BaseObject;
return psVariables.Where(p => !noTouchVariables.Contains(p.Name));
}
catch (DriveNotFoundException)
{
return new PSVariable[] { };
}
}
private static void CaptureFunctions(SessionState sessionState, InitialSessionState initialSessionState)
{
var functions = GetFunctions(sessionState);
foreach (var func in functions)
{
initialSessionState.Commands.Add(new SessionStateFunctionEntry(func.Name, func.Definition));
}
}
private static void CaptureVariables(SessionState sessionState, InitialSessionState initialSessionState)
{
var variables = GetVariables(sessionState);
foreach (var variable in variables)
{
var existing = initialSessionState.Variables[variable.Name].FirstOrDefault();
if (existing != null)
{
if ((existing.Options & (ScopedItemOptions.Constant | ScopedItemOptions.ReadOnly)) != ScopedItemOptions.None)
{
continue;
}
else
{
initialSessionState.Variables.Remove(existing.Name, existing.GetType());
initialSessionState.Variables.Add(new SessionStateVariableEntry(variable.Name, variable.Value, variable.Description, variable.Options, variable.Attributes));
}
}
else
{
initialSessionState.Variables.Add(new SessionStateVariableEntry(variable.Name, variable.Value, variable.Description, variable.Options, variable.Attributes));
}
}
}
private void ValidateParameters()
{
if (NoProgress)
{
var boundParameters = MyInvocation.BoundParameters;
foreach (var p in new[] { nameof(ProgressActivity), nameof(ParentProgressId), nameof(ProgressId) })
{
if (!boundParameters.ContainsKey(p)) continue;
var argumentException = new ArgumentException($"'{p}' must not be specified together with 'NoProgress'", p);
ThrowTerminatingError(new ErrorRecord(argumentException, "InvalidProgressParam", ErrorCategory.InvalidArgument, p));
}
}
}
InitialSessionState GetSessionState()
{
if (MyInvocation.BoundParameters.ContainsKey(nameof(InitialSessionState)))
{
if (InitialSessionState == null)
{
return InitialSessionState.Create();
}
return InitialSessionState;
}
return GetSessionState(base.SessionState);
}
private WorkerBase _worker;
protected override void BeginProcessing()
{
ValidateParameters();
var iss = GetSessionState();
PowershellPool = new PowershellPool(ThrottleLimit, iss, _cancelationTokenSource.Token);
_worker = NoProgress ? (WorkerBase) new NoProgressWorker(this) : new ProgressWorker(this);
}
protected override void ProcessRecord()
{
_worker.ProcessRecord(InputObject);
}
protected override void EndProcessing()
{
_worker.EndProcessing();
}
protected override void StopProcessing()
{
_cancelationTokenSource.Cancel();
PowershellPool?.Stop();
}
private void WriteOutputs()
{
Debug.WriteLine("Processing output");
if (_cancelationTokenSource.IsCancellationRequested)
{
return;
}
var streams = PowershellPool.Streams;
foreach (var o in streams.Output.ReadAll())
{
WriteObject(o, false);
}
foreach (var o in streams.Debug.ReadAll())
{
WriteDebug(o.Message);
}
foreach (var e in streams.Error.ReadAll())
{
WriteError(e);
}
foreach (var w in streams.Warning.ReadAll())
{
WriteWarning(w.Message);
}
foreach (var i in streams.Information.ReadAll())
{
WriteInformation(i);
}
foreach (var v in streams.Verbose.ReadAll())
{
WriteVerbose(v.Message);
}
_worker.WriteProgress(streams.ReadAllProgress());
}
public void Dispose()
{
PowershellPool?.Dispose();
_cancelationTokenSource.Dispose();
}
private abstract class WorkerBase
{
protected readonly InvokeParallelCommand Cmdlet;
protected readonly PowershellPool Pool;
protected bool Stopping => Cmdlet.Stopping;
protected void WriteOutputs() => Cmdlet.WriteOutputs();
protected void WriteProgress(ProgressRecord record) => Cmdlet.WriteProgress(record);
public abstract void ProcessRecord(PSObject inputObject);
public abstract void EndProcessing();
public abstract void WriteProgress(Collection<ProgressRecord> progress);
protected ScriptBlock ScriptBlock => Cmdlet.ScriptBlock;
protected WorkerBase(InvokeParallelCommand cmdlet)
{
Cmdlet = cmdlet;
Pool = cmdlet.PowershellPool;
}
}
class NoProgressWorker : WorkerBase
{
public NoProgressWorker(InvokeParallelCommand cmdlet) : base(cmdlet)
{
}
public override void ProcessRecord(PSObject inputObject)
{
while (!Pool.TryAddInput(Cmdlet.ScriptBlock, Cmdlet.InputObject))
{
Cmdlet.WriteOutputs();
}
}
public override void EndProcessing()
{
while (!Pool.WaitForAllPowershellCompleted(100))
{
if (Stopping)
{
return;
}
WriteOutputs();
}
WriteOutputs();
}
public override void WriteProgress(Collection<ProgressRecord> progress)
{
foreach (var p in progress)
{
base.WriteProgress(p);
}
}
}
class ProgressWorker : WorkerBase
{
readonly ProgressManager _progressManager;
private readonly List<PSObject> _input;
private int _lastEstimate = -1;
public ProgressWorker(InvokeParallelCommand cmdlet) : base(cmdlet)
{
_progressManager = new ProgressManager(cmdlet.ProgressId, cmdlet.ProgressActivity, $"Processing with {cmdlet.ThrottleLimit} workers", cmdlet.ParentProgressId);
_input = new List<PSObject>(500);
}
public override void ProcessRecord(PSObject inputObject)
{
_input.Add(inputObject);
}
public override void EndProcessing()
{
try
{
_progressManager.TotalCount = _input.Count;
var lastPercentComplete = -1;
foreach (var i in _input)
{
var processed = Pool.GetEstimatedProgressCount();
_lastEstimate = processed;
_progressManager.SetCurrentOperation($"Starting processing of {i}");
_progressManager.UpdateCurrentProgressRecord(processed);
var pr = _progressManager.ProgressRecord;
if (lastPercentComplete != pr.PercentComplete)
{
WriteProgress(pr);
lastPercentComplete = pr.PercentComplete;
}
while (!Pool.TryAddInput(ScriptBlock, i))
{
WriteOutputs();
}
}
_progressManager.SetCurrentOperation("All work queued. Waiting for remaining work to complete.");
while (!Pool.WaitForAllPowershellCompleted(100))
{
WriteProgressIfUpdated();
if (Stopping)
{
return;
}
WriteOutputs();
}
WriteOutputs();
}
finally
{
_progressManager.UpdateCurrentProgressRecord(Pool.GetEstimatedProgressCount());
WriteProgress(_progressManager.Completed());
}
}
public override void WriteProgress(Collection<ProgressRecord> progress)
{
foreach (var p in progress)
{
if (p.ActivityId != _progressManager.ActivityId)
{
p.ParentActivityId = _progressManager.ActivityId;
}
WriteProgress(p);
}
if (progress.Count > 0)
{
WriteProgressIfUpdated();
}
}
private void WriteProgressIfUpdated()
{
var estimatedCompletedCount = Pool.GetEstimatedProgressCount();
if (_lastEstimate != estimatedCompletedCount)
{
_lastEstimate = estimatedCompletedCount;
_progressManager.UpdateCurrentProgressRecord(estimatedCompletedCount);
WriteProgress(_progressManager.ProgressRecord);
}
}
}
}
}