| |
| |
|
|
| using System.Collections.Generic; |
| using System.Collections.ObjectModel; |
| using System.Diagnostics.CodeAnalysis; |
| using System.Management.Automation.Host; |
| using System.Management.Automation.Internal; |
| using System.Management.Automation.Language; |
| using System.Management.Automation.Remoting; |
| using System.Management.Automation.Remoting.Internal; |
| using System.Management.Automation.Runspaces; |
| using System.Management.Automation.Tracing; |
| using System.Runtime.Serialization; |
| using System.Text; |
| using System.Threading; |
|
|
| using Microsoft.PowerShell.Commands; |
|
|
| using Dbg = System.Management.Automation.Diagnostics; |
|
|
| |
| #pragma warning disable 1634, 1691 |
|
|
| namespace System.Management.Automation |
| { |
| |
| |
| |
| |
| public enum JobState |
| { |
| |
| |
| |
| NotStarted = 0, |
|
|
| |
| |
| |
| Running = 1, |
|
|
| |
| |
| |
| |
| Completed = 2, |
|
|
| |
| |
| |
| |
| Failed = 3, |
|
|
| |
| |
| |
| |
| Stopped = 4, |
|
|
| |
| |
| |
| Blocked = 5, |
|
|
| |
| |
| |
| Suspended = 6, |
|
|
| |
| |
| |
| Disconnected = 7, |
|
|
| |
| |
| |
| Suspending = 8, |
|
|
| |
| |
| |
| Stopping = 9, |
|
|
| |
| |
| |
| AtBreakpoint = 10 |
| } |
|
|
| |
| |
| |
| |
| public class InvalidJobStateException : SystemException |
| { |
| |
| |
| |
| public InvalidJobStateException() |
| : base |
| ( |
| PSRemotingErrorInvariants.FormatResourceString |
| ( |
| RemotingErrorIdStrings.InvalidJobStateGeneral |
| ) |
| ) |
| { |
| } |
|
|
| |
| |
| |
| |
| |
| |
| public InvalidJobStateException(string message) |
| : base(message) |
| { |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| public InvalidJobStateException(string message, Exception innerException) |
| : base(message, innerException) |
| { |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| public InvalidJobStateException(JobState currentState, string actionMessage) |
| : base |
| ( |
| PSRemotingErrorInvariants.FormatResourceString |
| ( |
| RemotingErrorIdStrings.InvalidJobStateSpecific, currentState, actionMessage |
| ) |
| ) |
| { |
| _currState = currentState; |
| } |
|
|
| |
| |
| |
| |
| |
| internal InvalidJobStateException(JobState currentState) |
| : base |
| ( |
| PSRemotingErrorInvariants.FormatResourceString |
| ( |
| RemotingErrorIdStrings.InvalidJobStateGeneral |
| ) |
| ) |
| { |
| _currState = currentState; |
| } |
|
|
| #region ISerializable Members |
|
|
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] |
| protected |
| InvalidJobStateException(SerializationInfo info, StreamingContext context) |
| { |
| throw new NotSupportedException(); |
| } |
|
|
| #endregion |
|
|
| |
| |
| |
| public JobState CurrentState |
| { |
| get |
| { |
| return _currState; |
| } |
| } |
|
|
| |
| |
| |
| [NonSerialized] |
| private readonly JobState _currState = 0; |
| } |
|
|
| |
| |
| |
| |
| public sealed class JobStateInfo |
| { |
| #region constructors |
|
|
| |
| |
| |
| |
| public JobStateInfo(JobState state) |
| : this(state, null) |
| { |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| public JobStateInfo(JobState state, Exception reason) |
| { |
| State = state; |
| Reason = reason; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| internal JobStateInfo(JobStateInfo jobStateInfo) |
| { |
| State = jobStateInfo.State; |
| Reason = jobStateInfo.Reason; |
| } |
|
|
| #endregion constructors |
|
|
| #region public_properties |
|
|
| |
| |
| |
| |
| |
| |
| public JobState State { get; } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| public Exception Reason { get; } |
|
|
| #endregion public_properties |
|
|
| |
| |
| |
| |
| public override string ToString() |
| { |
| return State.ToString(); |
| } |
|
|
| |
| |
| |
| |
| internal JobStateInfo Clone() |
| { |
| return new JobStateInfo(this); |
| } |
|
|
| #region private_fields |
|
|
| #endregion private_fields |
| } |
|
|
| |
| |
| |
| |
| public sealed class JobStateEventArgs : EventArgs |
| { |
| #region constructors |
|
|
| |
| |
| |
| |
| public JobStateEventArgs(JobStateInfo jobStateInfo) |
| : this(jobStateInfo, null) |
| { |
| } |
|
|
| |
| |
| |
| |
| |
| public JobStateEventArgs(JobStateInfo jobStateInfo, JobStateInfo previousJobStateInfo) |
| { |
| if (jobStateInfo == null) |
| { |
| throw PSTraceSource.NewArgumentNullException(nameof(jobStateInfo)); |
| } |
|
|
| JobStateInfo = jobStateInfo; |
| PreviousJobStateInfo = previousJobStateInfo; |
| } |
|
|
| #endregion constructors |
|
|
| #region public_properties |
|
|
| |
| |
| |
| public JobStateInfo JobStateInfo { get; } |
|
|
| |
| |
| |
| public JobStateInfo PreviousJobStateInfo { get; } |
|
|
| #endregion public_properties |
| } |
|
|
| |
| |
| |
| |
| public sealed class JobIdentifier |
| { |
| internal JobIdentifier(int id, Guid instanceId) |
| { |
| if (id <= 0) |
| PSTraceSource.NewArgumentException(nameof(id), RemotingErrorIdStrings.JobSessionIdLessThanOne, id); |
| Id = id; |
| InstanceId = instanceId; |
| } |
|
|
| internal int Id { get; } |
|
|
| internal Guid InstanceId { get; private set; } |
| } |
|
|
| |
| |
| |
| #nullable enable |
| public interface IJobDebugger |
| { |
| |
| |
| |
| Debugger? Debugger |
| { |
| get; |
| } |
|
|
| |
| |
| |
| bool IsAsync |
| { |
| get; |
| set; |
| } |
| } |
| #nullable restore |
|
|
| |
| |
| |
| |
| public abstract class Job : IDisposable |
| { |
| #region Constructor |
|
|
| |
| |
| |
| protected Job() |
| { |
| Id = System.Threading.Interlocked.Increment(ref s_jobIdSeed); |
| } |
|
|
| |
| |
| |
| |
| protected Job(string command) |
| : this() |
| { |
| Command = command; |
| _name = AutoGenerateJobName(); |
| } |
|
|
| |
| |
| |
| |
| |
| protected Job(string command, string name) |
| : this(command) |
| { |
| if (!string.IsNullOrEmpty(name)) |
| { |
| _name = name; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| protected Job(string command, string name, IList<Job> childJobs) |
| : this(command, name) |
| { |
| _childJobs = childJobs; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| protected Job(string command, string name, JobIdentifier token) |
| { |
| if (token == null) |
| throw PSTraceSource.NewArgumentNullException(nameof(token), RemotingErrorIdStrings.JobIdentifierNull); |
| if (token.Id > s_jobIdSeed) |
| { |
| throw PSTraceSource.NewArgumentException(nameof(token), RemotingErrorIdStrings.JobIdNotYetAssigned, token.Id); |
| } |
|
|
| Command = command; |
|
|
| Id = token.Id; |
| InstanceId = token.InstanceId; |
|
|
| if (!string.IsNullOrEmpty(name)) |
| { |
| _name = name; |
| } |
| else |
| { |
| _name = AutoGenerateJobName(); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| protected Job(string command, string name, Guid instanceId) |
| : this(command, name) |
| { |
| InstanceId = instanceId; |
| } |
|
|
| internal static string GetCommandTextFromInvocationInfo(InvocationInfo invocationInfo) |
| { |
| if (invocationInfo == null) |
| { |
| return null; |
| } |
|
|
| IScriptExtent scriptExtent = invocationInfo.ScriptPosition; |
| if ((scriptExtent != null) && (scriptExtent.StartScriptPosition != null) && !string.IsNullOrWhiteSpace(scriptExtent.StartScriptPosition.Line)) |
| { |
| Dbg.Assert(scriptExtent.StartScriptPosition.ColumnNumber > 0, "Column numbers start at 1"); |
| Dbg.Assert(scriptExtent.StartScriptPosition.ColumnNumber <= scriptExtent.StartScriptPosition.Line.Length, "Column numbers are not greater than the length of a line"); |
| return scriptExtent.StartScriptPosition.Line.AsSpan(scriptExtent.StartScriptPosition.ColumnNumber - 1).Trim().ToString(); |
| } |
|
|
| return invocationInfo.InvocationName; |
| } |
|
|
| #endregion Constructor |
|
|
| #region Private Members |
|
|
| private ManualResetEvent _finished = new ManualResetEvent(false); |
|
|
| private string _name; |
| private IList<Job> _childJobs; |
| internal readonly object syncObject = new object(); |
| |
| private PSDataCollection<PSStreamObject> _results = new PSDataCollection<PSStreamObject>(); |
| private bool _resultsOwner = true; |
| private PSDataCollection<ErrorRecord> _error = new PSDataCollection<ErrorRecord>(); |
| private bool _errorOwner = true; |
| private PSDataCollection<ProgressRecord> _progress = new PSDataCollection<ProgressRecord>(); |
| private bool _progressOwner = true; |
| private PSDataCollection<VerboseRecord> _verbose = new PSDataCollection<VerboseRecord>(); |
| private bool _verboseOwner = true; |
| private PSDataCollection<WarningRecord> _warning = new PSDataCollection<WarningRecord>(); |
| private bool _warningOwner = true; |
| private PSDataCollection<DebugRecord> _debug = new PSDataCollection<DebugRecord>(); |
| private bool _debugOwner = true; |
| private PSDataCollection<InformationRecord> _information = new PSDataCollection<InformationRecord>(); |
| private bool _informationOwner = true; |
| private PSDataCollection<PSObject> _output = new PSDataCollection<PSObject>(); |
| private bool _outputOwner = true; |
|
|
| |
| |
| |
| private static int s_jobIdSeed = 0; |
|
|
| private string _jobTypeName = string.Empty; |
|
|
| #endregion Private Members |
|
|
| #region Job Properties |
|
|
| |
| |
| |
| public string Command { get; } |
|
|
| |
| |
| |
| public JobStateInfo JobStateInfo { get; private set; } = new JobStateInfo(JobState.NotStarted); |
|
|
| |
| |
| |
| |
| |
| public WaitHandle Finished |
| { |
| get |
| { |
| lock (this.syncObject) |
| { |
| if (_finished != null) |
| { |
| return _finished; |
| } |
| else |
| { |
| |
| |
| |
| |
| |
| return new ManualResetEvent(true); |
| } |
| } |
| } |
| } |
|
|
| |
| |
| |
| public Guid InstanceId { get; } = Guid.NewGuid(); |
|
|
| |
| |
| |
| |
| public int Id { get; } |
|
|
| |
| |
| |
| public string Name |
| { |
| get |
| { |
| return _name; |
| } |
|
|
| set |
| { |
| AssertNotDisposed(); |
| _name = value; |
| } |
| } |
|
|
| |
| |
| |
| public IList<Job> ChildJobs |
| { |
| get |
| { |
| if (_childJobs == null) |
| { |
| lock (syncObject) |
| { |
| _childJobs ??= new List<Job>(); |
| } |
| } |
|
|
| return _childJobs; |
| } |
| } |
|
|
| |
| |
| |
| public abstract string StatusMessage { get; } |
|
|
| |
| |
| |
| |
| public abstract bool HasMoreData { get; } |
|
|
| |
| |
| |
| public DateTime? PSBeginTime { get; protected set; } = null; |
|
|
| |
| |
| |
| public DateTime? PSEndTime { get; protected set; } = null; |
|
|
| |
| |
| |
| public string PSJobTypeName |
| { |
| get |
| { |
| return _jobTypeName; |
| } |
|
|
| protected internal set |
| { |
| _jobTypeName = value ?? this.GetType().ToString(); |
| } |
| } |
|
|
| #region results |
|
|
| |
| |
| |
| |
| |
| internal PSDataCollection<PSStreamObject> Results |
| { |
| get |
| { |
| return _results; |
| } |
|
|
| set |
| { |
| if (value == null) |
| { |
| throw PSTraceSource.NewArgumentNullException("Results"); |
| } |
|
|
| lock (syncObject) |
| { |
| AssertChangesAreAccepted(); |
| _resultsOwner = false; |
| _results = value; |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| internal bool UsesResultsCollection { get; set; } |
|
|
| |
| |
| |
| |
| internal bool SuppressOutputForwarding { get; set; } |
|
|
| internal virtual void WriteObject(object outputObject) |
| { |
| PSObject pso = (outputObject == null) ? null : PSObject.AsPSObject(outputObject); |
| this.Output.Add(pso); |
|
|
| if (!SuppressOutputForwarding) |
| { |
| this.Results.Add(new PSStreamObject(PSStreamObjectType.Output, pso)); |
| } |
| } |
|
|
| |
| |
| |
| |
| internal bool PropagateThrows { get; set; } |
|
|
| private void WriteError(Cmdlet cmdlet, ErrorRecord errorRecord) |
| { |
| if (this.PropagateThrows) |
| { |
| Exception e = GetExceptionFromErrorRecord(errorRecord); |
| if (e != null) |
| throw e; |
| } |
|
|
| errorRecord.PreserveInvocationInfoOnce = true; |
| cmdlet.WriteError(errorRecord); |
| } |
|
|
| private static Exception GetExceptionFromErrorRecord(ErrorRecord errorRecord) |
| { |
| if (errorRecord.Exception is not RuntimeException runtimeException) |
| return null; |
|
|
| if (runtimeException is not RemoteException remoteException) |
| return null; |
|
|
| PSPropertyInfo wasThrownFromThrow = |
| remoteException.SerializedRemoteException.Properties["WasThrownFromThrowStatement"]; |
| if (wasThrownFromThrow == null || !((bool)wasThrownFromThrow.Value)) |
| return null; |
|
|
| runtimeException.WasThrownFromThrowStatement = true; |
| return runtimeException; |
| } |
|
|
| internal virtual void WriteError(ErrorRecord errorRecord) |
| { |
| Error.Add(errorRecord); |
| if (PropagateThrows) |
| { |
| Exception exception = GetExceptionFromErrorRecord(errorRecord); |
| if (exception != null) |
| { |
| Results.Add(new PSStreamObject(PSStreamObjectType.Exception, exception)); |
| return; |
| } |
| } |
|
|
| Results.Add(new PSStreamObject(PSStreamObjectType.Error, errorRecord)); |
| } |
|
|
| internal void WriteError(ErrorRecord errorRecord, out Exception exceptionThrownOnCmdletThread) |
| { |
| this.Error.Add(errorRecord); |
| this.InvokeCmdletMethodAndWaitForResults<object>( |
| (Cmdlet cmdlet) => |
| { |
| this.WriteError(cmdlet, errorRecord); |
| return null; |
| }, |
| out exceptionThrownOnCmdletThread); |
| } |
|
|
| internal virtual void WriteWarning(string message) |
| { |
| this.Warning.Add(new WarningRecord(message)); |
| this.Results.Add(new PSStreamObject(PSStreamObjectType.Warning, message)); |
| } |
|
|
| internal virtual void WriteVerbose(string message) |
| { |
| this.Verbose.Add(new VerboseRecord(message)); |
| this.Results.Add(new PSStreamObject(PSStreamObjectType.Verbose, message)); |
| } |
|
|
| internal virtual void WriteDebug(string message) |
| { |
| this.Debug.Add(new DebugRecord(message)); |
| this.Results.Add(new PSStreamObject(PSStreamObjectType.Debug, message)); |
| } |
|
|
| internal virtual void WriteProgress(ProgressRecord progressRecord) |
| { |
| if ((progressRecord.ParentActivityId == (-1)) && (_parentActivityId != null)) |
| { |
| progressRecord = new ProgressRecord(progressRecord) { ParentActivityId = _parentActivityId.Value }; |
| } |
|
|
| Progress.Add(progressRecord); |
| Results.Add(new PSStreamObject(PSStreamObjectType.Progress, progressRecord)); |
| } |
|
|
| internal virtual void WriteInformation(InformationRecord informationRecord) |
| { |
| Information.Add(informationRecord); |
| Results.Add(new PSStreamObject(PSStreamObjectType.Information, informationRecord)); |
| } |
|
|
| private Lazy<int> _parentActivityId; |
|
|
| internal void SetParentActivityIdGetter(Func<int> parentActivityIdGetter) |
| { |
| Dbg.Assert(parentActivityIdGetter != null, "Caller should verify parentActivityIdGetter != null"); |
| _parentActivityId = new Lazy<int>(parentActivityIdGetter); |
| } |
|
|
| internal bool ShouldContinue(string query, string caption) |
| { |
| Exception exceptionThrownOnCmdletThread; |
| return this.ShouldContinue(query, caption, out exceptionThrownOnCmdletThread); |
| } |
|
|
| internal bool ShouldContinue(string query, string caption, out Exception exceptionThrownOnCmdletThread) |
| { |
| bool methodResult = InvokeCmdletMethodAndWaitForResults( |
| cmdlet => cmdlet.ShouldContinue(query, caption), |
| out exceptionThrownOnCmdletThread); |
| return methodResult; |
| } |
|
|
| internal virtual void NonblockingShouldProcess( |
| string verboseDescription, |
| string verboseWarning, |
| string caption) |
| { |
| InvokeCmdletMethodAndIgnoreResults( |
| (Cmdlet cmdlet) => |
| { |
| ShouldProcessReason throwAwayProcessReason; |
| cmdlet.ShouldProcess( |
| verboseDescription, |
| verboseWarning, |
| caption, |
| out throwAwayProcessReason); |
| }); |
| } |
|
|
| internal virtual bool ShouldProcess( |
| string verboseDescription, |
| string verboseWarning, |
| string caption, |
| out ShouldProcessReason shouldProcessReason, |
| out Exception exceptionThrownOnCmdletThread) |
| { |
| ShouldProcessReason closureSafeShouldProcessReason = ShouldProcessReason.None; |
|
|
| bool methodResult = InvokeCmdletMethodAndWaitForResults( |
| cmdlet => cmdlet.ShouldProcess( |
| verboseDescription, |
| verboseWarning, |
| caption, |
| out closureSafeShouldProcessReason), |
| out exceptionThrownOnCmdletThread); |
|
|
| shouldProcessReason = closureSafeShouldProcessReason; |
| return methodResult; |
| } |
|
|
| private void InvokeCmdletMethodAndIgnoreResults(Action<Cmdlet> invokeCmdletMethod) |
| { |
| object resultsLock = new object(); |
| CmdletMethodInvoker<object> methodInvoker = new CmdletMethodInvoker<object> |
| { |
| Action = (Cmdlet cmdlet) => { invokeCmdletMethod(cmdlet); return null; }, |
| Finished = null, |
| SyncObject = resultsLock |
| }; |
| Results.Add(new PSStreamObject(PSStreamObjectType.BlockingError, methodInvoker)); |
| } |
|
|
| private T InvokeCmdletMethodAndWaitForResults<T>(Func<Cmdlet, T> invokeCmdletMethodAndReturnResult, out Exception exceptionThrownOnCmdletThread) |
| { |
| Dbg.Assert(invokeCmdletMethodAndReturnResult != null, "Caller should verify invokeCmdletMethodAndReturnResult != null"); |
|
|
| T methodResult = default(T); |
| Exception closureSafeExceptionThrownOnCmdletThread = null; |
| object resultsLock = new object(); |
| using (var gotResultEvent = new ManualResetEventSlim(false)) |
| { |
| EventHandler<JobStateEventArgs> stateChangedEventHandler = |
| (object sender, JobStateEventArgs eventArgs) => |
| { |
| if (IsFinishedState(eventArgs.JobStateInfo.State) || eventArgs.JobStateInfo.State == JobState.Stopping) |
| { |
| lock (resultsLock) |
| { |
| closureSafeExceptionThrownOnCmdletThread = new OperationCanceledException(); |
| } |
|
|
| gotResultEvent.Set(); |
| } |
| }; |
| this.StateChanged += stateChangedEventHandler; |
| Interlocked.MemoryBarrier(); |
| try |
| { |
| stateChangedEventHandler(null, new JobStateEventArgs(this.JobStateInfo)); |
|
|
| if (!gotResultEvent.IsSet) |
| { |
| this.SetJobState(JobState.Blocked); |
|
|
| |
| CmdletMethodInvoker<T> methodInvoker = new CmdletMethodInvoker<T> |
| { |
| Action = invokeCmdletMethodAndReturnResult, |
| Finished = gotResultEvent, |
| SyncObject = resultsLock |
| }; |
| PSStreamObjectType objectType = PSStreamObjectType.ShouldMethod; |
|
|
| if (typeof(T) == typeof(object)) |
| objectType = PSStreamObjectType.BlockingError; |
|
|
| Results.Add(new PSStreamObject(objectType, methodInvoker)); |
|
|
| gotResultEvent.Wait(); |
| this.SetJobState(JobState.Running); |
|
|
| lock (resultsLock) |
| { |
| if (closureSafeExceptionThrownOnCmdletThread == null) |
| { |
| closureSafeExceptionThrownOnCmdletThread = methodInvoker.ExceptionThrownOnCmdletThread; |
| methodResult = methodInvoker.MethodResult; |
| } |
| } |
| } |
| } |
| finally |
| { |
| this.StateChanged -= stateChangedEventHandler; |
| } |
| } |
|
|
| lock (resultsLock) |
| { |
| exceptionThrownOnCmdletThread = closureSafeExceptionThrownOnCmdletThread; |
| return methodResult; |
| } |
| } |
|
|
| internal virtual void ForwardAvailableResultsToCmdlet(Cmdlet cmdlet) |
| { |
| foreach (PSStreamObject obj in Results.ReadAll()) |
| { |
| obj.WriteStreamObject(cmdlet); |
| } |
| } |
|
|
| internal virtual void ForwardAllResultsToCmdlet(Cmdlet cmdlet) |
| { |
| foreach (PSStreamObject obj in this.Results) |
| { |
| obj.WriteStreamObject(cmdlet); |
| } |
| } |
|
|
| |
| |
| |
| |
| protected virtual void DoLoadJobStreams() |
| { |
| } |
|
|
| |
| |
| |
| |
| protected virtual void DoUnloadJobStreams() |
| { |
| } |
|
|
| |
| |
| |
| public void LoadJobStreams() |
| { |
| if (_jobStreamsLoaded) |
| { |
| return; |
| } |
|
|
| lock (syncObject) |
| { |
| if (_jobStreamsLoaded) |
| { |
| return; |
| } |
|
|
| _jobStreamsLoaded = true; |
| } |
|
|
| try |
| { |
| DoLoadJobStreams(); |
| } |
| catch (Exception e) |
| { |
| |
| |
| |
| using (PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource()) |
| { |
| tracer.TraceException(e); |
| } |
| } |
| } |
|
|
| private bool _jobStreamsLoaded; |
|
|
| |
| |
| |
| public void UnloadJobStreams() |
| { |
| if (!_jobStreamsLoaded) return; |
|
|
| lock (syncObject) |
| { |
| if (!_jobStreamsLoaded) return; |
| _jobStreamsLoaded = false; |
| } |
|
|
| try |
| { |
| DoUnloadJobStreams(); |
| } |
| catch (Exception e) |
| { |
| |
| |
| |
| using (PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource()) |
| { |
| tracer.TraceException(e); |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] |
| public PSDataCollection<PSObject> Output |
| { |
| get |
| { |
| LoadJobStreams(); |
| return _output; |
| } |
|
|
| set |
| { |
| if (value == null) |
| { |
| throw PSTraceSource.NewArgumentNullException("Output"); |
| } |
|
|
| lock (syncObject) |
| { |
| AssertChangesAreAccepted(); |
| _outputOwner = false; |
| _output = value; |
| _jobStreamsLoaded = true; |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] |
| public PSDataCollection<ErrorRecord> Error |
| { |
| get |
| { |
| LoadJobStreams(); |
| return _error; |
| } |
|
|
| set |
| { |
| if (value == null) |
| { |
| throw PSTraceSource.NewArgumentNullException("Error"); |
| } |
|
|
| lock (syncObject) |
| { |
| AssertChangesAreAccepted(); |
| _errorOwner = false; |
| _error = value; |
| _jobStreamsLoaded = true; |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] |
| public PSDataCollection<ProgressRecord> Progress |
| { |
| get |
| { |
| LoadJobStreams(); |
| return _progress; |
| } |
|
|
| set |
| { |
| if (value == null) |
| { |
| throw PSTraceSource.NewArgumentNullException("Progress"); |
| } |
|
|
| lock (syncObject) |
| { |
| AssertChangesAreAccepted(); |
| _progressOwner = false; |
| _progress = value; |
| _jobStreamsLoaded = true; |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] |
| public PSDataCollection<VerboseRecord> Verbose |
| { |
| get |
| { |
| LoadJobStreams(); |
| return _verbose; |
| } |
|
|
| set |
| { |
| if (value == null) |
| { |
| throw PSTraceSource.NewArgumentNullException("Verbose"); |
| } |
|
|
| lock (syncObject) |
| { |
| AssertChangesAreAccepted(); |
| _verboseOwner = false; |
| _verbose = value; |
| _jobStreamsLoaded = true; |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] |
| public PSDataCollection<DebugRecord> Debug |
| { |
| get |
| { |
| LoadJobStreams(); |
| return _debug; |
| } |
|
|
| set |
| { |
| if (value == null) |
| { |
| throw PSTraceSource.NewArgumentNullException("Debug"); |
| } |
|
|
| lock (syncObject) |
| { |
| AssertChangesAreAccepted(); |
| _debugOwner = false; |
| _debug = value; |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] |
| public PSDataCollection<WarningRecord> Warning |
| { |
| get |
| { |
| LoadJobStreams(); |
| return _warning; |
| } |
|
|
| set |
| { |
| if (value == null) |
| { |
| throw PSTraceSource.NewArgumentNullException("Warning"); |
| } |
|
|
| lock (syncObject) |
| { |
| AssertChangesAreAccepted(); |
| _warningOwner = false; |
| _warning = value; |
| _jobStreamsLoaded = true; |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] |
| public PSDataCollection<InformationRecord> Information |
| { |
| get |
| { |
| LoadJobStreams(); |
| return _information; |
| } |
|
|
| set |
| { |
| if (value == null) |
| { |
| throw PSTraceSource.NewArgumentNullException("Information"); |
| } |
|
|
| lock (syncObject) |
| { |
| AssertChangesAreAccepted(); |
| _informationOwner = false; |
| _information = value; |
| _jobStreamsLoaded = true; |
| } |
| } |
| } |
|
|
| |
| |
| |
| public abstract string Location { get; } |
|
|
| #endregion results |
|
|
| #region Connect/Disconnect |
|
|
| |
| |
| |
| |
| |
| internal virtual bool CanDisconnect |
| { |
| get { return false; } |
| } |
|
|
| |
| |
| |
| |
| |
| internal virtual IEnumerable<RemoteRunspace> GetRunspaces() |
| { |
| return null; |
| } |
|
|
| #endregion |
|
|
| #endregion Job Properties |
|
|
| #region Job State and State Change Event |
|
|
| |
| |
| |
| [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] |
| public event EventHandler<JobStateEventArgs> StateChanged; |
|
|
| |
| |
| |
| |
| |
| |
| protected void SetJobState(JobState state) |
| { |
| AssertNotDisposed(); |
| SetJobState(state, null); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| internal void SetJobState(JobState state, Exception reason) |
| { |
| using (PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource()) |
| { |
| AssertNotDisposed(); |
|
|
| bool alldone = false; |
| JobStateInfo previousState = JobStateInfo; |
|
|
| lock (syncObject) |
| { |
| JobStateInfo = new JobStateInfo(state, reason); |
|
|
| if (state == JobState.Running) |
| { |
| |
| if (PSBeginTime == null) |
| { |
| PSBeginTime = DateTime.Now; |
| } |
| } |
| else if (IsFinishedState(state)) |
| { |
| alldone = true; |
|
|
| |
| if (PSEndTime == null) |
| { |
| PSEndTime = DateTime.Now; |
| } |
| } |
| } |
|
|
| if (alldone) |
| { |
| CloseAllStreams(); |
|
|
| if (_processingOutput) |
| { |
| try |
| { |
| |
| HandleOutputProcessingStateChanged(this, new OutputProcessingStateEventArgs(false)); |
| } |
| catch (Exception) |
| { |
| } |
| } |
| } |
|
|
| #pragma warning disable 56500 |
| |
| |
| try |
| { |
| tracer.WriteMessage("Job", "SetJobState", Guid.Empty, this, "Invoking StateChanged event", null); |
| StateChanged.SafeInvoke(this, new JobStateEventArgs(JobStateInfo.Clone(), previousState)); |
| } |
| catch (Exception exception) |
| { |
| tracer.WriteMessage("Job", "SetJobState", Guid.Empty, this, |
| "Some Job StateChange event handler threw an unhandled exception.", null); |
| tracer.TraceException(exception); |
| } |
|
|
| |
| |
| if (alldone) |
| { |
| lock (syncObject) |
| { |
| _finished?.Set(); |
| } |
| } |
| #pragma warning restore 56500 |
| } |
| } |
|
|
| #endregion Job State and State Change Event |
|
|
| #region Job Public Methods |
|
|
| |
| |
| |
| |
| public abstract void StopJob(); |
|
|
| #endregion Job Public Methods |
|
|
| #region Private/Internal Methods |
|
|
| |
| |
| |
| |
| |
| |
| internal Collection<PSStreamObject> ReadAll() |
| { |
| Output.Clear(); |
| Error.Clear(); |
| Debug.Clear(); |
| Warning.Clear(); |
| Verbose.Clear(); |
| Progress.Clear(); |
|
|
| return Results.ReadAll(); |
| } |
|
|
| |
| |
| |
| |
| |
| internal bool IsFinishedState(JobState state) |
| { |
| lock (syncObject) |
| { |
| return (state == JobState.Completed || state == JobState.Failed || state == JobState.Stopped); |
| } |
| } |
|
|
| internal bool IsPersistentState(JobState state) |
| { |
| lock (syncObject) |
| { |
| return (IsFinishedState(state) || state == JobState.Disconnected || state == JobState.Suspended); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| private void AssertChangesAreAccepted() |
| { |
| AssertNotDisposed(); |
| lock (syncObject) |
| { |
| if (JobStateInfo.State == JobState.Running) |
| { |
| throw new InvalidJobStateException(JobState.Running); |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| protected string AutoGenerateJobName() |
| { |
| return "Job" + Id.ToString(System.Globalization.NumberFormatInfo.InvariantInfo); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| internal void AssertNotDisposed() |
| { |
| if (_isDisposed) |
| { |
| throw PSTraceSource.NewObjectDisposedException("PSJob"); |
| } |
| } |
|
|
| |
| |
| |
| internal void CloseAllStreams() |
| { |
| |
| |
| |
| if (_resultsOwner) { try { _results.Complete(); } catch (Exception e) { TraceException(e); } } |
|
|
| if (_outputOwner) { try { _output.Complete(); } catch (Exception e) { TraceException(e); } } |
|
|
| if (_errorOwner) { try { _error.Complete(); } catch (Exception e) { TraceException(e); } } |
|
|
| if (_progressOwner) { try { _progress.Complete(); } catch (Exception e) { TraceException(e); } } |
|
|
| if (_verboseOwner) { try { _verbose.Complete(); } catch (Exception e) { TraceException(e); } } |
|
|
| if (_warningOwner) { try { _warning.Complete(); } catch (Exception e) { TraceException(e); } } |
|
|
| if (_debugOwner) { try { _debug.Complete(); } catch (Exception e) { TraceException(e); } } |
|
|
| if (_informationOwner) { try { _information.Complete(); } catch (Exception e) { TraceException(e); } } |
| } |
|
|
| private static void TraceException(Exception e) |
| { |
| using (PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource()) |
| { |
| tracer.TraceException(e); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| internal List<Job> GetJobsForLocation(string location) |
| { |
| List<Job> returnJobList = new List<Job>(); |
|
|
| foreach (Job job in ChildJobs) |
| { |
| if (string.Equals(job.Location, location, StringComparison.OrdinalIgnoreCase)) |
| { |
| returnJobList.Add(job); |
| } |
| } |
|
|
| return returnJobList; |
| } |
|
|
| #endregion Private/Internal Methods |
|
|
| #region IDisposable Members |
|
|
| |
| |
| |
| |
| public void Dispose() |
| { |
| Dispose(true); |
| |
| |
| System.GC.SuppressFinalize(this); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| protected virtual void Dispose(bool disposing) |
| { |
| if (disposing) |
| { |
| if (!_isDisposed) |
| { |
| CloseAllStreams(); |
|
|
| |
| lock (syncObject) |
| { |
| if (_finished != null) |
| { |
| _finished.Dispose(); |
| _finished = null; |
| } |
| } |
|
|
| |
| if (_resultsOwner) _results.Dispose(); |
| if (_outputOwner) _output.Dispose(); |
| if (_errorOwner) _error.Dispose(); |
| if (_debugOwner) _debug.Dispose(); |
| if (_informationOwner) _information.Dispose(); |
| if (_verboseOwner) _verbose.Dispose(); |
| if (_warningOwner) _warning.Dispose(); |
| if (_progressOwner) _progress.Dispose(); |
|
|
| _isDisposed = true; |
| } |
| } |
| } |
|
|
| private bool _isDisposed; |
|
|
| #endregion IDisposable Members |
|
|
| #region MonitorOutputProcessing |
|
|
| internal event EventHandler<OutputProcessingStateEventArgs> OutputProcessingStateChanged; |
|
|
| private bool _processingOutput; |
|
|
| |
| |
| |
| internal bool MonitorOutputProcessing |
| { |
| get; |
| set; |
| } |
|
|
| internal void SetMonitorOutputProcessing(IOutputProcessingState outputProcessingState) |
| { |
| if (outputProcessingState != null) |
| { |
| outputProcessingState.OutputProcessingStateChanged += HandleOutputProcessingStateChanged; |
| } |
| } |
|
|
| internal void RemoveMonitorOutputProcessing(IOutputProcessingState outputProcessingState) |
| { |
| if (outputProcessingState != null) |
| { |
| outputProcessingState.OutputProcessingStateChanged -= HandleOutputProcessingStateChanged; |
| } |
| } |
|
|
| private void HandleOutputProcessingStateChanged(object sender, OutputProcessingStateEventArgs e) |
| { |
| _processingOutput = e.ProcessingOutput; |
| OutputProcessingStateChanged.SafeInvoke<OutputProcessingStateEventArgs>(this, e); |
| } |
|
|
| #endregion |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| internal class PSRemotingJob : Job |
| { |
| #region Internal Constructors |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] |
| internal PSRemotingJob(string[] computerNames, |
| List<IThrottleOperation> computerNameHelpers, string remoteCommand, string name) |
| : this(computerNames, computerNameHelpers, remoteCommand, 0, name) |
| { } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| internal PSRemotingJob(PSSession[] remoteRunspaceInfos, |
| List<IThrottleOperation> runspaceHelpers, string remoteCommand, string name) |
| : this(remoteRunspaceInfos, runspaceHelpers, remoteCommand, 0, name) |
| { } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| internal PSRemotingJob(string[] computerNames, |
| List<IThrottleOperation> computerNameHelpers, string remoteCommand, |
| int throttleLimit, string name) |
| : base(remoteCommand, name) |
| { |
| |
| foreach (ExecutionCmdletHelperComputerName helper in computerNameHelpers) |
| { |
| |
| PSRemotingChildJob childJob = new PSRemotingChildJob(remoteCommand, |
| helper, _throttleManager); |
| childJob.StateChanged += HandleChildJobStateChanged; |
| childJob.JobUnblocked += HandleJobUnblocked; |
|
|
| |
| ChildJobs.Add(childJob); |
| } |
|
|
| CommonInit(throttleLimit, computerNameHelpers); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| internal PSRemotingJob(PSSession[] remoteRunspaceInfos, |
| List<IThrottleOperation> runspaceHelpers, string remoteCommand, |
| int throttleLimit, string name) |
| : base(remoteCommand, name) |
| { |
| |
| for (int i = 0; i < remoteRunspaceInfos.Length; i++) |
| { |
| ExecutionCmdletHelperRunspace helper = (ExecutionCmdletHelperRunspace)runspaceHelpers[i]; |
|
|
| |
| PSRemotingChildJob job = new PSRemotingChildJob(remoteCommand, |
| helper, _throttleManager); |
| job.StateChanged += HandleChildJobStateChanged; |
| job.JobUnblocked += HandleJobUnblocked; |
|
|
| |
| ChildJobs.Add(job); |
| } |
|
|
| CommonInit(throttleLimit, runspaceHelpers); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| internal PSRemotingJob(List<IThrottleOperation> helpers, |
| int throttleLimit, string name, bool aggregateResults) |
| : base(string.Empty, name) |
| { |
| |
| |
| |
| foreach (ExecutionCmdletHelper helper in helpers) |
| { |
| PSRemotingChildJob job = new PSRemotingChildJob(helper, _throttleManager, aggregateResults); |
| job.StateChanged += HandleChildJobStateChanged; |
| job.JobUnblocked += HandleJobUnblocked; |
|
|
| ChildJobs.Add(job); |
| } |
|
|
| |
| |
| base.CloseAllStreams(); |
|
|
| |
| SetJobState(JobState.Disconnected); |
|
|
| |
| _throttleManager.ThrottleLimit = throttleLimit; |
| _throttleManager.SubmitOperations(helpers); |
| _throttleManager.EndSubmitOperations(); |
| } |
|
|
| |
| |
| |
| protected PSRemotingJob() { } |
|
|
| |
| |
| |
| private void CommonInit(int throttleLimit, List<IThrottleOperation> helpers) |
| { |
| |
| |
| base.CloseAllStreams(); |
|
|
| |
| SetJobState(JobState.Running); |
|
|
| |
| _throttleManager.ThrottleLimit = throttleLimit; |
| _throttleManager.SubmitOperations(helpers); |
| _throttleManager.EndSubmitOperations(); |
| } |
| #endregion Internal Constructors |
|
|
| #region internal methods |
|
|
| |
| |
| |
| |
| |
| |
| internal List<Job> GetJobsForComputer(string computerName) |
| { |
| List<Job> returnJobList = new List<Job>(); |
|
|
| foreach (Job j in ChildJobs) |
| { |
| if (j is not PSRemotingChildJob child) continue; |
| if (string.Equals(child.Runspace.ConnectionInfo.ComputerName, computerName, |
| StringComparison.OrdinalIgnoreCase)) |
| { |
| returnJobList.Add(child); |
| } |
| } |
|
|
| return returnJobList; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| internal List<Job> GetJobsForRunspace(PSSession runspace) |
| { |
| List<Job> returnJobList = new List<Job>(); |
|
|
| foreach (Job j in ChildJobs) |
| { |
| if (j is not PSRemotingChildJob child) continue; |
| if (child.Runspace.InstanceId.Equals(runspace.InstanceId)) |
| { |
| returnJobList.Add(child); |
| } |
| } |
|
|
| return returnJobList; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| internal List<Job> GetJobsForOperation(IThrottleOperation operation) |
| { |
| List<Job> returnJobList = new List<Job>(); |
| ExecutionCmdletHelper helper = operation as ExecutionCmdletHelper; |
|
|
| foreach (Job j in ChildJobs) |
| { |
| if (j is not PSRemotingChildJob child) continue; |
| if (child.Helper.Equals(helper)) |
| { |
| returnJobList.Add(child); |
| } |
| } |
|
|
| return returnJobList; |
| } |
|
|
| #endregion internal methods |
|
|
| #region Connection Support |
|
|
| |
| |
| |
| internal void ConnectJobs() |
| { |
| |
| List<IThrottleOperation> connectJobOperations = new List<IThrottleOperation>(); |
| foreach (PSRemotingChildJob childJob in ChildJobs) |
| { |
| if (childJob.JobStateInfo.State == JobState.Disconnected) |
| { |
| connectJobOperations.Add(new ConnectJobOperation(childJob)); |
| } |
| } |
|
|
| if (connectJobOperations.Count == 0) |
| { |
| return; |
| } |
|
|
| |
| |
| SubmitAndWaitForConnect(connectJobOperations); |
| } |
|
|
| |
| |
| |
| |
| internal void ConnectJob(Guid runspaceInstanceId) |
| { |
| List<IThrottleOperation> connectJobOperations = new List<IThrottleOperation>(); |
| PSRemotingChildJob childJob = FindDisconnectedChildJob(runspaceInstanceId); |
| if (childJob != null) |
| { |
| connectJobOperations.Add(new ConnectJobOperation(childJob)); |
| } |
|
|
| if (connectJobOperations.Count == 0) |
| { |
| return; |
| } |
|
|
| |
| |
| SubmitAndWaitForConnect(connectJobOperations); |
| } |
|
|
| private static void SubmitAndWaitForConnect(List<IThrottleOperation> connectJobOperations) |
| { |
| using (ThrottleManager connectThrottleManager = new ThrottleManager()) |
| { |
| using (ManualResetEvent connectResult = new ManualResetEvent(false)) |
| { |
| EventHandler<EventArgs> throttleCompleteEventHandler = |
| (object sender, EventArgs eventArgs) => connectResult.Set(); |
|
|
| connectThrottleManager.ThrottleComplete += throttleCompleteEventHandler; |
| try |
| { |
| connectThrottleManager.ThrottleLimit = 0; |
| connectThrottleManager.SubmitOperations(connectJobOperations); |
| connectThrottleManager.EndSubmitOperations(); |
|
|
| connectResult.WaitOne(); |
| } |
| finally |
| { |
| connectThrottleManager.ThrottleComplete -= throttleCompleteEventHandler; |
| } |
| } |
| } |
| } |
|
|
| |
| |
| |
| private sealed class ConnectJobOperation : IThrottleOperation |
| { |
| private readonly PSRemotingChildJob _psRemoteChildJob; |
|
|
| internal ConnectJobOperation(PSRemotingChildJob job) |
| { |
| _psRemoteChildJob = job; |
| _psRemoteChildJob.StateChanged += ChildJobStateChangedHandler; |
| } |
|
|
| internal override void StartOperation() |
| { |
| bool startedSuccessfully = true; |
|
|
| try |
| { |
| _psRemoteChildJob.ConnectAsync(); |
| } |
| catch (InvalidJobStateException e) |
| { |
| startedSuccessfully = false; |
|
|
| string msg = StringUtil.Format(RemotingErrorIdStrings.JobConnectFailed, _psRemoteChildJob.Name); |
| Exception reason = new RuntimeException(msg, e); |
| ErrorRecord errorRecord = new ErrorRecord(reason, "PSJobConnectFailed", ErrorCategory.InvalidOperation, _psRemoteChildJob); |
| _psRemoteChildJob.WriteError(errorRecord); |
| } |
|
|
| if (!startedSuccessfully) |
| { |
| RemoveEventCallback(); |
| SendStartComplete(); |
| } |
| } |
|
|
| internal override void StopOperation() |
| { |
| RemoveEventCallback(); |
|
|
| |
| OperationStateEventArgs operationStateEventArgs = new OperationStateEventArgs(); |
| operationStateEventArgs.OperationState = OperationState.StopComplete; |
| OperationComplete.SafeInvoke(this, operationStateEventArgs); |
| } |
|
|
| internal override event EventHandler<OperationStateEventArgs> OperationComplete; |
|
|
| private void ChildJobStateChangedHandler(object sender, JobStateEventArgs eArgs) |
| { |
| if (eArgs.JobStateInfo.State == JobState.Disconnected) |
| { |
| return; |
| } |
|
|
| RemoveEventCallback(); |
| SendStartComplete(); |
| } |
|
|
| private void SendStartComplete() |
| { |
| OperationStateEventArgs operationStateEventArgs = new OperationStateEventArgs(); |
| operationStateEventArgs.OperationState = OperationState.StartComplete; |
| OperationComplete.SafeInvoke(this, operationStateEventArgs); |
| } |
|
|
| private void RemoveEventCallback() |
| { |
| _psRemoteChildJob.StateChanged -= ChildJobStateChangedHandler; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| internal PowerShell GetAssociatedPowerShellObject(Guid runspaceInstanceId) |
| { |
| PowerShell ps = null; |
| PSRemotingChildJob childJob = FindDisconnectedChildJob(runspaceInstanceId); |
| if (childJob != null) |
| { |
| ps = childJob.GetPowerShell(); |
| } |
|
|
| return ps; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| private PSRemotingChildJob FindDisconnectedChildJob(Guid runspaceInstanceId) |
| { |
| PSRemotingChildJob rtnJob = null; |
|
|
| foreach (PSRemotingChildJob childJob in this.ChildJobs) |
| { |
| if ((childJob.Runspace.InstanceId.Equals(runspaceInstanceId)) && |
| (childJob.JobStateInfo.State == JobState.Disconnected)) |
| { |
| rtnJob = childJob; |
| break; |
| } |
| } |
|
|
| return rtnJob; |
| } |
|
|
| |
| |
| |
| |
| |
| internal void InternalStopJob() |
| { |
| if (_isDisposed || _stopIsCalled || IsFinishedState(JobStateInfo.State)) |
| { |
| return; |
| } |
|
|
| lock (_syncObject) |
| { |
| if (_isDisposed || _stopIsCalled || IsFinishedState(JobStateInfo.State)) |
| { |
| return; |
| } |
|
|
| _stopIsCalled = true; |
| } |
|
|
| _throttleManager.StopAllOperations(); |
|
|
| Finished.WaitOne(); |
| } |
|
|
| #endregion |
|
|
| private bool _moreData = true; |
| |
| |
| |
| |
| |
| |
| public override bool HasMoreData |
| { |
| get |
| { |
| |
| |
| |
|
|
| if (_moreData && IsFinishedState(JobStateInfo.State)) |
| { |
| bool atleastOneChildHasMoreData = false; |
|
|
| for (int i = 0; i < ChildJobs.Count; i++) |
| { |
| if (ChildJobs[i].HasMoreData) |
| { |
| atleastOneChildHasMoreData = true; |
| break; |
| } |
| } |
|
|
| _moreData = atleastOneChildHasMoreData; |
| } |
|
|
| return _moreData; |
| } |
| } |
|
|
| private bool _stopIsCalled = false; |
| |
| |
| |
| public override void StopJob() |
| { |
| |
| |
| if (JobStateInfo.State == JobState.Disconnected) |
| { |
| bool ConnectSuccessful; |
|
|
| try |
| { |
| ConnectJobs(); |
| ConnectSuccessful = true; |
| } |
| catch (InvalidRunspaceStateException) |
| { |
| ConnectSuccessful = false; |
| } |
| catch (PSRemotingTransportException) |
| { |
| ConnectSuccessful = false; |
| } |
| catch (PSInvalidOperationException) |
| { |
| ConnectSuccessful = false; |
| } |
|
|
| if (!ConnectSuccessful && this.Error.IsOpen) |
| { |
| string msg = StringUtil.Format(RemotingErrorIdStrings.StopJobNotConnected, this.Name); |
| Exception reason = new RuntimeException(msg); |
| ErrorRecord errorRecord = new ErrorRecord(reason, "StopJobCannotConnectToServer", |
| ErrorCategory.InvalidOperation, this); |
| WriteError(errorRecord); |
|
|
| return; |
| } |
| } |
|
|
| InternalStopJob(); |
| } |
|
|
| private string _statusMessage; |
| |
| |
| |
| public override string StatusMessage |
| { |
| get |
| { |
| return _statusMessage; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| internal bool HideComputerName |
| { |
| get |
| { |
| return _hideComputerName; |
| } |
|
|
| set |
| { |
| _hideComputerName = value; |
| foreach (Job job in this.ChildJobs) |
| { |
| PSRemotingChildJob rJob = job as PSRemotingChildJob; |
| if (rJob != null) |
| { |
| rJob.HideComputerName = value; |
| } |
| } |
| } |
| } |
|
|
| private bool _hideComputerName = true; |
|
|
| |
| |
| |
| |
| [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] |
| private void SetStatusMessage() |
| { |
| _statusMessage = "test"; |
| |
| |
|
|
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| } |
|
|
| #region finish logic |
|
|
| |
| private bool _atleastOneChildJobFailed = false; |
|
|
| |
| private int _finishedChildJobsCount = 0; |
|
|
| |
| private int _blockedChildJobsCount = 0; |
|
|
| |
| private int _disconnectedChildJobsCount = 0; |
|
|
| |
| private int _debugChildJobsCount = 0; |
|
|
| |
| |
| |
| |
| |
| private void HandleChildJobStateChanged(object sender, JobStateEventArgs e) |
| { |
| |
| CheckDisconnectedAndUpdateState(e.JobStateInfo.State, e.PreviousJobStateInfo.State); |
|
|
| if (e.JobStateInfo.State == JobState.Blocked) |
| { |
| |
| lock (_syncObject) |
| { |
| _blockedChildJobsCount++; |
| } |
|
|
| |
| SetJobState(JobState.Blocked, null); |
| return; |
| } |
|
|
| |
| if (e.JobStateInfo.State == JobState.AtBreakpoint) |
| { |
| lock (_syncObject) { _debugChildJobsCount++; } |
|
|
| |
| SetJobState(JobState.AtBreakpoint); |
| return; |
| } |
|
|
| |
| if ((e.JobStateInfo.State == JobState.Running) && |
| (e.PreviousJobStateInfo.State == JobState.AtBreakpoint)) |
| { |
| int totalDebugCount; |
| lock (_syncObject) { totalDebugCount = --_debugChildJobsCount; } |
|
|
| if (totalDebugCount == 0) |
| { |
| SetJobState(JobState.Running); |
| return; |
| } |
| } |
|
|
| |
| if (!IsFinishedState(e.JobStateInfo.State)) |
| { |
| return; |
| } |
|
|
| if (e.JobStateInfo.State == JobState.Failed) |
| { |
| |
| _atleastOneChildJobFailed = true; |
| } |
|
|
| bool allChildJobsFinished = false; |
| lock (_syncObject) |
| { |
| _finishedChildJobsCount++; |
|
|
| |
| if (_finishedChildJobsCount + _disconnectedChildJobsCount |
| == ChildJobs.Count) |
| { |
| allChildJobsFinished = true; |
| } |
| } |
|
|
| if (allChildJobsFinished) |
| { |
| |
| |
| |
| if (_disconnectedChildJobsCount > 0) |
| { |
| SetJobState(JobState.Disconnected); |
| } |
| else if (_atleastOneChildJobFailed) |
| { |
| SetJobState(JobState.Failed); |
| } |
| else if (_stopIsCalled) |
| { |
| SetJobState(JobState.Stopped); |
| } |
| else |
| { |
| SetJobState(JobState.Completed); |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| private void CheckDisconnectedAndUpdateState(JobState newState, JobState prevState) |
| { |
| if (IsFinishedState(JobStateInfo.State)) |
| { |
| return; |
| } |
|
|
| |
| |
| lock (_syncObject) |
| { |
| if (newState == JobState.Disconnected) |
| { |
| ++(_disconnectedChildJobsCount); |
|
|
| |
| |
| if (prevState == JobState.Blocked) |
| { |
| --_blockedChildJobsCount; |
| } |
|
|
| |
| |
| if ((_disconnectedChildJobsCount + |
| _finishedChildJobsCount + |
| _blockedChildJobsCount) == ChildJobs.Count) |
| { |
| SetJobState(JobState.Disconnected, null); |
| } |
| } |
| else |
| { |
| if (prevState == JobState.Disconnected) |
| { |
| --(_disconnectedChildJobsCount); |
| } |
|
|
| if ((newState == JobState.Running) && (JobStateInfo.State == JobState.Disconnected)) |
| { |
| |
| |
| SetJobState(JobState.Running, null); |
| } |
| } |
| } |
| } |
|
|
| #endregion finish logic |
|
|
| |
| |
| |
| |
| |
| |
| protected override void Dispose(bool disposing) |
| { |
| if (disposing) |
| { |
| if (_isDisposed) |
| { |
| return; |
| } |
|
|
| lock (_syncObject) |
| { |
| if (_isDisposed) |
| { |
| return; |
| } |
|
|
| _isDisposed = true; |
| } |
|
|
| try |
| { |
| if (!IsFinishedState(JobStateInfo.State)) |
| { |
| StopJob(); |
| } |
|
|
| foreach (Job job in ChildJobs) |
| { |
| job.Dispose(); |
| } |
|
|
| _throttleManager.Dispose(); |
| } |
| finally |
| { |
| base.Dispose(disposing); |
| } |
| } |
| } |
|
|
| private bool _isDisposed = false; |
|
|
| private string ConstructLocation() |
| { |
| StringBuilder location = new StringBuilder(); |
|
|
| if (ChildJobs.Count > 0) |
| { |
| foreach (PSRemotingChildJob job in ChildJobs) |
| { |
| location.Append(job.Location); |
| location.Append(','); |
| } |
|
|
| location.Remove(location.Length - 1, 1); |
| } |
|
|
| return location.ToString(); |
| } |
|
|
| |
| |
| |
| public override string Location |
| { |
| get |
| { |
| return ConstructLocation(); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| internal override bool CanDisconnect |
| { |
| get |
| { |
| |
| |
| return (ChildJobs.Count > 0) && ChildJobs[0].CanDisconnect; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| internal override IEnumerable<RemoteRunspace> GetRunspaces() |
| { |
| List<RemoteRunspace> runspaces = new List<RemoteRunspace>(); |
| foreach (PSRemotingChildJob job in ChildJobs) |
| { |
| runspaces.Add(job.Runspace as RemoteRunspace); |
| } |
|
|
| return runspaces; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| private void HandleJobUnblocked(object sender, EventArgs eventArgs) |
| { |
| bool unblockjob = false; |
|
|
| lock (_syncObject) |
| { |
| _blockedChildJobsCount--; |
|
|
| if (_blockedChildJobsCount == 0) |
| { |
| unblockjob = true; |
| } |
| } |
|
|
| if (unblockjob) |
| { |
| SetJobState(JobState.Running, null); |
| } |
| } |
|
|
| #region Private Members |
|
|
| private readonly ThrottleManager _throttleManager = new ThrottleManager(); |
|
|
| private readonly object _syncObject = new object(); |
|
|
| #endregion Private Members |
| } |
|
|
| #region DisconnectedJobOperation class |
|
|
| |
| |
| |
| |
| internal class DisconnectedJobOperation : ExecutionCmdletHelper |
| { |
| internal DisconnectedJobOperation(Pipeline pipeline) |
| { |
| this.pipeline = pipeline; |
| this.pipeline.StateChanged += HandlePipelineStateChanged; |
| } |
|
|
| internal override void StartOperation() |
| { |
| |
| |
| } |
|
|
| internal override void StopOperation() |
| { |
| if (pipeline.PipelineStateInfo.State == PipelineState.Running || |
| pipeline.PipelineStateInfo.State == PipelineState.Disconnected || |
| pipeline.PipelineStateInfo.State == PipelineState.NotStarted) |
| { |
| |
| |
| |
| |
| pipeline.StopAsync(); |
| } |
| else |
| { |
| |
| |
| SendStopComplete(); |
| } |
| } |
|
|
| internal override event EventHandler<OperationStateEventArgs> OperationComplete; |
|
|
| private void HandlePipelineStateChanged(object sender, PipelineStateEventArgs stateEventArgs) |
| { |
| PipelineStateInfo stateInfo = stateEventArgs.PipelineStateInfo; |
|
|
| switch (stateInfo.State) |
| { |
| case PipelineState.Running: |
| case PipelineState.NotStarted: |
| case PipelineState.Stopping: |
| case PipelineState.Disconnected: |
| return; |
| } |
|
|
| SendStopComplete(stateEventArgs); |
| } |
|
|
| private void SendStopComplete(EventArgs eventArgs = null) |
| { |
| OperationStateEventArgs operationStateEventArgs = new OperationStateEventArgs(); |
| operationStateEventArgs.BaseEvent = eventArgs; |
| operationStateEventArgs.OperationState = OperationState.StopComplete; |
| OperationComplete.SafeInvoke(this, operationStateEventArgs); |
| } |
| } |
|
|
| #endregion |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| internal class PSRemotingChildJob : Job, IJobDebugger |
| { |
| #region Internal Constructor |
|
|
| |
| |
| |
| |
| |
| |
| internal PSRemotingChildJob(string remoteCommand, ExecutionCmdletHelper helper, ThrottleManager throttleManager) |
| : base(remoteCommand) |
| { |
| UsesResultsCollection = true; |
| Dbg.Assert(helper.Pipeline is RemotePipeline, "Pipeline passed should be a remote pipeline"); |
|
|
| Helper = helper; |
| Runspace = helper.Pipeline.Runspace; |
| _remotePipeline = helper.Pipeline as RemotePipeline; |
| _throttleManager = throttleManager; |
|
|
| RemoteRunspace remoteRS = Runspace as RemoteRunspace; |
| if ((remoteRS != null) && (remoteRS.RunspaceStateInfo.State == RunspaceState.BeforeOpen)) |
| { |
| remoteRS.URIRedirectionReported += HandleURIDirectionReported; |
| } |
|
|
| AggregateResultsFromHelper(helper); |
|
|
| Runspace.AvailabilityChanged += HandleRunspaceAvailabilityChanged; |
|
|
| RegisterThrottleComplete(throttleManager); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| internal PSRemotingChildJob(ExecutionCmdletHelper helper, ThrottleManager throttleManager, bool aggregateResults = false) |
| { |
| UsesResultsCollection = true; |
| Dbg.Assert((helper.Pipeline is RemotePipeline), "Helper pipeline object should be a remote pipeline"); |
| Dbg.Assert((helper.Pipeline.PipelineStateInfo.State == PipelineState.Disconnected), "Remote pipeline object must be in Disconnected state."); |
|
|
| Helper = helper; |
| _remotePipeline = helper.Pipeline as RemotePipeline; |
| Runspace = helper.Pipeline.Runspace; |
| _throttleManager = throttleManager; |
|
|
| if (aggregateResults) |
| { |
| AggregateResultsFromHelper(helper); |
| } |
| else |
| { |
| _remotePipeline.StateChanged += HandlePipelineStateChanged; |
| _remotePipeline.Output.DataReady += HandleOutputReady; |
| _remotePipeline.Error.DataReady += HandleErrorReady; |
| } |
|
|
| Runspace.AvailabilityChanged += HandleRunspaceAvailabilityChanged; |
|
|
| IThrottleOperation operation = helper as IThrottleOperation; |
| operation.OperationComplete += HandleOperationComplete; |
|
|
| SetJobState(JobState.Disconnected, null); |
| } |
|
|
| |
| |
| |
| protected PSRemotingChildJob() |
| { |
| } |
|
|
| #endregion Internal Constructor |
|
|
| #region Internal Methods |
|
|
| |
| |
| |
| internal void ConnectAsync() |
| { |
| if (JobStateInfo.State != JobState.Disconnected) |
| { |
| throw new InvalidJobStateException(JobStateInfo.State); |
| } |
|
|
| _remotePipeline.ConnectAsync(); |
| } |
|
|
| #endregion |
|
|
| #region stop |
|
|
| |
| |
| |
| |
| public override void StopJob() |
| { |
| if (_isDisposed || _stopIsCalled || IsFinishedState(JobStateInfo.State)) |
| { |
| return; |
| } |
|
|
| lock (SyncObject) |
| { |
| if (_isDisposed || _stopIsCalled || IsFinishedState(JobStateInfo.State)) |
| { |
| return; |
| } |
|
|
| _stopIsCalled = true; |
| } |
|
|
| _throttleManager.StopOperation(Helper); |
|
|
| |
| |
| |
| |
| |
| Finished.WaitOne(); |
| } |
|
|
| #endregion stop |
|
|
| #region Properties |
|
|
| |
| |
| |
| public override string StatusMessage |
| { |
| get |
| { |
| |
| return string.Empty; |
| } |
| } |
|
|
| |
| |
| |
| |
| public override bool HasMoreData |
| { |
| get |
| { |
| return (Results.IsOpen || Results.Count > 0); |
| } |
| } |
|
|
| |
| |
| |
| |
| public override string Location |
| { |
| get |
| { |
| return (Runspace != null) ? Runspace.ConnectionInfo.ComputerName : string.Empty; |
| } |
| } |
|
|
| |
| |
| public Runspace Runspace { get; } |
|
|
| |
| |
| |
| internal ExecutionCmdletHelper Helper { get; } = null; |
|
|
| |
| |
| |
| |
| |
| |
| internal bool HideComputerName |
| { |
| get |
| { |
| return _hideComputerName; |
| } |
|
|
| set |
| { |
| _hideComputerName = value; |
| foreach (Job job in this.ChildJobs) |
| { |
| PSRemotingChildJob rJob = job as PSRemotingChildJob; |
| if (rJob != null) |
| { |
| rJob.HideComputerName = value; |
| } |
| } |
| } |
| } |
|
|
| private bool _hideComputerName = true; |
|
|
| |
| |
| |
| |
| internal bool DisconnectedAndBlocked { get; private set; } = false; |
|
|
| |
| |
| |
| |
| |
| internal override bool CanDisconnect |
| { |
| get |
| { |
| RemoteRunspace remoteRS = Runspace as RemoteRunspace; |
| return remoteRS != null && remoteRS.CanDisconnect; |
| } |
| } |
|
|
| #endregion Properties |
|
|
| #region IJobDebugger |
|
|
| |
| |
| |
| public Debugger Debugger |
| { |
| get |
| { |
| if (_jobDebugger == null) |
| { |
| lock (this.SyncObject) |
| { |
| if ((_jobDebugger == null) && |
| (Runspace.Debugger != null)) |
| { |
| _jobDebugger = new RemotingJobDebugger(Runspace.Debugger, Runspace, this.Name); |
| } |
| } |
| } |
|
|
| return _jobDebugger; |
| } |
| } |
|
|
| |
| |
| |
| public bool IsAsync |
| { |
| get { return _isAsync; } |
|
|
| set { _isAsync = true; } |
| } |
|
|
| #endregion |
|
|
| #region Private Methods |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| private void HandleOutputReady(object sender, EventArgs eventArgs) |
| { |
| PSDataCollectionPipelineReader<PSObject, PSObject> reader = |
| sender as PSDataCollectionPipelineReader<PSObject, PSObject>; |
|
|
| Collection<PSObject> output = reader.NonBlockingRead(); |
|
|
| foreach (PSObject dataObject in output) |
| { |
| |
| |
| |
| if (dataObject != null) |
| { |
| |
| |
| |
|
|
| if (dataObject.Properties[RemotingConstants.ComputerNameNoteProperty] != null) |
| { |
| dataObject.Properties.Remove(RemotingConstants.ComputerNameNoteProperty); |
| } |
|
|
| if (dataObject.Properties[RemotingConstants.RunspaceIdNoteProperty] != null) |
| { |
| dataObject.Properties.Remove(RemotingConstants.RunspaceIdNoteProperty); |
| } |
|
|
| dataObject.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty, reader.ComputerName)); |
| dataObject.Properties.Add(new PSNoteProperty(RemotingConstants.RunspaceIdNoteProperty, reader.RunspaceId)); |
| |
| |
| if (dataObject.Properties[RemotingConstants.ShowComputerNameNoteProperty] == null) |
| { |
| PSNoteProperty showComputerNameNP = new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, !_hideComputerName); |
| dataObject.Properties.Add(showComputerNameNP); |
| } |
| } |
|
|
| this.WriteObject(dataObject); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| private void HandleErrorReady(object sender, EventArgs eventArgs) |
| { |
| PSDataCollectionPipelineReader<ErrorRecord, object> reader = |
| sender as PSDataCollectionPipelineReader<ErrorRecord, object>; |
|
|
| Collection<object> error = reader.NonBlockingRead(); |
|
|
| foreach (object errorData in error) |
| { |
| ErrorRecord er = errorData as ErrorRecord; |
| if (er != null) |
| { |
| OriginInfo originInfo = new OriginInfo(reader.ComputerName, reader.RunspaceId); |
|
|
| RemotingErrorRecord errorRecord = |
| new RemotingErrorRecord(er, originInfo); |
| errorRecord.PreserveInvocationInfoOnce = true; |
|
|
| |
| |
| this.WriteError(errorRecord); |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| protected void HandleURIDirectionReported(object sender, RemoteDataEventArgs<Uri> eventArgs) |
| { |
| string message = StringUtil.Format(RemotingErrorIdStrings.URIRedirectWarningToHost, eventArgs.Data.OriginalString); |
| this.WriteWarning(message); |
| } |
|
|
| |
| |
| |
| |
| |
| private void HandleHostCalls(object sender, EventArgs eventArgs) |
| { |
| ObjectStream hostCallsStream = sender as ObjectStream; |
|
|
| if (hostCallsStream != null) |
| { |
| Collection<object> hostCallMethodExecutors = |
| hostCallsStream.NonBlockingRead(hostCallsStream.Count); |
|
|
| lock (SyncObject) |
| { |
| foreach (ClientMethodExecutor hostCallMethodExecutor in hostCallMethodExecutors) |
| { |
| Results.Add(new PSStreamObject(PSStreamObjectType.MethodExecutor, hostCallMethodExecutor)); |
|
|
| |
| |
| if (hostCallMethodExecutor.RemoteHostCall.CallId != ServerDispatchTable.VoidCallId) |
| { |
| SetJobState(JobState.Blocked, null); |
| } |
| } |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| protected virtual void HandlePipelineStateChanged(object sender, PipelineStateEventArgs e) |
| { |
| if ((Runspace != null) && (e.PipelineStateInfo.State != PipelineState.Running)) |
| { |
| |
| |
| ((RemoteRunspace)Runspace).URIRedirectionReported -= HandleURIDirectionReported; |
| } |
|
|
| PipelineState state = e.PipelineStateInfo.State; |
| switch (state) |
| { |
| case PipelineState.Running: |
| if (DisconnectedAndBlocked) |
| { |
| DisconnectedAndBlocked = false; |
| SetJobState(JobState.Blocked); |
| } |
| else |
| { |
| SetJobState(JobState.Running); |
| } |
|
|
| break; |
|
|
| case PipelineState.Disconnected: |
| DisconnectedAndBlocked = (JobStateInfo.State == JobState.Blocked); |
| SetJobState(JobState.Disconnected); |
| break; |
| } |
|
|
| |
| |
| |
| |
| |
| } |
|
|
| |
| |
| |
| |
| |
| private void HandleThrottleComplete(object sender, EventArgs eventArgs) |
| { |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| DoFinish(); |
| } |
|
|
| |
| |
| |
| |
| |
| protected virtual void HandleOperationComplete(object sender, OperationStateEventArgs stateEventArgs) |
| { |
| |
| |
| |
| |
| |
| |
| |
| ExecutionCmdletHelper helper = sender as ExecutionCmdletHelper; |
| Dbg.Assert(helper != null, "Sender of OperationComplete has to be ExecutionCmdletHelper"); |
|
|
| DeterminedAndSetJobState(helper); |
| } |
|
|
| private bool _doFinishCalled = false; |
|
|
| |
| |
| |
| |
| protected virtual void DoFinish() |
| { |
| if (_doFinishCalled) |
| return; |
|
|
| lock (SyncObject) |
| { |
| if (_doFinishCalled) |
| return; |
|
|
| _doFinishCalled = true; |
| } |
|
|
| DeterminedAndSetJobState(Helper); |
|
|
| DoCleanupOnFinished(); |
| } |
|
|
| |
| |
| |
| private ErrorRecord _failureErrorRecord; |
|
|
| |
| |
| |
| |
| internal ErrorRecord FailureErrorRecord |
| { |
| get |
| { |
| return _failureErrorRecord; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception failureException, |
| out ErrorRecord failureErrorRecord) |
| { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| Dbg.Assert(helper != null, "helper is null"); |
|
|
| RemotePipeline pipeline = helper.Pipeline as RemotePipeline; |
| Dbg.Assert(pipeline != null, "pipeline is null"); |
|
|
| RemoteRunspace runspace = pipeline.GetRunspace() as RemoteRunspace; |
| Dbg.Assert(runspace != null, "runspace is null"); |
|
|
| failureException = null; |
| failureErrorRecord = null; |
|
|
| if (helper.InternalException != null) |
| { |
| string errorId = "RemotePipelineExecutionFailed"; |
| failureException = helper.InternalException; |
| if ((failureException is InvalidRunspaceStateException) || (failureException is InvalidRunspacePoolStateException)) |
| { |
| errorId = "InvalidSessionState"; |
| if (!string.IsNullOrEmpty(failureException.Source)) |
| { |
| errorId = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{errorId},{failureException.Source}"); |
| } |
| } |
|
|
| failureErrorRecord = new ErrorRecord(helper.InternalException, |
| errorId, ErrorCategory.OperationStopped, |
| helper); |
| } |
| |
| else if ((runspace.RunspaceStateInfo.State == RunspaceState.Broken) || |
| (runspace.RunspaceStateInfo.Reason != null)) |
| { |
| failureException = runspace.RunspaceStateInfo.Reason; |
| object targetObject = runspace.ConnectionInfo.ComputerName; |
|
|
| string errorDetails = null; |
|
|
| |
| |
| |
| PSRemotingTransportException transException = |
| failureException as PSRemotingTransportException; |
|
|
| string fullyQualifiedErrorId = |
| System.Management.Automation.Remoting.Client.WSManTransportManagerUtils.GetFQEIDFromTransportError( |
| (transException != null) ? transException.ErrorCode : 0, |
| "PSSessionStateBroken"); |
|
|
| if (transException != null) |
| { |
| errorDetails = "[" + runspace.ConnectionInfo.ComputerName + "] "; |
|
|
| if (transException.ErrorCode == |
| Remoting.Client.WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED) |
| { |
| |
| |
| |
| string message = PSRemotingErrorInvariants.FormatResourceString( |
| RemotingErrorIdStrings.URIRedirectionReported, |
| transException.Message, |
| "MaximumConnectionRedirectionCount", |
| Microsoft.PowerShell.Commands.PSRemotingBaseCmdlet.DEFAULT_SESSION_OPTION, |
| "AllowRedirection"); |
|
|
| errorDetails += message; |
| } |
| else if (!string.IsNullOrEmpty(transException.Message)) |
| { |
| errorDetails += transException.Message; |
| } |
| else if (!string.IsNullOrEmpty(transException.TransportMessage)) |
| { |
| errorDetails += transException.TransportMessage; |
| } |
| } |
|
|
| failureException ??= new RuntimeException( |
| PSRemotingErrorInvariants.FormatResourceString( |
| RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, |
| runspace.RunspaceStateInfo.State)); |
|
|
| failureErrorRecord = new ErrorRecord(failureException, targetObject, |
| fullyQualifiedErrorId, ErrorCategory.OpenError, |
| null, null, null, null, null, errorDetails, null); |
| } |
| else if (pipeline.PipelineStateInfo.State == PipelineState.Failed |
| || (pipeline.PipelineStateInfo.State == PipelineState.Stopped |
| && pipeline.PipelineStateInfo.Reason != null |
| && pipeline.PipelineStateInfo.Reason is not PipelineStoppedException)) |
| { |
| |
| object targetObject = runspace.ConnectionInfo.ComputerName; |
| failureException = pipeline.PipelineStateInfo.Reason; |
| if (failureException != null) |
| { |
| RemoteException rException = failureException as RemoteException; |
|
|
| ErrorRecord errorRecord = null; |
| if (rException != null) |
| { |
| errorRecord = rException.ErrorRecord; |
|
|
| |
| if (errorRecord != null && |
| errorRecord.FullyQualifiedErrorId.Equals("PipelineStopped", StringComparison.OrdinalIgnoreCase)) |
| { |
| |
| failureException = null; |
| return; |
| } |
| } |
| else |
| { |
| |
| |
| |
| |
| |
| |
| errorRecord = new ErrorRecord(pipeline.PipelineStateInfo.Reason, |
| "JobFailure", ErrorCategory.OperationStopped, |
| targetObject); |
| } |
|
|
| string computerName = ((RemoteRunspace)pipeline.GetRunspace()).ConnectionInfo.ComputerName; |
| Guid runspaceId = pipeline.GetRunspace().InstanceId; |
|
|
| OriginInfo originInfo = new OriginInfo(computerName, runspaceId); |
|
|
| failureErrorRecord = new RemotingErrorRecord(errorRecord, originInfo); |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| protected override void Dispose(bool disposing) |
| { |
| if (disposing) |
| { |
| if (_isDisposed) |
| { |
| return; |
| } |
|
|
| lock (SyncObject) |
| { |
| if (_isDisposed) |
| { |
| return; |
| } |
|
|
| _isDisposed = true; |
| } |
|
|
| try |
| { |
| DoCleanupOnFinished(); |
| } |
| finally |
| { |
| base.Dispose(disposing); |
| } |
| } |
| } |
|
|
| private bool _isDisposed = false; |
|
|
| private bool _cleanupDone = false; |
|
|
| |
| |
| |
| protected virtual void DoCleanupOnFinished() |
| { |
| bool doCleanup = false; |
| if (!_cleanupDone) |
| { |
| lock (SyncObject) |
| { |
| if (!_cleanupDone) |
| { |
| _cleanupDone = true; |
| doCleanup = true; |
| } |
| } |
| } |
|
|
| if (!doCleanup) return; |
|
|
| StopAggregateResultsFromHelper(Helper); |
| Runspace.AvailabilityChanged -= HandleRunspaceAvailabilityChanged; |
| IThrottleOperation operation = Helper as IThrottleOperation; |
| operation.OperationComplete -= HandleOperationComplete; |
| UnregisterThrottleComplete(_throttleManager); |
| _throttleManager = null; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| protected void AggregateResultsFromHelper(ExecutionCmdletHelper helper) |
| { |
| |
| Pipeline pipeline = helper.Pipeline; |
| pipeline.Output.DataReady += HandleOutputReady; |
| pipeline.Error.DataReady += HandleErrorReady; |
| pipeline.StateChanged += HandlePipelineStateChanged; |
|
|
| |
| Dbg.Assert(pipeline is RemotePipeline, "pipeline is RemotePipeline"); |
| RemotePipeline remotePipeline = pipeline as RemotePipeline; |
| remotePipeline.MethodExecutorStream.DataReady += HandleHostCalls; |
| remotePipeline.PowerShell.Streams.Progress.DataAdded += HandleProgressAdded; |
| remotePipeline.PowerShell.Streams.Warning.DataAdded += HandleWarningAdded; |
| remotePipeline.PowerShell.Streams.Verbose.DataAdded += HandleVerboseAdded; |
| remotePipeline.PowerShell.Streams.Debug.DataAdded += HandleDebugAdded; |
| remotePipeline.PowerShell.Streams.Information.DataAdded += HandleInformationAdded; |
|
|
| |
| |
| remotePipeline.IsMethodExecutorStreamEnabled = true; |
|
|
| IThrottleOperation operation = helper as IThrottleOperation; |
| operation.OperationComplete += HandleOperationComplete; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| private PowerShell GetPipelinePowerShell(RemotePipeline pipeline, Guid instanceId) |
| { |
| if (pipeline != null) |
| { |
| return pipeline.PowerShell; |
| } |
|
|
| return GetPowerShell(instanceId); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| private void HandleDebugAdded(object sender, DataAddedEventArgs eventArgs) |
| { |
| int index = eventArgs.Index; |
| PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); |
|
|
| if (powershell != null) |
| { |
| this.Debug.Add(powershell.Streams.Debug[index]); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| private void HandleVerboseAdded(object sender, DataAddedEventArgs eventArgs) |
| { |
| int index = eventArgs.Index; |
| PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); |
|
|
| if (powershell != null) |
| { |
| this.Verbose.Add(powershell.Streams.Verbose[index]); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| private void HandleWarningAdded(object sender, DataAddedEventArgs eventArgs) |
| { |
| int index = eventArgs.Index; |
| PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); |
|
|
| if (powershell != null) |
| { |
| WarningRecord warningRecord = powershell.Streams.Warning[index]; |
| this.Warning.Add(warningRecord); |
| this.Results.Add(new PSStreamObject(PSStreamObjectType.WarningRecord, warningRecord)); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| private void HandleProgressAdded(object sender, DataAddedEventArgs eventArgs) |
| { |
| int index = eventArgs.Index; |
| PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); |
|
|
| if (powershell != null) |
| { |
| this.Progress.Add(powershell.Streams.Progress[index]); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| private void HandleInformationAdded(object sender, DataAddedEventArgs eventArgs) |
| { |
| int index = eventArgs.Index; |
| PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); |
|
|
| if (powershell != null) |
| { |
| InformationRecord informationRecord = powershell.Streams.Information[index]; |
| this.Information.Add(informationRecord); |
|
|
| |
| |
| |
| if (informationRecord.Tags.Contains("PSHOST")) |
| { |
| informationRecord.Tags.Add("FORWARDED"); |
| } |
|
|
| this.Results.Add(new PSStreamObject(PSStreamObjectType.Information, informationRecord)); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| protected void StopAggregateResultsFromHelper(ExecutionCmdletHelper helper) |
| { |
| |
| RemoveAggreateCallbacksFromHelper(helper); |
|
|
| Pipeline pipeline = helper.Pipeline; |
| pipeline.Dispose(); |
| pipeline = null; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| protected void RemoveAggreateCallbacksFromHelper(ExecutionCmdletHelper helper) |
| { |
| |
| Pipeline pipeline = helper.Pipeline; |
| pipeline.Output.DataReady -= HandleOutputReady; |
| pipeline.Error.DataReady -= HandleErrorReady; |
| pipeline.StateChanged -= HandlePipelineStateChanged; |
|
|
| |
| Dbg.Assert(pipeline is RemotePipeline, "pipeline is RemotePipeline"); |
| RemotePipeline remotePipeline = pipeline as RemotePipeline; |
| remotePipeline.MethodExecutorStream.DataReady -= HandleHostCalls; |
| if (remotePipeline.PowerShell != null) |
| { |
| remotePipeline.PowerShell.Streams.Progress.DataAdded -= HandleProgressAdded; |
| remotePipeline.PowerShell.Streams.Warning.DataAdded -= HandleWarningAdded; |
| remotePipeline.PowerShell.Streams.Verbose.DataAdded -= HandleVerboseAdded; |
| remotePipeline.PowerShell.Streams.Debug.DataAdded -= HandleDebugAdded; |
| remotePipeline.PowerShell.Streams.Information.DataAdded -= HandleInformationAdded; |
| remotePipeline.IsMethodExecutorStreamEnabled = false; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| protected void RegisterThrottleComplete(ThrottleManager throttleManager) |
| { |
| throttleManager.ThrottleComplete += HandleThrottleComplete; |
| } |
|
|
| |
| |
| |
| |
| |
| protected void UnregisterThrottleComplete(ThrottleManager throttleManager) |
| { |
| throttleManager.ThrottleComplete -= HandleThrottleComplete; |
| } |
|
|
| |
| |
| |
| |
| |
| protected void DeterminedAndSetJobState(ExecutionCmdletHelper helper) |
| { |
| Exception failureException; |
| |
| ProcessJobFailure(helper, out failureException, out _failureErrorRecord); |
|
|
| if (failureException != null) |
| { |
| SetJobState(JobState.Failed, failureException); |
| } |
| else |
| { |
| |
| PipelineState state = helper.Pipeline.PipelineStateInfo.State; |
| if (state == PipelineState.NotStarted) |
| { |
| |
| |
| SetJobState(JobState.Stopped); |
| } |
| else if (state == PipelineState.Completed) |
| { |
| SetJobState(JobState.Completed); |
| } |
| else |
| { |
| SetJobState(JobState.Stopped); |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| internal void UnblockJob() |
| { |
| Dbg.Assert(JobStateInfo.State == JobState.Blocked, |
| "Current state of job must be blocked before it can be unblocked"); |
|
|
| SetJobState(JobState.Running, null); |
|
|
| Dbg.Assert(JobUnblocked != null, "Parent job must register for JobUnblocked event from all child jobs"); |
| JobUnblocked.SafeInvoke(this, EventArgs.Empty); |
| } |
|
|
| |
| |
| |
| |
| |
| internal virtual PowerShell GetPowerShell(Guid instanceId) |
| { |
| |
| throw PSTraceSource.NewInvalidOperationException(); |
| } |
|
|
| |
| |
| |
| |
| internal PowerShell GetPowerShell() |
| { |
| PowerShell ps = null; |
| if (_remotePipeline != null) |
| { |
| ps = _remotePipeline.PowerShell; |
| } |
|
|
| return ps; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| private void HandleRunspaceAvailabilityChanged(object sender, RunspaceAvailabilityEventArgs e) |
| { |
| RunspaceAvailability prevAvailability = _prevRunspaceAvailability; |
| _prevRunspaceAvailability = e.RunspaceAvailability; |
|
|
| if (e.RunspaceAvailability == RunspaceAvailability.RemoteDebug) |
| { |
| SetJobState(JobState.AtBreakpoint); |
| } |
| else if ((prevAvailability == RunspaceAvailability.RemoteDebug) && |
| (e.RunspaceAvailability == RunspaceAvailability.Busy)) |
| { |
| SetJobState(JobState.Running); |
| } |
| } |
|
|
| |
| |
| |
| |
| internal event EventHandler JobUnblocked; |
|
|
| #endregion Private Methods |
|
|
| #region Private Members |
|
|
| |
| private readonly RemotePipeline _remotePipeline = null; |
|
|
| |
| protected object SyncObject = new object(); |
|
|
| private ThrottleManager _throttleManager; |
| private bool _stopIsCalled = false; |
|
|
| private volatile Debugger _jobDebugger; |
|
|
| private bool _isAsync = true; |
|
|
| private RunspaceAvailability _prevRunspaceAvailability = RunspaceAvailability.None; |
|
|
| #endregion Private Members |
| } |
|
|
| |
| |
| |
| |
| internal sealed class RemotingJobDebugger : Debugger |
| { |
| #region Members |
|
|
| private readonly Debugger _wrappedDebugger; |
| private readonly Runspace _runspace; |
| private readonly string _jobName; |
|
|
| #endregion |
|
|
| #region Constructor |
|
|
| private RemotingJobDebugger() { } |
|
|
| |
| |
| |
| |
| |
| |
| public RemotingJobDebugger( |
| Debugger debugger, |
| Runspace runspace, |
| string jobName) |
| { |
| if (debugger == null) |
| { |
| throw new PSArgumentNullException(nameof(debugger)); |
| } |
|
|
| if (runspace == null) |
| { |
| throw new PSArgumentNullException(nameof(runspace)); |
| } |
|
|
| _wrappedDebugger = debugger; |
| _runspace = runspace; |
| _jobName = jobName ?? string.Empty; |
|
|
| |
| _wrappedDebugger.BreakpointUpdated += HandleBreakpointUpdated; |
| _wrappedDebugger.DebuggerStop += HandleDebuggerStop; |
| } |
|
|
| #endregion |
|
|
| #region Debugger overrides |
|
|
| |
| |
| |
| |
| |
| |
| |
| public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataCollection<PSObject> output) |
| { |
| |
| if (command.Commands[0].CommandText.Trim().Equals("prompt", StringComparison.OrdinalIgnoreCase)) |
| { |
| return HandlePromptCommand(output); |
| } |
|
|
| return _wrappedDebugger.ProcessCommand(command, output); |
| } |
|
|
| |
| |
| |
| |
| |
| public override void SetBreakpoints(IEnumerable<Breakpoint> breakpoints, int? runspaceId) => |
| _wrappedDebugger.SetBreakpoints(breakpoints, runspaceId); |
|
|
| |
| |
| |
| |
| |
| |
| public override Breakpoint GetBreakpoint(int id, int? runspaceId) => |
| _wrappedDebugger.GetBreakpoint(id, runspaceId); |
|
|
| |
| |
| |
| |
| |
| public override List<Breakpoint> GetBreakpoints(int? runspaceId) => |
| _wrappedDebugger.GetBreakpoints(runspaceId); |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| public override CommandBreakpoint SetCommandBreakpoint(string command, ScriptBlock action, string path, int? runspaceId) => |
| _wrappedDebugger.SetCommandBreakpoint(command, action, path, runspaceId); |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| public override LineBreakpoint SetLineBreakpoint(string path, int line, int column, ScriptBlock action, int? runspaceId) => |
| _wrappedDebugger.SetLineBreakpoint(path, line, column, action, runspaceId); |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| public override VariableBreakpoint SetVariableBreakpoint(string variableName, VariableAccessMode accessMode, ScriptBlock action, string path, int? runspaceId) => |
| _wrappedDebugger.SetVariableBreakpoint(variableName, accessMode, action, path, runspaceId); |
|
|
| |
| |
| |
| |
| |
| |
| public override bool RemoveBreakpoint(Breakpoint breakpoint, int? runspaceId) => |
| _wrappedDebugger.RemoveBreakpoint(breakpoint, runspaceId); |
|
|
| |
| |
| |
| |
| |
| |
| public override Breakpoint EnableBreakpoint(Breakpoint breakpoint, int? runspaceId) => |
| _wrappedDebugger.EnableBreakpoint(breakpoint, runspaceId); |
|
|
| |
| |
| |
| |
| |
| |
| public override Breakpoint DisableBreakpoint(Breakpoint breakpoint, int? runspaceId) => |
| _wrappedDebugger.DisableBreakpoint(breakpoint, runspaceId); |
|
|
| |
| |
| |
| |
| public override void SetDebuggerAction(DebuggerResumeAction resumeAction) |
| { |
| _wrappedDebugger.SetDebuggerAction(resumeAction); |
| } |
|
|
| |
| |
| |
| public override void StopProcessCommand() |
| { |
| _wrappedDebugger.StopProcessCommand(); |
| } |
|
|
| |
| |
| |
| |
| |
| public override DebuggerStopEventArgs GetDebuggerStopArgs() |
| { |
| return _wrappedDebugger.GetDebuggerStopArgs(); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| public override void SetParent( |
| Debugger parent, |
| IEnumerable<Breakpoint> breakPoints, |
| DebuggerResumeAction? startAction, |
| PSHost host, |
| PathInfo path) |
| { |
| |
| SetDebuggerStepMode(true); |
| } |
|
|
| |
| |
| |
| public override void SetDebugMode(DebugModes mode) |
| { |
| _wrappedDebugger.SetDebugMode(mode); |
|
|
| base.SetDebugMode(mode); |
| } |
|
|
| |
| |
| |
| |
| public override IEnumerable<CallStackFrame> GetCallStack() |
| { |
| return _wrappedDebugger.GetCallStack(); |
| } |
|
|
| |
| |
| |
| |
| public override void SetDebuggerStepMode(bool enabled) |
| { |
| _wrappedDebugger.SetDebuggerStepMode(enabled); |
| } |
|
|
| |
| |
| |
| internal void CheckStateAndRaiseStopEvent() |
| { |
| RemoteDebugger remoteDebugger = _wrappedDebugger as RemoteDebugger; |
| remoteDebugger?.CheckStateAndRaiseStopEvent(); |
| } |
|
|
| |
| |
| |
| public override bool InBreakpoint |
| { |
| get { return _wrappedDebugger.InBreakpoint; } |
| } |
|
|
| #endregion |
|
|
| #region Private methods |
|
|
| private void HandleDebuggerStop(object sender, DebuggerStopEventArgs e) |
| { |
| Pipeline remoteRunningCmd = null; |
| try |
| { |
| |
| remoteRunningCmd = DrainAndBlockRemoteOutput(); |
|
|
| this.RaiseDebuggerStopEvent(e); |
| } |
| finally |
| { |
| RestoreRemoteOutput(remoteRunningCmd); |
| } |
| } |
|
|
| private Pipeline DrainAndBlockRemoteOutput() |
| { |
| |
| if (_runspace is not RemoteRunspace) { return null; } |
|
|
| Pipeline runningCmd = _runspace.GetCurrentlyRunningPipeline(); |
| if (runningCmd != null) |
| { |
| runningCmd.DrainIncomingData(); |
| runningCmd.SuspendIncomingData(); |
|
|
| return runningCmd; |
| } |
|
|
| return null; |
| } |
|
|
| private static void RestoreRemoteOutput(Pipeline runningCmd) => runningCmd?.ResumeIncomingData(); |
|
|
| private void HandleBreakpointUpdated(object sender, BreakpointUpdatedEventArgs e) |
| { |
| this.RaiseBreakpointUpdatedEvent(e); |
| } |
|
|
| private DebuggerCommandResults HandlePromptCommand(PSDataCollection<PSObject> output) |
| { |
| |
| |
| string promptScript = "'[DBG]: '" + " + " + "'[" + CodeGeneration.EscapeSingleQuotedStringContent(_jobName) + "]: '" + " + " + @"""PS $($executionContext.SessionState.Path.CurrentLocation)>> """; |
| PSCommand promptCommand = new PSCommand(); |
| promptCommand.AddScript(promptScript); |
| _wrappedDebugger.ProcessCommand(promptCommand, output); |
|
|
| return new DebuggerCommandResults(null, true); |
| } |
|
|
| #endregion |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| internal class PSInvokeExpressionSyncJob : PSRemotingChildJob |
| { |
| #region Private Members |
|
|
| private readonly List<ExecutionCmdletHelper> _helpers = new List<ExecutionCmdletHelper>(); |
| private readonly ThrottleManager _throttleManager; |
| private readonly Dictionary<Guid, PowerShell> _powershells = new Dictionary<Guid, PowerShell>(); |
|
|
| private int _pipelineFinishedCount; |
| private int _pipelineDisconnectedCount; |
|
|
| #endregion Private Members |
|
|
| #region Constructors |
|
|
| |
| |
| |
| |
| |
| |
| internal PSInvokeExpressionSyncJob(List<IThrottleOperation> operations, ThrottleManager throttleManager) |
| { |
| UsesResultsCollection = true; |
| Results.AddRef(); |
|
|
| _throttleManager = throttleManager; |
| RegisterThrottleComplete(_throttleManager); |
|
|
| foreach (IThrottleOperation operation in operations) |
| { |
| ExecutionCmdletHelper helper = operation as ExecutionCmdletHelper; |
|
|
| RemoteRunspace remoteRS = helper.Pipeline.Runspace as RemoteRunspace; |
| if (remoteRS != null) |
| { |
| remoteRS.StateChanged += HandleRunspaceStateChanged; |
|
|
| if (remoteRS.RunspaceStateInfo.State == RunspaceState.BeforeOpen) |
| { |
| remoteRS.URIRedirectionReported += HandleURIDirectionReported; |
| } |
| } |
|
|
| _helpers.Add(helper); |
| AggregateResultsFromHelper(helper); |
|
|
| Dbg.Assert(helper.Pipeline is RemotePipeline, "Only remote pipeline can be used in InvokeExpressionSyncJob"); |
| RemotePipeline pipeline = helper.Pipeline as RemotePipeline; |
| _powershells.Add(pipeline.PowerShell.InstanceId, pipeline.PowerShell); |
| } |
| } |
|
|
| #endregion Constructors |
|
|
| #region Protected Methods |
|
|
| private bool _cleanupDone = false; |
|
|
| |
| |
| |
| protected override void DoCleanupOnFinished() |
| { |
| bool doCleanup = false; |
| if (!_cleanupDone) |
| { |
| lock (SyncObject) |
| { |
| if (!_cleanupDone) |
| { |
| _cleanupDone = true; |
| doCleanup = true; |
| } |
| } |
| } |
|
|
| if (!doCleanup) return; |
|
|
| foreach (ExecutionCmdletHelper helper in _helpers) |
| { |
| |
| RemoteRunspace remoteRS = helper.PipelineRunspace as RemoteRunspace; |
| if (remoteRS != null) |
| { |
| remoteRS.StateChanged -= HandleRunspaceStateChanged; |
| remoteRS.URIRedirectionReported -= HandleURIDirectionReported; |
| } |
|
|
| StopAggregateResultsFromHelper(helper); |
| } |
|
|
| UnregisterThrottleComplete(_throttleManager); |
| |
|
|
| Results.DecrementRef(); |
| } |
|
|
| |
| |
| |
| |
| protected override void Dispose(bool disposing) |
| { |
| base.Dispose(disposing); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| protected override void HandleOperationComplete(object sender, OperationStateEventArgs stateEventArgs) |
| { |
| ExecutionCmdletHelper helper = sender as ExecutionCmdletHelper; |
| Dbg.Assert(helper != null, "Sender of OperationComplete has to be ExecutionCmdletHelper"); |
|
|
| Exception failureException; |
| |
| ErrorRecord failureErrorRecord; |
|
|
| ProcessJobFailure(helper, out failureException, out failureErrorRecord); |
|
|
| if (failureErrorRecord != null) |
| { |
| this.WriteError(failureErrorRecord); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| protected override void HandlePipelineStateChanged(object sender, PipelineStateEventArgs e) |
| { |
| PipelineState state = e.PipelineStateInfo.State; |
| switch (state) |
| { |
| case PipelineState.Running: |
| SetJobState(JobState.Running); |
| break; |
|
|
| case PipelineState.Completed: |
| case PipelineState.Failed: |
| case PipelineState.Stopped: |
| case PipelineState.Disconnected: |
| CheckForAndSetDisconnectedState(state); |
| break; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| private void CheckForAndSetDisconnectedState(PipelineState pipelineState) |
| { |
| bool setJobStateToDisconnected; |
| lock (SyncObject) |
| { |
| if (IsTerminalState()) |
| { |
| return; |
| } |
|
|
| switch (pipelineState) |
| { |
| case PipelineState.Completed: |
| case PipelineState.Failed: |
| case PipelineState.Stopped: |
| _pipelineFinishedCount += 1; |
| break; |
|
|
| case PipelineState.Disconnected: |
| _pipelineDisconnectedCount += 1; |
| break; |
| } |
|
|
| setJobStateToDisconnected = ((_pipelineFinishedCount + _pipelineDisconnectedCount) == _helpers.Count && |
| _pipelineDisconnectedCount > 0); |
| } |
|
|
| if (setJobStateToDisconnected) |
| { |
| |
| |
| SetJobState(JobState.Disconnected); |
| } |
| } |
|
|
| |
| |
| |
| public override void StopJob() |
| { |
| _throttleManager.StopAllOperations(); |
| } |
|
|
| private bool _doFinishCalled = false; |
|
|
| |
| |
| |
| |
| protected override void DoFinish() |
| { |
| if (_doFinishCalled) |
| return; |
|
|
| lock (SyncObject) |
| { |
| if (_doFinishCalled) |
| return; |
|
|
| _doFinishCalled = true; |
| } |
|
|
| foreach (ExecutionCmdletHelper helper in _helpers) |
| { |
| DeterminedAndSetJobState(helper); |
| } |
|
|
| if (_helpers.Count == 0 && this.JobStateInfo.State == JobState.NotStarted) |
| { |
| SetJobState(JobState.Completed); |
| } |
|
|
| DoCleanupOnFinished(); |
| } |
|
|
| |
| |
| |
| |
| |
| internal override PowerShell GetPowerShell(Guid instanceId) |
| { |
| PowerShell powershell = null; |
|
|
| _powershells.TryGetValue(instanceId, out powershell); |
|
|
| return powershell; |
| } |
|
|
| #endregion Protected Methods |
|
|
| #region Event Handlers |
|
|
| |
| |
| |
| |
| |
| private void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs e) |
| { |
| RemoteRunspace remoteRS = sender as RemoteRunspace; |
| |
| |
| if (remoteRS != null) |
| { |
| if (e.RunspaceStateInfo.State != RunspaceState.Opening) |
| { |
| remoteRS.URIRedirectionReported -= HandleURIDirectionReported; |
|
|
| if (e.RunspaceStateInfo.State != RunspaceState.Opened) |
| { |
| remoteRS.StateChanged -= HandleRunspaceStateChanged; |
| } |
| } |
| } |
| } |
|
|
| #endregion |
|
|
| #region Internal Methods |
|
|
| |
| |
| |
| internal void StartOperations(List<IThrottleOperation> operations) |
| { |
| |
| _throttleManager.SubmitOperations(operations); |
| _throttleManager.EndSubmitOperations(); |
| } |
|
|
| |
| |
| |
| |
| |
| internal bool IsTerminalState() |
| { |
| return (IsFinishedState(this.JobStateInfo.State) || |
| this.JobStateInfo.State == JobState.Disconnected); |
| } |
|
|
| |
| |
| |
| |
| internal Collection<PowerShell> GetPowerShells() |
| { |
| Collection<PowerShell> powershellsToReturn = new Collection<PowerShell>(); |
| foreach (PowerShell ps in _powershells.Values) |
| { |
| powershellsToReturn.Add(ps); |
| } |
|
|
| return powershellsToReturn; |
| } |
|
|
| |
| |
| |
| |
| |
| internal PSRemotingJob CreateDisconnectedRemotingJob() |
| { |
| List<IThrottleOperation> disconnectedJobHelpers = new List<IThrottleOperation>(); |
| foreach (var helper in _helpers) |
| { |
| if (helper.Pipeline.PipelineStateInfo.State == PipelineState.Disconnected) |
| { |
| |
| RemoveAggreateCallbacksFromHelper(helper); |
|
|
| |
| disconnectedJobHelpers.Add(new DisconnectedJobOperation(helper.Pipeline)); |
| } |
| } |
|
|
| if (disconnectedJobHelpers.Count == 0) |
| { |
| return null; |
| } |
|
|
| return new PSRemotingJob(disconnectedJobHelpers, 0, Name, true); |
| } |
|
|
| #endregion Internal Methods |
| } |
|
|
| #region OutputProcessingState class |
|
|
| internal class OutputProcessingStateEventArgs : EventArgs |
| { |
| internal bool ProcessingOutput { get; } |
|
|
| internal OutputProcessingStateEventArgs(bool processingOutput) |
| { |
| ProcessingOutput = processingOutput; |
| } |
| } |
|
|
| #nullable enable |
| internal interface IOutputProcessingState |
| { |
| event EventHandler<OutputProcessingStateEventArgs>? OutputProcessingStateChanged; |
| } |
|
|
| #endregion |
| } |
|
|