-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
pipeline.cs
1597 lines (1389 loc) · 63.3 KB
/
pipeline.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
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Tracing;
using System.Reflection;
using System.Runtime.ExceptionServices;
using Microsoft.PowerShell.Telemetry;
using Dbg = System.Management.Automation.Diagnostics;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
namespace System.Management.Automation.Internal
{
/// <summary>
/// Loads InternalCommand objects and executes them.
/// </summary>
/// <remarks>
/// The PipelineProcessor class is not thread-safe, so methods such as
/// AddCommand and SynchronousExecute should not be called
/// simultaneously. While SynchronousExecute is running, it may access
/// ExternalInput, ExternalSuccessOutput and ExternalErrorOutput, and
/// those objects are thread-safe.
/// </remarks>
internal class PipelineProcessor : IDisposable
{
#region private_members
private List<CommandProcessorBase> _commands = new List<CommandProcessorBase>();
private List<PipelineProcessor> _redirectionPipes;
private PipelineReader<object> _externalInputPipe;
private PipelineWriter _externalSuccessOutput;
private PipelineWriter _externalErrorOutput;
private bool _executionStarted = false;
private bool _stopping = false;
private SessionStateScope _executionScope;
private ExceptionDispatchInfo _firstTerminatingError = null;
private bool _linkedSuccessOutput = false;
private bool _linkedErrorOutput = false;
#if !CORECLR // Impersonation Not Supported On CSS
// This is the security context when the pipeline was allocated
internal System.Security.SecurityContext SecurityContext =
System.Security.SecurityContext.Capture();
#endif
#endregion private_members
#region IDispose
private bool _disposed = false;
/// <summary>
/// When the command is complete, PipelineProcessor will be
/// disposed.
/// </summary>
/// <remarks>
/// This is only public because it implements an interface method.
/// The class itself is internal.
/// We use the standard IDispose pattern.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
DisposeCommands();
_localPipeline = null;
_externalSuccessOutput = null;
_externalErrorOutput = null;
_executionScope = null;
_eventLogBuffer = null;
#if !CORECLR // Impersonation Not Supported On CSS
SecurityContext.Dispose();
SecurityContext = null;
#endif
}
_disposed = true;
}
#endregion IDispose
#region Execution Logging
private bool _executionFailed = false;
internal List<CommandProcessorBase> Commands
{
get { return _commands; }
}
internal bool ExecutionFailed
{
get
{
return _executionFailed;
}
set
{
_executionFailed = value;
}
}
internal void LogExecutionInfo(InvocationInfo invocationInfo, string text)
{
string message = StringUtil.Format(PipelineStrings.PipelineExecutionInformation, GetCommand(invocationInfo), text);
Log(message, invocationInfo, PipelineExecutionStatus.Started);
}
internal void LogExecutionComplete(InvocationInfo invocationInfo, string text)
{
string message = StringUtil.Format(PipelineStrings.PipelineExecutionInformation, GetCommand(invocationInfo), text);
Log(message, invocationInfo, PipelineExecutionStatus.Complete);
}
internal void LogPipelineComplete()
{
Log(null, null, PipelineExecutionStatus.PipelineComplete);
}
internal void LogExecutionParameterBinding(InvocationInfo invocationInfo, string parameterName, string parameterValue)
{
string message = StringUtil.Format(PipelineStrings.PipelineExecutionParameterBinding, GetCommand(invocationInfo), parameterName, parameterValue);
Log(message, invocationInfo, PipelineExecutionStatus.ParameterBinding);
}
internal void LogExecutionError(InvocationInfo invocationInfo, ErrorRecord errorRecord)
{
if (errorRecord == null)
return;
string message = StringUtil.Format(PipelineStrings.PipelineExecutionNonTerminatingError, GetCommand(invocationInfo), errorRecord.ToString());
Log(message, invocationInfo, PipelineExecutionStatus.Error);
}
private bool _terminatingErrorLogged = false;
internal void LogExecutionException(Exception exception)
{
_executionFailed = true;
// Only log one terminating error for pipeline execution.
if (_terminatingErrorLogged)
return;
_terminatingErrorLogged = true;
if (exception == null)
return;
string message = StringUtil.Format(PipelineStrings.PipelineExecutionTerminatingError, GetCommand(exception), exception.Message);
Log(message, null, PipelineExecutionStatus.Error);
}
private static string GetCommand(InvocationInfo invocationInfo)
{
if (invocationInfo == null)
return string.Empty;
if (invocationInfo.MyCommand != null)
{
return invocationInfo.MyCommand.Name;
}
return string.Empty;
}
private static string GetCommand(Exception exception)
{
IContainsErrorRecord icer = exception as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
return GetCommand(icer.ErrorRecord.InvocationInfo);
return string.Empty;
}
private void Log(string logElement, InvocationInfo invocation, PipelineExecutionStatus pipelineExecutionStatus)
{
System.Management.Automation.Host.PSHostUserInterface hostInterface = null;
if (this.LocalPipeline != null)
{
hostInterface = this.LocalPipeline.Runspace.GetExecutionContext.EngineHostInterface.UI;
}
// Acknowledge command completion
if (hostInterface != null)
{
if (pipelineExecutionStatus == PipelineExecutionStatus.Complete)
{
hostInterface.TranscribeCommandComplete(invocation);
return;
}
else if (pipelineExecutionStatus == PipelineExecutionStatus.PipelineComplete)
{
hostInterface.TranscribePipelineComplete();
return;
}
}
// Log the cmdlet invocation execution details if we didn't have an associated script line with it.
if ((invocation == null) || string.IsNullOrEmpty(invocation.Line))
{
if (hostInterface != null)
{
hostInterface.TranscribeCommand(logElement, invocation);
}
}
if (!string.IsNullOrEmpty(logElement))
{
_eventLogBuffer.Add(logElement);
}
}
internal void LogToEventLog()
{
if (NeedToLog())
{
// We check to see if the command is needs writing (or if there is anything in the buffer)
// before we flush it. Flushing the empty buffer causes a measurable performance degradation.
if (_commands == null || _commands.Count == 0 || _eventLogBuffer.Count == 0)
return;
MshLog.LogPipelineExecutionDetailEvent(_commands[0].Command.Context,
_eventLogBuffer,
_commands[0].Command.MyInvocation);
}
}
private bool NeedToLog()
{
if (_commands == null)
return false;
foreach (CommandProcessorBase commandProcessor in _commands)
{
MshCommandRuntime cmdRuntime = commandProcessor.Command.commandRuntime as MshCommandRuntime;
if (cmdRuntime != null && cmdRuntime.LogPipelineExecutionDetail)
return true;
}
return false;
}
private List<string> _eventLogBuffer = new List<string>();
#endregion
#region public_methods
/// <summary>
/// Add a single InternalCommand to the end of the pipeline.
/// </summary>
/// <returns>Results from last pipeline stage.</returns>
/// <exception cref="InvalidOperationException">
/// see AddCommand
/// </exception>
/// <exception cref="ObjectDisposedException"></exception>
internal int Add(CommandProcessorBase commandProcessor)
{
commandProcessor.CommandRuntime.PipelineProcessor = this;
return AddCommand(commandProcessor, _commands.Count, false);
}
internal void AddRedirectionPipe(PipelineProcessor pipelineProcessor)
{
if (pipelineProcessor is null)
{
throw PSTraceSource.NewArgumentNullException(nameof(pipelineProcessor));
}
_redirectionPipes ??= new List<PipelineProcessor>();
_redirectionPipes.Add(pipelineProcessor);
}
// 2004/02/28-JSnover (from spec review) ReadFromErrorQueue
// should be an int or enum to allow for more queues
// 2005/03/08-JonN: This is an internal API
/// <summary>
/// Add a command to the pipeline.
/// </summary>
/// <param name="commandProcessor"></param>
/// <param name="readFromCommand">Reference number of command from which to read, 0 for none.</param>
/// <param name="readErrorQueue">Read from error queue of command readFromCommand.</param>
/// <returns>Reference number of this command for use in readFromCommand.</returns>
/// <exception cref="ObjectDisposedException"></exception>
/// <exception cref="ArgumentException">
/// FirstCommandCannotHaveInput: <paramref name="readFromCommand"/> must be zero
/// for the first command in the pipe
/// InvalidCommandNumber: there is no command numbered <paramref name="readFromCommand"/>
/// A command can only read from earlier commands; this prevents circular queues
/// </exception>
/// <exception cref="InvalidOperationException">
/// ExecutionAlreadyStarted: pipeline has already started or completed
/// PipeAlreadyTaken: the downstream pipe of command <paramref name="readFromCommand"/>
/// is already taken
/// </exception>
internal int AddCommand(CommandProcessorBase commandProcessor, int readFromCommand, bool readErrorQueue)
{
if (commandProcessor == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(commandProcessor));
}
if (_commands == null)
{
// "_commands == null"
throw PSTraceSource.NewInvalidOperationException();
}
if (_disposed)
{
throw PSTraceSource.NewObjectDisposedException("PipelineProcessor");
}
if (_executionStarted)
{
throw PSTraceSource.NewInvalidOperationException(
PipelineStrings.ExecutionAlreadyStarted);
}
if (commandProcessor.AddedToPipelineAlready)
{
throw PSTraceSource.NewInvalidOperationException(
PipelineStrings.CommandProcessorAlreadyUsed);
}
if (_commands.Count == 0)
{
if (readFromCommand != 0)
{
// "First command cannot have input"
throw PSTraceSource.NewArgumentException(
nameof(readFromCommand),
PipelineStrings.FirstCommandCannotHaveInput);
}
commandProcessor.AddedToPipelineAlready = true;
}
// 2003/08/11-JonN Subsequent commands must have predecessor
else if (readFromCommand > _commands.Count || readFromCommand <= 0)
{
// "invalid command number"
throw PSTraceSource.NewArgumentException(
nameof(readFromCommand),
PipelineStrings.InvalidCommandNumber);
}
else
{
var prevcommandProcessor = _commands[readFromCommand - 1] as CommandProcessorBase;
ValidateCommandProcessorNotNull(prevcommandProcessor, errorMessage: null);
Pipe UpstreamPipe = (readErrorQueue)
? prevcommandProcessor.CommandRuntime.ErrorOutputPipe
: prevcommandProcessor.CommandRuntime.OutputPipe;
if (UpstreamPipe == null)
{
throw PSTraceSource.NewInvalidOperationException();
}
if (UpstreamPipe.DownstreamCmdlet != null)
{
throw PSTraceSource.NewInvalidOperationException(
PipelineStrings.PipeAlreadyTaken);
}
commandProcessor.AddedToPipelineAlready = true;
commandProcessor.CommandRuntime.InputPipe = UpstreamPipe;
UpstreamPipe.DownstreamCmdlet = commandProcessor;
// 2004/09/14-JonN This code could be moved to SynchronousExecute
// if this setting needed to bind at a later time
// than AddCommand.
if (commandProcessor.CommandRuntime.MergeUnclaimedPreviousErrorResults)
{
for (int i = 0; i < _commands.Count; i++)
{
prevcommandProcessor = _commands[i];
ValidateCommandProcessorNotNull(prevcommandProcessor, errorMessage: null);
// check whether the error output is already claimed
if (prevcommandProcessor.CommandRuntime.ErrorOutputPipe.DownstreamCmdlet != null)
continue;
if (prevcommandProcessor.CommandRuntime.ErrorOutputPipe.ExternalWriter != null)
continue;
// Set the upstream cmdlet's error output to go down
// the same pipe as the downstream cmdlet's input
prevcommandProcessor.CommandRuntime.ErrorOutputPipe = UpstreamPipe;
}
}
}
_commands.Add(commandProcessor);
// We give the Command a pointer back to the
// PipelineProcessor so that it can check whether the
// command has been stopped.
commandProcessor.CommandRuntime.PipelineProcessor = this;
return _commands.Count;
}
// 2005/03/08-JonN: This is an internal API
/// <summary>
/// Execute the accumulated commands and clear the pipeline.
/// SynchronousExecute does not return until all commands have
/// completed. There is no asynchronous variant; instead, once the
/// pipeline is set up, the caller can spawn a thread and call
/// SynchronousExecute from that thread. This does not mean that
/// PipelineProcessor is thread-safe; once SynchronousExecute is
/// running, PipelineProcessor should not be accessed through any
/// other means. This variant of the routine looks at it's input
/// object to see if it's enumerable or not.
/// </summary>
/// <param name="input">
/// Input objects for first stage. If this is AutomationNull.Value, the
/// first cmdlet is the beginning of the pipeline.
/// </param>
/// <returns>
/// Results from last pipeline stage. This will be empty if
/// ExternalSuccessOutput is set.
/// </returns>
/// <exception cref="InvalidOperationException">
/// ExecutionAlreadyStarted: pipeline has already started or completed
/// </exception>
/// <exception cref="InvalidOperationException">
/// PipelineExecuteRequiresAtLeastOneCommand
/// </exception>
/// <exception cref="CmdletInvocationException">
/// A cmdlet encountered a terminating error
/// </exception>
/// <exception cref="PipelineStoppedException">
/// The pipeline was stopped asynchronously
/// </exception>
/// <exception cref="ActionPreferenceStopException">
/// The ActionPreference.Stop or ActionPreference.Inquire policy
/// triggered a terminating error.
/// </exception>
/// <exception cref="ParameterBindingException">
/// If any parameters fail to bind,
/// or
/// If any mandatory parameters are missing.
/// </exception>
/// <exception cref="MetadataException">
/// If there is an error generating the metadata for dynamic parameters.
/// </exception>
/// <exception cref="ExtendedTypeSystemException">
/// An error occurred clearing the error variable.
/// </exception>
/// <exception cref="HaltCommandException">
/// HaltCommandException will cause the command
/// to stop, but should not be reported as an error.
/// </exception>
internal Array SynchronousExecuteEnumerate(object input)
{
if (Stopping)
{
throw new PipelineStoppedException();
}
bool pipelineSucceeded = false;
ExceptionDispatchInfo toRethrowInfo = null;
CommandProcessorBase commandRequestingUpstreamCommandsToStop = null;
try
{
try
{
try
{
// If the caller specified an input object array, we run assuming there is an incoming "stream"
// of objects. This will prevent the one default call to ProcessRecord on the first command.
Start(input != AutomationNull.Value);
// Start has already validated firstcommandProcessor
CommandProcessorBase firstCommandProcessor = _commands[0];
// Add any input to the first command.
if (ExternalInput != null)
{
firstCommandProcessor.CommandRuntime.InputPipe.ExternalReader = ExternalInput;
}
Inject(input, enumerate: true);
}
catch (PipelineStoppedException)
{
if (_firstTerminatingError?.SourceException is StopUpstreamCommandsException exception)
{
_firstTerminatingError = null;
commandRequestingUpstreamCommandsToStop = exception.RequestingCommandProcessor;
}
else
{
throw;
}
}
DoCompleteCore(commandRequestingUpstreamCommandsToStop);
pipelineSucceeded = true;
}
finally
{
// Clean up resources for script commands, no matter the pipeline succeeded or not.
// This method catches and handles all exceptions inside, so it will never throw.
Clean();
}
if (pipelineSucceeded)
{
// Now, we are sure all 'commandProcessors' hosted by the current 'pipelineProcessor' are done execution,
// so if there are any redirection 'pipelineProcessors' associated with any of those 'commandProcessors',
// they must have successfully executed 'StartStepping' and 'Step', and thus we should call 'DoComplete'
// on them for completeness.
if (_redirectionPipes is not null)
{
foreach (PipelineProcessor redirectPipelineProcessor in _redirectionPipes)
{
// The 'Clean' block for each 'commandProcessor' might still write to a pipe that is associated
// with the redirection 'pipelineProcessor' (e.g. a redirected error pipe), which would trigger
// the call to 'pipelineProcessor.Step'.
// It's possible (though very unlikely) that the call to 'pipelineProcessor.Step' failed with an
// exception, and in such case, the 'pipelineProcessor' would have been disposed, and therefore
// the call to 'DoComplete' will simply return, because '_commands' was already set to null.
redirectPipelineProcessor.DoCompleteCore(null);
}
}
// The 'Clean' blocks write nothing to the output pipe, so the results won't be affected by them.
return RetrieveResults();
}
}
catch (RuntimeException e)
{
toRethrowInfo = GetFirstError(e);
}
finally
{
DisposeCommands();
}
// By rethrowing the exception outside of the handler, we allow the CLR on X64/IA64 to free from
// the stack the exception records related to this exception.
// The only reason we should get here is if an exception should be rethrown.
Diagnostics.Assert(toRethrowInfo != null, "Alternate protocol path failure");
toRethrowInfo.Throw();
// UNREACHABLE
return null;
}
private ExceptionDispatchInfo GetFirstError(RuntimeException e)
{
// The error we want to report is the first terminating error which occurred during pipeline execution,
// regardless of whether other errors occurred afterward.
var firstError = _firstTerminatingError ?? ExceptionDispatchInfo.Capture(e);
LogExecutionException(firstError.SourceException);
return firstError;
}
private void ThrowFirstErrorIfExisting(bool logException)
{
// The main purpose of this method is to check if the pipeline is being stopped asynchronously,
// by 'Ctrl+c' manually or 'PowerShell.Stop' programatically.
// When the pipeline is being stopped, a 'PipelineStoppedException' object will be assigned to
// '_firstTerminatingError' (see 'PipelineProcessor.Stop' for details), and thus the pipeline
// execution needs to check if '_firstTerminatingError' has been set in various places, so as
// to throw out this 'PipelineStoppedException' to terminate the pipeline execution.
if (_firstTerminatingError != null)
{
if (logException)
{
LogExecutionException(_firstTerminatingError.SourceException);
}
_firstTerminatingError.Throw();
}
}
private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamCommandsToStop)
{
if (_commands is null)
{
// This could happen to a redirection pipeline, either for an expression (e.g. 1 > a.txt)
// or for a command (e.g. command > a.txt).
// An exception may be thrown from the call to 'StartStepping' or 'Step' on the pipeline,
// which causes the pipeline commands to be disposed.
return;
}
// Call DoComplete() for all the commands, which will internally call Complete()
MshCommandRuntime lastCommandRuntime = null;
for (int i = 0; i < _commands.Count; i++)
{
CommandProcessorBase commandProcessor = _commands[i];
if (commandProcessor == null)
{
// An internal error that should not happen.
throw PSTraceSource.NewInvalidOperationException();
}
if (object.ReferenceEquals(commandRequestingUpstreamCommandsToStop, commandProcessor))
{
// Do not call DoComplete/EndProcessing on the command that initiated stopping.
commandRequestingUpstreamCommandsToStop = null;
continue;
}
if (commandRequestingUpstreamCommandsToStop != null)
{
// Do not call DoComplete/EndProcessing on commands that were stopped upstream.
continue;
}
try
{
commandProcessor.DoComplete();
}
catch (PipelineStoppedException)
{
if (_firstTerminatingError?.SourceException is StopUpstreamCommandsException exception)
{
_firstTerminatingError = null;
commandRequestingUpstreamCommandsToStop = exception.RequestingCommandProcessor;
}
else
{
throw;
}
}
EtwActivity.SetActivityId(commandProcessor.PipelineActivityId);
// Log a command stopped event
MshLog.LogCommandLifecycleEvent(
commandProcessor.Command.Context,
CommandState.Stopped,
commandProcessor.Command.MyInvocation);
// Log the execution of a command (not script chunks, as they are not commands in and of themselves).
if (commandProcessor.CommandInfo.CommandType != CommandTypes.Script)
{
LogExecutionComplete(commandProcessor.Command.MyInvocation, commandProcessor.CommandInfo.Name);
}
lastCommandRuntime = commandProcessor.CommandRuntime;
}
// Log the pipeline completion.
if (lastCommandRuntime != null)
{
// Only log the pipeline completion if this wasn't a nested pipeline, as
// pipeline state in transcription is associated with the toplevel pipeline
if (LocalPipeline == null || !LocalPipeline.IsNested)
{
lastCommandRuntime.PipelineProcessor.LogPipelineComplete();
}
}
// If a terminating error occurred, report it now.
// This pipeline could have been stopped asynchronously and we need to check and
// see if that's the case.
// An example:
// - 'Start-Sleep' is running in this pipeline, and 'pipelineProcessor.Stop' gets
// called on a different thread, which sets a 'PipelineStoppedException' object
// to '_firstTerminatingError' and runs 'StopProcessing' on 'Start-Sleep'.
// The 'StopProcessing' will cause 'Start-Sleep' to return from 'ProcessRecord'
// call, and thus the pipeline execution will move forward to run 'DoComplete'
// for the 'Start-Sleep' command and thus the code flow will reach here.
// For this given example, we need to check '_firstTerminatingError' and throw out
// the 'PipelineStoppedException' if the pipeline was indeed being stopped.
ThrowFirstErrorIfExisting(logException: true);
}
/// <summary>
/// Clean up resources for script commands in this pipeline processor.
/// </summary>
private void Clean()
{
if (_commands is null)
{
return;
}
// So far, if '_firstTerminatingError' is not null, then it must be a terminating error
// thrown from one of 'Begin/Process/End' blocks. There can be terminating error thrown
// from 'Clean' block as well, which needs to be handled in this method.
// In order to capture the subsequent first terminating error thrown from 'Clean', we
// need to forget the previous '_firstTerminatingError' value before calling 'DoClean'
// on each command processor, so we have to save the old value here and restore later.
ExceptionDispatchInfo oldFirstTerminatingError = _firstTerminatingError;
try
{
foreach (CommandProcessorBase commandProcessor in _commands)
{
if (commandProcessor is null || !commandProcessor.HasCleanBlock)
{
continue;
}
try
{
// Forget the terminating error we saw before, so a terminating error thrown
// from the subsequent 'Clean' block can be recorded and handled properly.
_firstTerminatingError = null;
commandProcessor.DoCleanup();
}
catch (RuntimeException e)
{
// Exception from a 'Clean' block is not allowed to terminate the pipeline
// so that other 'Clean' blocks can run without being affected.
ExceptionDispatchInfo firstError = GetFirstError(e);
commandProcessor.ReportCleanupError(firstError.SourceException);
}
catch (Exception ex)
{
// Theoretically, only RuntimeException could be thrown out, but we catch
// all and log them here just to be safe.
// Skip special flow control exceptions and log others.
if (ex is not FlowControlException && ex is not HaltCommandException)
{
MshLog.LogCommandHealthEvent(commandProcessor.Context, ex, Severity.Warning);
}
}
}
}
finally
{
_firstTerminatingError = oldFirstTerminatingError;
}
}
/// <summary>
/// Implements DoComplete as a stand-alone function for completing
/// the execution of a steppable pipeline.
/// </summary>
/// <returns>The results of the execution.</returns>
internal Array DoComplete()
{
try
{
if (Stopping)
{
throw new PipelineStoppedException();
}
if (!_executionStarted)
{
throw PSTraceSource.NewInvalidOperationException(
PipelineStrings.PipelineNotStarted);
}
ExceptionDispatchInfo toRethrowInfo;
try
{
DoCompleteCore(null);
return RetrieveResults();
}
catch (RuntimeException e)
{
toRethrowInfo = GetFirstError(e);
}
// By rethrowing the exception outside of the handler, we allow the CLR on X64/IA64 to free from the stack
// the exception records related to this exception.
// The only reason we should get here is if an exception should be rethrown.
Diagnostics.Assert(toRethrowInfo != null, "Alternate protocol path failure");
toRethrowInfo.Throw();
// UNREACHABLE
return null;
}
finally
{
DisposeCommands();
}
}
/// <summary>
/// This routine starts the stepping process. It is optional to
/// call this but can be useful if you want the begin clauses
/// of the pipeline to be run even when there may not be any input
/// to process as is the case for I/O redirection into a file. We
/// still want the file opened, even if there was nothing to write to it.
/// </summary>
/// <param name="expectInput">True if you want to write to this pipeline.</param>
internal void StartStepping(bool expectInput)
{
try
{
Start(expectInput);
// If a terminating error occurred, report it now.
ThrowFirstErrorIfExisting(logException: false);
}
catch (PipelineStoppedException)
{
DisposeCommands();
// The error we want to report is the first terminating error
// which occurred during pipeline execution, regardless
// of whether other errors occurred afterward.
ThrowFirstErrorIfExisting(logException: false);
throw;
}
}
/// <summary>
/// Request that the pipeline execution should stop. Unlike other
/// methods of PipelineProcessor, this method can be called
/// asynchronously.
/// </summary>
internal void Stop()
{
// Only call StopProcessing if the pipeline is being stopped
// for the first time
if (!RecordFailure(new PipelineStoppedException(), null))
return;
// Retain copy of _commands in case Dispose() is called
List<CommandProcessorBase> commands = _commands;
if (commands == null)
return;
// Call StopProcessing() for all the commands.
for (int i = 0; i < commands.Count; i++)
{
CommandProcessorBase commandProcessor = commands[i];
if (commandProcessor == null)
{
throw PSTraceSource.NewInvalidOperationException();
}
try
{
commandProcessor.Command.DoStopProcessing();
}
catch (Exception)
{
// We swallow exceptions which occur during StopProcessing.
continue;
}
}
}
#endregion public_methods
#region private_methods
/// <summary>
/// Partially execute the pipeline, and retrieve the output
/// after the input objects have been entered into the pipe.
/// </summary>
/// <param name="input">
/// Array of input objects for first stage
/// </param>
/// <returns>
/// Results from last pipeline stage. This will be empty if
/// ExternalSuccessOutput is set.
/// </returns>
/// <exception cref="InvalidOperationException">
/// PipelineExecuteRequiresAtLeastOneCommand
/// </exception>
/// <exception cref="PipelineStoppedException">
/// The pipeline has already been stopped, or a cmdlet encountered
/// a terminating error
/// </exception>
/// <exception cref="ParameterBindingException">
/// If any parameters fail to bind,
/// or
/// If any mandatory parameters are missing.
/// </exception>
/// <exception cref="MetadataException">
/// If there is an error generating the metadata for dynamic parameters.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// The pipeline has already been stopped,
/// or a terminating error occurred.
/// </exception>
/// <exception cref="ExtendedTypeSystemException">
/// An error occurred clearing the error variable.
/// </exception>
internal Array Step(object input)
{
if (Stopping)
{
DisposeCommands();
throw new PipelineStoppedException();
}
try
{
Start(true);
Inject(input, enumerate: false);
// If a terminating error occurred, report it now.
ThrowFirstErrorIfExisting(logException: false);
return RetrieveResults();
}
catch (PipelineStoppedException)
{
DisposeCommands();
// The error we want to report is the first terminating error
// which occurred during pipeline execution, regardless
// of whether other errors occurred afterward.
ThrowFirstErrorIfExisting(logException: false);
throw;
}
catch (Exception)
{
DisposeCommands();
throw;
}
}
/// <summary>
/// Prepares the pipeline for execution.
/// </summary>
/// <param name="incomingStream">
/// Input objects are expected, so do not close the first command.
/// This will prevent the one default call to ProcessRecord
/// on the first command.
/// </param>
/// <remarks>
/// Start must always be called in a context where terminating errors will
/// be caught and result in DisposeCommands.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// PipelineExecuteRequiresAtLeastOneCommand
/// </exception>
/// <exception cref="ParameterBindingException">
/// If any parameters fail to bind,
/// or
/// If any mandatory parameters are missing.
/// </exception>
/// <exception cref="MetadataException">
/// If there is an error generating the metadata for dynamic parameters.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// The pipeline has already been stopped,
/// or a terminating error occurred in a downstream cmdlet.
/// </exception>
/// <exception cref="ExtendedTypeSystemException">
/// An error occurred clearing the error variable.
/// </exception>
private void Start(bool incomingStream)
{
// Every call to Step or SynchronousExecute will call Start.
if (_disposed)
{
throw PSTraceSource.NewObjectDisposedException("PipelineProcessor");
}
if (Stopping)
{
throw new PipelineStoppedException();
}
if (_executionStarted)
return;
if (_commands == null || _commands.Count == 0)
{
throw PSTraceSource.NewInvalidOperationException(
PipelineStrings.PipelineExecuteRequiresAtLeastOneCommand);
}
CommandProcessorBase firstcommandProcessor = _commands[0];
ValidateCommandProcessorNotNull(firstcommandProcessor, PipelineStrings.PipelineExecuteRequiresAtLeastOneCommand);
// Set the execution scope using the current scope
if (_executionScope == null)
{