// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation.Host;
using System.Management.Automation.Remoting;
using System.Management.Automation.Remoting.Client;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Runspaces.Internal;
using System.Management.Automation.Tracing;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Internal
{
///
/// Handles all PowerShell data structure handler communication with the
/// server side RunspacePool.
///
internal sealed class ClientRunspacePoolDataStructureHandler : IDisposable
{
private bool _reconnecting = false;
#region Constructors
///
/// Constructor which takes a client runspace pool and creates
/// an associated ClientRunspacePoolDataStructureHandler.
///
/// Client runspace pool object.
/// Typetable to use for serialization/deserialization.
internal ClientRunspacePoolDataStructureHandler(RemoteRunspacePoolInternal clientRunspacePool,
TypeTable typeTable)
{
_clientRunspacePoolId = clientRunspacePool.InstanceId;
_minRunspaces = clientRunspacePool.GetMinRunspaces();
_maxRunspaces = clientRunspacePool.GetMaxRunspaces();
_host = clientRunspacePool.Host;
_applicationArguments = clientRunspacePool.ApplicationArguments;
RemoteSession = CreateClientRemoteSession(clientRunspacePool);
// TODO: Assign remote session name.. should be passed from clientRunspacePool
_transportManager = RemoteSession.SessionDataStructureHandler.TransportManager;
_transportManager.TypeTable = typeTable;
RemoteSession.StateChanged += HandleClientRemoteSessionStateChanged;
_reconnecting = false;
_transportManager.RobustConnectionNotification += HandleRobustConnectionNotification;
_transportManager.CreateCompleted += HandleSessionCreateCompleted;
}
#endregion Constructors
#region Data Structure Handler Methods
///
/// Create a runspace pool asynchronously (and opens) it
/// on the server.
///
internal void CreateRunspacePoolAndOpenAsync()
{
// #1: Connect to remote session
Dbg.Assert(RemoteSession.SessionDataStructureHandler.StateMachine.State == RemoteSessionState.Idle,
"State of ClientRemoteSession is expected to be idle before connection is established");
RemoteSession.CreateAsync();
// #2: send the message for runspace pool creation
// this is done in HandleClientRemoteSessionStateChanged
}
///
/// Closes the server runspace pool asynchronously.
///
internal void CloseRunspacePoolAsync()
{
RemoteSession.CloseAsync();
}
///
/// Suspends connection to a runspace pool asynchronously.
///
internal void DisconnectPoolAsync()
{
// Prepare running commands for disconnect and start disconnect
// when ready.
PrepareForAndStartDisconnect();
}
///
/// Restore connection to a runspace pool asynchronously.
///
internal void ReconnectPoolAsync()
{
// TODO: Integrate this into state machine
_reconnecting = true;
PrepareForConnect();
RemoteSession.ReconnectAsync();
}
///
/// Creates a connection to an existing remote runspace pool.
///
internal void ConnectPoolAsync()
{
PrepareForConnect();
RemoteSession.ConnectAsync();
}
///
/// Process the data received from the runspace pool
/// on the server.
///
/// Data received.
internal void ProcessReceivedData(RemoteDataObject receivedData)
{
// verify if this data structure handler is the intended recipient
if (receivedData.RunspacePoolId != _clientRunspacePoolId)
{
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceIdsDoNotMatch,
receivedData.RunspacePoolId, _clientRunspacePoolId);
}
// take appropriate action based on the action type
Dbg.Assert(receivedData.TargetInterface == RemotingTargetInterface.RunspacePool,
"Target interface is expected to be RunspacePool");
switch (receivedData.DataType)
{
case RemotingDataType.RemoteHostCallUsingRunspaceHost:
{
Dbg.Assert(RemoteHostCallReceived != null,
"RemoteRunspacePoolInternal should subscribe to all data structure handler events");
RemoteHostCall remoteHostCall = RemoteHostCall.Decode(receivedData.Data);
RemoteHostCallReceived.SafeInvoke(this, new RemoteDataEventArgs(remoteHostCall));
}
break;
case RemotingDataType.RunspacePoolInitData:
{
RunspacePoolInitInfo initInfo = RemotingDecoder.GetRunspacePoolInitInfo(receivedData.Data);
Dbg.Assert(RSPoolInitInfoReceived != null,
"RemoteRunspacePoolInternal should subscribe to all data structure handler events");
RSPoolInitInfoReceived.SafeInvoke(this,
new RemoteDataEventArgs(initInfo));
}
break;
case RemotingDataType.RunspacePoolStateInfo:
{
RunspacePoolStateInfo stateInfo =
RemotingDecoder.GetRunspacePoolStateInfo(receivedData.Data);
Dbg.Assert(StateInfoReceived != null,
"RemoteRunspacePoolInternal should subscribe to all data structure handler events");
StateInfoReceived.SafeInvoke(this,
new RemoteDataEventArgs(stateInfo));
NotifyAssociatedPowerShells(stateInfo);
}
break;
case RemotingDataType.ApplicationPrivateData:
{
PSPrimitiveDictionary applicationPrivateData = RemotingDecoder.GetApplicationPrivateData(receivedData.Data);
Dbg.Assert(ApplicationPrivateDataReceived != null,
"RemoteRunspacePoolInternal should subscribe to all data structure handler events");
ApplicationPrivateDataReceived.SafeInvoke(this,
new RemoteDataEventArgs(applicationPrivateData));
}
break;
case RemotingDataType.RunspacePoolOperationResponse:
{
Dbg.Assert(SetMaxMinRunspacesResponseReceived != null,
"RemoteRunspacePoolInternal should subscribe to all data structure handler events");
SetMaxMinRunspacesResponseReceived.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data));
}
break;
case RemotingDataType.PSEventArgs:
{
PSEventArgs psEventArgs = RemotingDecoder.GetPSEventArgs(receivedData.Data);
Dbg.Assert(PSEventArgsReceived != null,
"RemoteRunspacePoolInternal should subscribe to all data structure handler events");
PSEventArgsReceived.SafeInvoke(this, new RemoteDataEventArgs(psEventArgs));
}
break;
}
}
///
/// Creates a PowerShell data structure handler instance associated
/// with this runspace pool data structure handler.
///
/// Associated powershell.
/// PowerShell data structure handler object.
internal ClientPowerShellDataStructureHandler CreatePowerShellDataStructureHandler(
ClientRemotePowerShell shell)
{
BaseClientCommandTransportManager clientTransportMgr =
RemoteSession.SessionDataStructureHandler.CreateClientCommandTransportManager(shell, shell.NoInput);
return new ClientPowerShellDataStructureHandler(
clientTransportMgr, _clientRunspacePoolId, shell.InstanceId);
}
///
/// Creates a PowerShell instances on the server, associates it
/// with this runspace pool and invokes.
///
/// The client remote powershell.
internal void CreatePowerShellOnServerAndInvoke(ClientRemotePowerShell shell)
{
// add to associated powershell list and send request to server
lock (_associationSyncObject)
{
_associatedPowerShellDSHandlers.Add(shell.InstanceId, shell.DataStructureHandler);
}
shell.DataStructureHandler.RemoveAssociation += HandleRemoveAssociation;
// Find out if this is an invoke and disconnect operation and if so whether the endpoint
// supports disconnect. Throw exception if disconnect is not supported.
bool invokeAndDisconnect = shell.Settings != null && shell.Settings.InvokeAndDisconnect;
if (invokeAndDisconnect && !EndpointSupportsDisconnect)
{
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.EndpointDoesNotSupportDisconnect);
}
if (RemoteSession == null)
{
throw new ObjectDisposedException("ClientRunspacePoolDataStructureHandler");
}
shell.DataStructureHandler.Start(RemoteSession.SessionDataStructureHandler.StateMachine, invokeAndDisconnect);
}
///
/// Add a ClientPowerShellDataStructureHandler to association list.
///
/// PowerShell Instance Id.
/// ClientPowerShellDataStructureHandler for PowerShell.
internal void AddRemotePowerShellDSHandler(Guid psShellInstanceId, ClientPowerShellDataStructureHandler psDSHandler)
{
lock (_associationSyncObject)
{
// Remove old DSHandler and replace with new.
_associatedPowerShellDSHandlers[psShellInstanceId] = psDSHandler;
}
psDSHandler.RemoveAssociation += HandleRemoveAssociation;
}
///
/// Dispatch the message to the associated powershell data structure handler.
///
/// Message received.
internal void DispatchMessageToPowerShell(RemoteDataObject rcvdData)
{
ClientPowerShellDataStructureHandler dsHandler =
GetAssociatedPowerShellDataStructureHandler(rcvdData.PowerShellId);
// if a data structure handler does not exist it means
// the association has been removed -
// discard messages
dsHandler?.ProcessReceivedData(rcvdData);
}
///
/// Send the host response to the server.
///
/// Host response object to send.
internal void SendHostResponseToServer(RemoteHostResponse hostResponse)
{
SendDataAsync(hostResponse.Encode(), DataPriorityType.PromptResponse);
}
///
/// Send a message to the server instructing it to reset its runspace state.
///
/// Caller Id.
internal void SendResetRunspaceStateToServer(long callId)
{
RemoteDataObject message =
RemotingEncoder.GenerateResetRunspaceState(_clientRunspacePoolId, callId);
SendDataAsync(message);
}
///
/// Sent a message to modify the max runspaces of the runspace pool.
///
/// New maxrunspaces to set.
/// call id on which the calling method will
/// be blocked on
internal void SendSetMaxRunspacesToServer(int maxRunspaces, long callId)
{
RemoteDataObject message =
RemotingEncoder.GenerateSetMaxRunspaces(_clientRunspacePoolId, maxRunspaces, callId);
SendDataAsync(message);
}
///
/// Send a message to modify the min runspaces of the runspace pool.
///
/// New minrunspaces to set.
/// call id on which the calling method will
/// be blocked on
internal void SendSetMinRunspacesToServer(int minRunspaces, long callId)
{
RemoteDataObject message =
RemotingEncoder.GenerateSetMinRunspaces(_clientRunspacePoolId, minRunspaces, callId);
SendDataAsync(message);
}
///
/// Send a message to get the available runspaces from the server.
///
/// call id on which the calling method will
/// be blocked on
internal void SendGetAvailableRunspacesToServer(long callId)
{
SendDataAsync(RemotingEncoder.GenerateGetAvailableRunspaces(_clientRunspacePoolId, callId));
}
#endregion Data Structure Handler Methods
#region Data Structure Handler events
///
/// Event raised when a host call is received.
///
internal event EventHandler> RemoteHostCallReceived;
///
/// Event raised when state information is received.
///
internal event EventHandler> StateInfoReceived;
///
/// Event raised when RunspacePoolInitInfo is received. This is the first runspace pool message expected
/// after connecting to an existing remote runspace pool. RemoteRunspacePoolInternal should use this
/// notification to set the state of a reconstructed runspace to "Opened State" and use the
/// minRunspace and MaxRunspaces information to set its state.
///
internal event EventHandler> RSPoolInitInfoReceived;
///
/// Event raised when application private data is received.
///
internal event EventHandler> ApplicationPrivateDataReceived;
///
/// Event raised when a PSEventArgs is received.
///
internal event EventHandler> PSEventArgsReceived;
///
/// Event raised when the session is closed.
///
internal event EventHandler> SessionClosed;
///
///
internal event EventHandler> SessionDisconnected;
///
///
internal event EventHandler> SessionReconnected;
///
/// Event raised when the session is closing.
///
internal event EventHandler> SessionClosing;
///
/// Event raised when a response to a SetMaxRunspaces or SetMinRunspaces call
/// is received.
///
internal event EventHandler> SetMaxMinRunspacesResponseReceived;
///
/// EventHandler used to report connection URI redirections to the application.
///
internal event EventHandler> URIRedirectionReported;
///
/// Indicates that a disconnect has been initiated by the WinRM robust connections layer.
///
internal event EventHandler> SessionRCDisconnecting;
///
/// Notification that session creation has completed.
///
internal event EventHandler SessionCreateCompleted;
#endregion Data Structure Handler events
#region Private Methods
///
/// Send the data specified as a RemoteDataObject asynchronously
/// to the runspace pool on the remote session.
///
/// Data to send.
/// This overload takes a RemoteDataObject and should be
/// the one used within the code
private void SendDataAsync(RemoteDataObject data)
{
_transportManager.DataToBeSentCollection.Add