protected void UpdateRunspaceAvailability(RunspaceState runspaceState, bool raiseEvent) { System.Management.Automation.Runspaces.RunspaceAvailability runspaceAvailability = this.RunspaceAvailability; RemoteRunspace runspace = this as RemoteRunspace; ConnectCommandInfo info = (runspace != null) ? runspace.RemoteCommand : null; switch (runspaceAvailability) { case System.Management.Automation.Runspaces.RunspaceAvailability.None: if (runspaceState == RunspaceState.Opened) { this.RunspaceAvailability = ((info == null) && (this.GetCurrentlyRunningPipeline() == null)) ? System.Management.Automation.Runspaces.RunspaceAvailability.Available : System.Management.Automation.Runspaces.RunspaceAvailability.Busy; } break; case System.Management.Automation.Runspaces.RunspaceAvailability.Available: case System.Management.Automation.Runspaces.RunspaceAvailability.AvailableForNestedCommand: case System.Management.Automation.Runspaces.RunspaceAvailability.Busy: switch (runspaceState) { case RunspaceState.Closed: case RunspaceState.Closing: case RunspaceState.Broken: case RunspaceState.Disconnected: this.RunspaceAvailability = System.Management.Automation.Runspaces.RunspaceAvailability.None; goto Label_007D; } break; } Label_007D: if (raiseEvent && (this.RunspaceAvailability != runspaceAvailability)) { this.OnAvailabilityChanged(new RunspaceAvailabilityEventArgs(this.RunspaceAvailability)); } }
private static void DefaultRunspace_StateChanged(object sender, RunspaceStateEventArgs e) { CimSessionState cimSessionState = null; Runspace runspace = (Runspace)sender; RunspaceState state = e.RunspaceStateInfo.State; switch (state) { case RunspaceState.Closed: case RunspaceState.Broken: { if (CimSessionBase.cimSessions.TryRemove(runspace.InstanceId, out cimSessionState)) { object[] instanceId = new object[2]; instanceId[0] = runspace.InstanceId; instanceId[1] = e.RunspaceStateInfo.State; DebugHelper.WriteLog(string.Format(CultureInfo.CurrentUICulture, DebugHelper.runspaceStateChanged, instanceId)); cimSessionState.Dispose(); } runspace.StateChanged -= new EventHandler <RunspaceStateEventArgs>(CimSessionBase.DefaultRunspace_StateChanged); return; } case RunspaceState.Closing: { return; } default: { return; } } }
internal InvalidRunspaceStateException( string message, RunspaceState currentState, RunspaceState expectedState) : base(message) { this._expectedState = expectedState; this._currentState = currentState; }
/// <summary> /// Initializes a new instance of the InvalidRunspaceStateException /// with a specified error message and current and expected state. /// </summary> /// <param name="message">The message that describes the error. </param> /// <param name="currentState">Current state of runspace</param> /// <param name="expectedState">Expected states of runspace</param> internal InvalidRunspaceStateException ( string message, RunspaceState currentState, RunspaceState expectedState ) : base(message) { _expectedState = expectedState; _currentState = currentState; }
private void SetRunspaceState(RunspaceState state, Exception reason) { lock (this._syncRoot) { if (state != this._runspaceStateInfo.State) { this._runspaceStateInfo = new System.Management.Automation.Runspaces.RunspaceStateInfo(state, reason); System.Management.Automation.Runspaces.RunspaceAvailability currentAvailability = this._runspaceAvailability; base.UpdateRunspaceAvailability(this._runspaceStateInfo.State, false); this._runspaceEventQueue.Enqueue(new RunspaceEventQueueItem(this._runspaceStateInfo.Clone(), currentAvailability, this._runspaceAvailability)); PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceStateChange, PSOpcode.Open, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, new object[] { state.ToString() }); } } }
/// <summary> /// Constructor for state changes with an optional error /// </summary> /// <param name="state">The state of runspace.</param> /// <param name="reason">A non-null exception if the state change was /// caused by an error, otherwise; null. /// </param> internal RunspaceStateInfo(RunspaceState state, Exception reason) : base() { State = state; Reason = reason; }
/// <summary> /// Used to update the runspace availability event when the state of the runspace changes /// </summary> /// <remarks> /// The possible runspace states are: /// BeforeOpen /// Opening /// Opened /// Closed /// Closing /// Broken /// </remarks> protected void UpdateRunspaceAvailability(RunspaceState runspaceState, bool raiseEvent) { RunspaceAvailability oldAvailability = this.RunspaceAvailability; RemoteRunspace remoteRunspace = this as RemoteRunspace; Internal.ConnectCommandInfo remoteCommand = null; bool remoteDebug = false; if (remoteRunspace != null) { remoteCommand = remoteRunspace.RemoteCommand; RemoteDebugger remoteDebugger = remoteRunspace.Debugger as RemoteDebugger; remoteDebug = (remoteDebugger != null) && remoteDebugger.IsRemoteDebug; } switch (oldAvailability) { case RunspaceAvailability.None: switch (runspaceState) { case RunspaceState.Opened: if (remoteDebug) { this.RunspaceAvailability = Runspaces.RunspaceAvailability.RemoteDebug; } else { this.RunspaceAvailability = (remoteCommand == null && GetCurrentlyRunningPipeline() == null) ? RunspaceAvailability.Available : RunspaceAvailability.Busy; } break; default: break; // no change in the availability } break; case RunspaceAvailability.Available: case RunspaceAvailability.AvailableForNestedCommand: case RunspaceAvailability.RemoteDebug: case RunspaceAvailability.Busy: switch (runspaceState) { case RunspaceState.Closing: case RunspaceState.Closed: case RunspaceState.Broken: case RunspaceState.Disconnected: this.RunspaceAvailability = RunspaceAvailability.None; break; default: break; // no change in the availability } break; default: Diagnostics.Assert(false, "Invalid RunspaceAvailability"); break; } if (raiseEvent && this.RunspaceAvailability != oldAvailability) { OnAvailabilityChanged(new RunspaceAvailabilityEventArgs(this.RunspaceAvailability)); } }
/// <summary> /// Constructor for state changes not resulting from an error. /// </summary> /// <param name="state">The state of the runspace.</param> internal RunspaceStateInfo(RunspaceState state) : this(state, null) { }
/// <summary> /// Set the current runspace state - no error /// </summary> /// <param name="state">the new state</param> protected void SetRunspaceState(RunspaceState state) { this.SetRunspaceState(state, null); }
internal RunspaceStateInfo(RunspaceState state) : this(state, (Exception)null) { }
internal RunspaceStateInfo(RunspaceState state) : this(state, null) { }
protected void UpdateRunspaceAvailability(RunspaceState runspaceState, bool raiseEvent) { System.Management.Automation.Runspaces.RunspaceAvailability runspaceAvailability = this.RunspaceAvailability; RemoteRunspace runspace = this as RemoteRunspace; ConnectCommandInfo info = (runspace != null) ? runspace.RemoteCommand : null; switch (runspaceAvailability) { case System.Management.Automation.Runspaces.RunspaceAvailability.None: if (runspaceState == RunspaceState.Opened) { this.RunspaceAvailability = ((info == null) && (this.GetCurrentlyRunningPipeline() == null)) ? System.Management.Automation.Runspaces.RunspaceAvailability.Available : System.Management.Automation.Runspaces.RunspaceAvailability.Busy; } break; case System.Management.Automation.Runspaces.RunspaceAvailability.Available: case System.Management.Automation.Runspaces.RunspaceAvailability.AvailableForNestedCommand: case System.Management.Automation.Runspaces.RunspaceAvailability.Busy: switch (runspaceState) { case RunspaceState.Closed: case RunspaceState.Closing: case RunspaceState.Broken: case RunspaceState.Disconnected: this.RunspaceAvailability = System.Management.Automation.Runspaces.RunspaceAvailability.None; goto Label_007D; } break; } Label_007D: if (raiseEvent && (this.RunspaceAvailability != runspaceAvailability)) { this.OnAvailabilityChanged(new RunspaceAvailabilityEventArgs(this.RunspaceAvailability)); } }
internal RunspaceStateInfo(RunspaceStateInfo runspaceStateInfo) { this._state = runspaceStateInfo.State; this._reason = runspaceStateInfo.Reason; }
/// <summary> /// Set the new runspace state. /// </summary> /// <param name="state">the new state</param> /// <param name="reason">An exception indicating the state change is the /// result of an error, otherwise; null. /// </param> /// <returns>Previous runspace state</returns> /// <remarks> /// Sets the internal runspace state information member variable. It also /// adds RunspaceStateInfo to a queue. /// RaiseRunspaceStateEvents raises event for each item in this queue. /// </remarks> private RunspaceState SetRunspaceState(RunspaceState state, Exception reason) { RunspaceState prevState; lock (_syncRoot) { prevState = _runspaceStateInfo.State; if (state != prevState) { _runspaceStateInfo = new RunspaceStateInfo(state, reason); //Add _runspaceStateInfo to _runspaceEventQueue. //RaiseRunspaceStateEvents will raise event for each item //in this queue. //Note:We are doing clone here instead of passing the member //_runspaceStateInfo because we donot want outside //to change our runspace state. RunspaceAvailability previousAvailability = _runspaceAvailability; this.UpdateRunspaceAvailability(_runspaceStateInfo.State, false); _runspaceEventQueue.Enqueue( new RunspaceEventQueueItem( _runspaceStateInfo.Clone(), previousAvailability, _runspaceAvailability)); PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceStateChange, PSOpcode.Open, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, state.ToString()); } } return prevState; }
private void RunspaceStateChanged(object sender, RunspaceStateEventArgs e) { Guid guid = this._instanceId; this._structuredTracer.RunspaceStateChanged(guid.ToString(), e.RunspaceStateInfo.State.ToString(), string.Empty); this._tracer.WriteMessage(string.Concat("PSW Conn: runspace state", e.RunspaceStateInfo.State.ToString())); RunspaceState state = e.RunspaceStateInfo.State; switch (state) { case RunspaceState.Opened: { this.RetryAttempt = 0; this.ReadyForReconnect = false; this.AsyncResult.Connection = this; this.AsyncResult.SetAsCompleted(null); this.RaiseEvents(1); this.RaiseEvents(4); return; } case RunspaceState.Closed: { this.DisposeRunspace(); this.RaiseEvents(2); return; } case RunspaceState.Broken: { if (this.RetryCount <= 0 || this.RetryAttempt >= this.RetryCount) { this.Busy = false; lock (this._syncObject) { if (this.AsyncResult != null) { this.AsyncResult.Connection = null; this.AsyncResult.SetAsCompleted(e.RunspaceStateInfo.Reason); } } object[] computerName = new object[1]; computerName[0] = this._runspace.ConnectionInfo.ComputerName; this._tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "Disposing broken connection to {0}", computerName)); this.DisposeRunspace(); this.RaiseEvents(1); this.RaiseEvents(3); this.RaiseEvents(2); this.RaiseEvents(4); return; } else { Connection retryAttempt = this; retryAttempt.RetryAttempt = retryAttempt.RetryAttempt + 1; Timer timer = new Timer(); timer.AutoReset = false; timer.Enabled = false; timer.Interval = (double)((float)(this._retryInterval * 0x3e8)); Timer timer1 = timer; timer1.Elapsed += new ElapsedEventHandler(this.RetryTimerElapsed); timer1.Start(); return; } } case RunspaceState.Disconnecting: { this.ReadyForDisconnect = false; return; } case RunspaceState.Disconnected: { this.ReadyForReconnect = true; this.RaiseEvents(3); return; } default: { return; } } }
public RunspaceStateEventArg(RunspaceState state) { State = state; }
/// <summary> /// This sample shows how to use the PowerShell Runspace and Pipeline classes to /// start a long running script on a remote server, disconnect from the server /// while the script continues to run, and then reconnect to the server to obtain /// status information on the running script and to retrieve output data. /// </summary> /// <param name="args">This parameter is not used.</param> public static void Main(string[] args) { RunspaceState rsState = RunspaceState.BeforeOpen; PipelineState plState = PipelineState.NotStarted; // Create the connection object that defines a WSMan/WinRM connection. // The default constructor will create a WSMan connection object for // the localhost. WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); // // Scenario 1 // // In this scenario a remote runspace object and a pipeline object are created to // invoke a long running script on the remote (localhost) server. // While the script is running the remoterunspace and pipeline objects are // disconnected. The same remote runspace and pipeline objects are then // *reconnected* here to the (localhost) server to obtain status information and // output data generated by the script. // // Create a remote runspace with the connection information. using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo)) { // Open the remote runspace, which will establish the connection. runspace.Open(); // Create a pipeline object to run a "long running" PowerShell script // that will run for 60 seconds and output data. using (Pipeline pipeline = runspace.CreatePipeline(@"1..60 | foreach {sleep 1; 'Output ' + $_}")) { // Start the script running in a remote session on the localhost. This // is an asynchronous invoke so the call will return immediately while // the script runs in the remote session. pipeline.InvokeAsync(); // Let the script run for a while. Thread.Sleep(2000); // Disconnect the runspace and pipeline objects. The script continues to // run in the remote (localhost) session. runspace.Disconnect(); // Check that the runspace object is disconnected. rsState = runspace.RunspaceStateInfo.State; // Check that the pipeline object is disconnected. plState = pipeline.PipelineStateInfo.State; // Let the script run on the server for a while. Thread.Sleep(2000); // Reconnect the pipeline back to the server asynchronously. This call will return // immediately and the status of the running script can be checked. Note that the // associated runspace object is also reconnected implicitly. pipeline.ConnectAsync(); // Allow time for connection operation to complete. Thread.Sleep(2000); // Check that the runspace object is reconnected (Opened state). rsState = runspace.RunspaceStateInfo.State; // Check that the pipeline object is reconnected and running. plState = pipeline.PipelineStateInfo.State; // Get all available output from the pipeline, and continue getting output data // until the pipeline running script completes. while (!pipeline.Output.EndOfPipeline) { pipeline.Output.WaitHandle.WaitOne(); while (pipeline.Output.Count > 0) { PSObject psObject = pipeline.Output.Read(); // Write output object data. Console.WriteLine(psObject.ToString()); } } } } // // Scenario 2 // // In this scenario a new pipeline object is created on the runspace and the // same long running script is invoked. Again the remote runspace and pipeline // objects are disconnected while the script runs on the localhost. // This time we will dispose the remote runspace and pipeline objects while they // are in the disconnected state. The remote runspace and pipeline objects are // then *reconstructed* based on information from the localhost remote session. // The remote runspace and pipeline objects are connected to the server to obtain // status information and output data from the running command. // Guid runspaceInstanceId; // Create a remote runspace with the connection information. using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo)) { // Open the remote runspace, which will establish the connection. runspace.Open(); // Save the runspace instance Id for later referral. runspaceInstanceId = runspace.InstanceId; // Create a script pipeline. using (Pipeline pipeline = runspace.CreatePipeline(@"1..60 | foreach {sleep 1; 'Output ' + $_}")) { // Start the script running on the (localhost) server. pipeline.InvokeAsync(); // Let the script run for a while. Thread.Sleep(2000); // Disconnect the remote runspace and pipeline objects. The script continues to // run on the (localhost) server. runspace.Disconnect(); // Check that the runspace object is disconnected. rsState = runspace.RunspaceStateInfo.State; // Check that the pipeline object is disconnected. plState = pipeline.PipelineStateInfo.State; // Let the script run on the server for a while. Thread.Sleep(2000); } } // Both the runspace and pipeline objects are disconnected from this PowerShell // client but still running in the remote session. We can reconstruct new // client runspace and pipeline objects from the original runspace instance Id, // which uniquely identifies the disconnected session running on the localhost. // Query the localhost server for runspaces with running script/commands. Runspace runspace1 = null; Runspace[] runspaces = Runspace.GetRunspaces(connectionInfo); foreach (Runspace rs in runspaces) { if (rs.InstanceId == runspaceInstanceId) { runspace1 = rs; break; } } if (runspace1 != null) { // This is a new runspace object in the Disconnected state that contains information // about the script running in this runspace on the remote session. using (runspace1) { // Create a new pipeline object for the script running on the server in this runspace. // The pipeline object is created in a disconnected state. using (Pipeline pipeline = runspace1.CreateDisconnectedPipeline()) { // Check the state of the pipeline. plState = pipeline.PipelineStateInfo.State; // Connect the pipeline object asynchronously. // Note that this method also connects the runspace implicitly. pipeline.ConnectAsync(); // Allow time for connection operation to complete. Thread.Sleep(2000); // Check that the runspace is connected and in the Opened state. rsState = runspace1.RunspaceStateInfo.State; // Check that the pipeline object is reconnected and running. plState = pipeline.PipelineStateInfo.State; // Get all available output from the pipeline, and continue getting output data // until the pipeline script completes. while (!pipeline.Output.EndOfPipeline) { pipeline.Output.WaitHandle.WaitOne(); while (pipeline.Output.Count > 0) { PSObject psObject = pipeline.Output.Read(); // Write output object data. Console.WriteLine(psObject.ToString()); } } } } } }
internal RunspaceStateInfo(RunspaceStateInfo runspaceStateInfo) { this._state = runspaceStateInfo.State; this._reason = runspaceStateInfo.Reason; }
internal RunspaceStateInfo(RunspaceState state, Exception reason) { this._state = state; this._reason = reason; }
internal RunspaceStateInfo(RunspaceState state, Exception reason) { this._state = state; this._reason = reason; }
/// <summary> /// Set the new runspace state. /// </summary> /// <param name="state">the new state</param> /// <param name="reason">An exception indicating the state change is the /// result of an error, otherwise; null. /// </param> /// <remarks> /// Sets the internal runspace state information member variable. It also /// adds RunspaceStateInfo to a queue. /// RaiseRunspaceStateEvents raises event for each item in this queue. /// </remarks> protected void SetRunspaceState(RunspaceState state, Exception reason) { lock (SyncRoot) { if (state != RunspaceState) { _runspaceStateInfo = new RunspaceStateInfo(state, reason); //Add _runspaceStateInfo to _runspaceEventQueue. //RaiseRunspaceStateEvents will raise event for each item //in this queue. //Note:We are doing clone here instead of passing the member //_runspaceStateInfo because we donot want outside //to change our runspace state. RunspaceAvailability previousAvailability = _runspaceAvailability; this.UpdateRunspaceAvailability(_runspaceStateInfo.State, false); _runspaceEventQueue.Enqueue( new RunspaceEventQueueItem( _runspaceStateInfo.Clone(), previousAvailability, _runspaceAvailability)); } } }
private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs stateEventArgs) { ErrorRecord errorRecord; PSRemotingTransportException exception2; string str; if (sender == null) { throw PSTraceSource.NewArgumentNullException("sender"); } if (stateEventArgs == null) { throw PSTraceSource.NewArgumentNullException("stateEventArgs"); } RunspaceStateEventArgs baseEvent = stateEventArgs.BaseEvent as RunspaceStateEventArgs; RunspaceState state = baseEvent.RunspaceStateInfo.State; OpenRunspaceOperation operation = sender as OpenRunspaceOperation; RemoteRunspace operatedRunspace = operation.OperatedRunspace; if (operatedRunspace != null) { operatedRunspace.URIRedirectionReported -= new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported); } PipelineWriter objectWriter = this.stream.ObjectWriter; Exception reason = baseEvent.RunspaceStateInfo.Reason; switch (state) { case RunspaceState.Opened: { PSSession remoteRunspaceInfo = new PSSession(operatedRunspace); base.RunspaceRepository.Add(remoteRunspaceInfo); Action <Cmdlet> action = cmdlet => cmdlet.WriteObject(remoteRunspaceInfo); if (objectWriter.IsOpen) { objectWriter.Write(action); } return; } case RunspaceState.Closed: { Uri uri = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <Uri>(operatedRunspace.ConnectionInfo, "ConnectionUri", null); string message = base.GetMessage(RemotingErrorIdStrings.RemoteRunspaceClosed, new object[] { (uri != null) ? uri.AbsoluteUri : string.Empty }); Action <Cmdlet> action3 = cmdlet => cmdlet.WriteVerbose(message); if (objectWriter.IsOpen) { objectWriter.Write(action3); } if (reason != null) { ErrorRecord errorRecord2 = new ErrorRecord(reason, "PSSessionStateClosed", ErrorCategory.OpenError, operatedRunspace); Action <Cmdlet> action4 = cmdlet => cmdlet.WriteError(errorRecord2); if (objectWriter.IsOpen) { objectWriter.Write(action4); } } return; } case RunspaceState.Closing: return; case RunspaceState.Broken: exception2 = reason as PSRemotingTransportException; str = null; if (exception2 != null) { OpenRunspaceOperation operation2 = sender as OpenRunspaceOperation; if (operation2 != null) { string computerName = operation2.OperatedRunspace.ConnectionInfo.ComputerName; if (exception2.ErrorCode != -2144108135) { str = "[" + computerName + "] "; if (!string.IsNullOrEmpty(exception2.Message)) { str = str + exception2.Message; } else if (!string.IsNullOrEmpty(exception2.TransportMessage)) { str = str + exception2.TransportMessage; } break; } string str3 = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.URIRedirectionReported, new object[] { exception2.Message, "MaximumConnectionRedirectionCount", "PSSessionOption", "AllowRedirection" }); str = "[" + computerName + "] " + str3; } } break; default: return; } PSRemotingDataStructureException exception3 = reason as PSRemotingDataStructureException; if (exception3 != null) { OpenRunspaceOperation operation3 = sender as OpenRunspaceOperation; if (operation3 != null) { string str4 = operation3.OperatedRunspace.ConnectionInfo.ComputerName; str = "[" + str4 + "] " + exception3.Message; } } if (reason == null) { reason = new RuntimeException(base.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, new object[] { state })); } string fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError((exception2 != null) ? exception2.ErrorCode : 0, this._defaultFQEID); errorRecord = new ErrorRecord(reason, operatedRunspace, fQEIDFromTransportError, ErrorCategory.OpenError, null, null, null, null, null, str, null); Action <Cmdlet> action2 = cmdlet => cmdlet.WriteError(errorRecord); if (objectWriter.IsOpen) { objectWriter.Write(action2); } this.toDispose.Add(operatedRunspace); }
private void SetRunspaceState(RunspaceState state, Exception reason) { lock (this._syncRoot) { if (state != this._runspaceStateInfo.State) { this._runspaceStateInfo = new System.Management.Automation.Runspaces.RunspaceStateInfo(state, reason); System.Management.Automation.Runspaces.RunspaceAvailability currentAvailability = this._runspaceAvailability; base.UpdateRunspaceAvailability(this._runspaceStateInfo.State, false); this._runspaceEventQueue.Enqueue(new RunspaceEventQueueItem(this._runspaceStateInfo.Clone(), currentAvailability, this._runspaceAvailability)); PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceStateChange, PSOpcode.Open, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, new object[] { state.ToString() }); } } }