File size: 18,174 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Management.Automation.Host;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// Execution context used for stepping.
/// </summary>
internal sealed class ExecutionContextForStepping : IDisposable
{
private readonly ExecutionContext _executionContext;
private PSInformationalBuffers _originalInformationalBuffers;
private PSHost _originalHost;
private ExecutionContextForStepping(ExecutionContext ctxt)
{
Dbg.Assert(ctxt != null, "ExecutionContext cannot be null.");
_executionContext = ctxt;
}
internal static ExecutionContextForStepping PrepareExecutionContext(
ExecutionContext ctxt,
PSInformationalBuffers newBuffers,
PSHost newHost)
{
ExecutionContextForStepping result = new ExecutionContextForStepping(ctxt);
result._originalInformationalBuffers
= ctxt.InternalHost.InternalUI.GetInformationalMessageBuffers();
result._originalHost = ctxt.InternalHost.ExternalHost;
ctxt.InternalHost.InternalUI.SetInformationalMessageBuffers(newBuffers);
ctxt.InternalHost.SetHostRef(newHost);
return result;
}
// Summary:
// Performs application-defined tasks associated with freeing, releasing, or
// resetting unmanaged resources.
void IDisposable.Dispose()
{
_executionContext.InternalHost.InternalUI.SetInformationalMessageBuffers(_originalInformationalBuffers);
_executionContext.InternalHost.SetHostRef(_originalHost);
GC.SuppressFinalize(this);
}
}
/// <summary>
/// This class wraps a RunspacePoolInternal object. It is used to function
/// as a server side runspacepool.
/// </summary>
internal class ServerSteppablePipelineDriver
{
#region Private Data
// that is associated with this
// powershell driver
// associated with this powershell
// data structure handler object to handle all
// communications with the client
// private bool datasent = false; // if the remaining data has been sent
// to the client before sending state
// information
// data to client
// was created
private readonly bool _addToHistory;
// associated with this powershell
private readonly ApartmentState apartmentState; // apartment state for this powershell
// pipeline that runs the actual command.
private readonly ServerSteppablePipelineSubscriber _eventSubscriber;
private readonly PSDataCollection<object> _powershellInput; // input collection of the PowerShell pipeline
#endregion
/// <summary>
/// Default constructor for creating ServerSteppablePipelineDriver...Used by server to concurrently
/// run 2 pipelines.
/// </summary>
/// <param name="powershell">Decoded powershell object.</param>
/// <param name="noInput">Whether there is input for this powershell.</param>
/// <param name="clientPowerShellId">The client powershell id.</param>
/// <param name="clientRunspacePoolId">The client runspacepool id.</param>
/// <param name="runspacePoolDriver">runspace pool driver
/// which is creating this powershell driver</param>
/// <param name="apartmentState">Apartment state for this powershell.</param>
/// <param name="hostInfo">host info using which the host for
/// this powershell will be constructed</param>
/// <param name="streamOptions">Serialization options for the streams in this powershell.</param>
/// <param name="addToHistory">
/// true if the command is to be added to history list of the runspace. false, otherwise.
/// </param>
/// <param name="rsToUse">
/// If not null, this Runspace will be used to invoke Powershell.
/// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used.
/// </param>
/// <param name="eventSubscriber">
/// Steppable pipeline event subscriber
/// </param>
/// <param name="powershellInput">Input collection of the PowerShell pipeline.</param>
internal ServerSteppablePipelineDriver(PowerShell powershell, bool noInput, Guid clientPowerShellId,
Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions,
bool addToHistory, Runspace rsToUse, ServerSteppablePipelineSubscriber eventSubscriber, PSDataCollection<object> powershellInput)
{
LocalPowerShell = powershell;
InstanceId = clientPowerShellId;
RunspacePoolId = clientRunspacePoolId;
RemoteStreamOptions = streamOptions;
this.apartmentState = apartmentState;
NoInput = noInput;
_addToHistory = addToHistory;
_eventSubscriber = eventSubscriber;
_powershellInput = powershellInput;
Input = new PSDataCollection<object>();
InputEnumerator = Input.GetEnumerator();
Input.ReleaseOnEnumeration = true;
DataStructureHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, RemoteStreamOptions, null);
RemoteHost = DataStructureHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost);
// subscribe to various data structure handler events
DataStructureHandler.InputEndReceived += HandleInputEndReceived;
DataStructureHandler.InputReceived += HandleInputReceived;
DataStructureHandler.StopPowerShellReceived += HandleStopReceived;
DataStructureHandler.HostResponseReceived += HandleHostResponseReceived;
DataStructureHandler.OnSessionConnected += HandleSessionConnected;
if (rsToUse == null)
{
throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NestedPipelineMissingRunspace);
}
// else, set the runspace pool and invoke this powershell
LocalPowerShell.Runspace = rsToUse;
eventSubscriber.SubscribeEvents(this);
PipelineState = PSInvocationState.NotStarted;
}
#region Internal Methods
/// <summary>
/// Local PowerShell instance.
/// </summary>
internal PowerShell LocalPowerShell { get; }
/// <summary>
/// Instance id by which this powershell driver is
/// identified. This is the same as the id of the
/// powershell on the client side.
/// </summary>
internal Guid InstanceId { get; }
/// <summary>
/// Server remote host.
/// </summary>
internal ServerRemoteHost RemoteHost { get; }
/// <summary>
/// Serialization options for the streams in this powershell.
/// </summary>
internal RemoteStreamOptions RemoteStreamOptions { get; }
/// <summary>
/// Id of the runspace pool driver which created
/// this object. This is the same as the id of
/// the runspace pool at the client side which
/// is associated with the powershell on the
/// client side.
/// </summary>
internal Guid RunspacePoolId { get; }
/// <summary>
/// ServerPowerShellDataStructureHandler associated with this
/// powershell driver.
/// </summary>
internal ServerPowerShellDataStructureHandler DataStructureHandler { get; }
/// <summary>
/// Pipeline invocation state.
/// </summary>
internal PSInvocationState PipelineState { get; private set; }
/// <summary>
/// Checks if the steppable pipeline has input.
/// </summary>
internal bool NoInput { get; }
/// <summary>
/// Steppablepipeline object.
/// </summary>
internal SteppablePipeline SteppablePipeline { get; set; }
/// <summary>
/// Synchronization object.
/// </summary>
internal object SyncObject { get; } = new object();
/// <summary>
/// Processing input.
/// </summary>
internal bool ProcessingInput { get; set; }
/// <summary>
/// Input enumerator.
/// </summary>
internal IEnumerator<object> InputEnumerator { get; }
/// <summary>
/// Input collection.
/// </summary>
internal PSDataCollection<object> Input { get; }
/// <summary>
/// Is the pipeline pulsed.
/// </summary>
internal bool Pulsed { get; set; }
/// <summary>
/// Total objects processed.
/// </summary>
internal int TotalObjectsProcessed { get; set; }
/// <summary>
/// Starts the exectution.
/// </summary>
internal void Start()
{
PipelineState = PSInvocationState.Running;
_eventSubscriber.FireStartSteppablePipeline(this);
_powershellInput?.Pulse();
}
#endregion Internal Methods
#region DataStructure related event handling / processing
/// <summary>
/// Close the input collection of the local powershell.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">Arguments describing this event.</param>
internal void HandleInputEndReceived(object sender, EventArgs eventArgs)
{
Input.Complete();
CheckAndPulseForProcessing(true);
_powershellInput?.Pulse();
}
private void HandleSessionConnected(object sender, EventArgs eventArgs)
{
// Close input if its active. no need to synchronize as input stream would have already been processed
// when connect call came into PS plugin
Input?.Complete();
}
/// <summary>
/// Handle a host message response received.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">Arguments describing this event.</param>
internal void HandleHostResponseReceived(object sender, RemoteDataEventArgs<RemoteHostResponse> eventArgs)
{
RemoteHost.ServerMethodExecutor.HandleRemoteHostResponseFromClient(eventArgs.Data);
}
/// <summary>
/// Stop the local powershell.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">Unused.</param>
private void HandleStopReceived(object sender, EventArgs eventArgs)
{
lock (SyncObject)
{
PipelineState = PSInvocationState.Stopping;
}
PerformStop();
_powershellInput?.Pulse();
}
/// <summary>
/// Add input to the local powershell's input collection.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">Arguments describing this event.</param>
private void HandleInputReceived(object sender, RemoteDataEventArgs<object> eventArgs)
{
Dbg.Assert(!NoInput, "Input data should not be received for powershells created with no input");
if (Input != null)
{
lock (SyncObject)
{
Input.Add(eventArgs.Data);
}
CheckAndPulseForProcessing(false);
_powershellInput?.Pulse();
}
}
/// <summary>
/// Checks if there is any pending input that needs processing. If so, triggers RunProcessRecord
/// event. The pipeline execution thread catches this and calls us back when the pipeline is
/// suspended.
/// </summary>
/// <param name="complete"></param>
internal void CheckAndPulseForProcessing(bool complete)
{
if (complete)
{
_eventSubscriber.FireHandleProcessRecord(this);
}
else if (!Pulsed)
{
bool shouldPulse = false;
lock (SyncObject)
{
if (Pulsed)
{
return;
}
if (!ProcessingInput && ((Input.Count > TotalObjectsProcessed)))
{
shouldPulse = true;
Pulsed = true;
}
}
if (shouldPulse && (PipelineState == PSInvocationState.Running))
{
_eventSubscriber.FireHandleProcessRecord(this);
}
}
}
/// <summary>
/// Performs the stop operation.
/// </summary>
internal void PerformStop()
{
bool shouldPerformStop = false;
lock (SyncObject)
{
if (!ProcessingInput && (PipelineState == PSInvocationState.Stopping))
{
shouldPerformStop = true;
}
}
if (shouldPerformStop)
{
SetState(PSInvocationState.Stopped, new PipelineStoppedException());
}
}
/// <summary>
/// Changes state and sends message to the client as needed.
/// </summary>
/// <param name="newState"></param>
/// <param name="reason"></param>
internal void SetState(PSInvocationState newState, Exception reason)
{
PSInvocationState copyState = PSInvocationState.NotStarted;
bool shouldRaiseEvents = false;
lock (SyncObject)
{
switch (PipelineState)
{
case PSInvocationState.NotStarted:
{
switch (newState)
{
case PSInvocationState.Running:
case PSInvocationState.Stopping:
case PSInvocationState.Completed:
case PSInvocationState.Stopped:
case PSInvocationState.Failed:
copyState = newState;
// NotStarted -> Running..we dont send
// state back to client.
break;
}
}
break;
case PSInvocationState.Running:
{
switch (newState)
{
case PSInvocationState.NotStarted:
throw new InvalidOperationException();
case PSInvocationState.Running:
break;
case PSInvocationState.Stopping:
copyState = newState;
break;
case PSInvocationState.Completed:
case PSInvocationState.Stopped:
case PSInvocationState.Failed:
copyState = newState;
shouldRaiseEvents = true;
break;
}
}
break;
case PSInvocationState.Stopping:
{
switch (newState)
{
case PSInvocationState.Completed:
case PSInvocationState.Failed:
copyState = PSInvocationState.Stopped;
shouldRaiseEvents = true;
break;
case PSInvocationState.Stopped:
copyState = newState;
shouldRaiseEvents = true;
break;
default:
throw new InvalidOperationException();
}
}
break;
case PSInvocationState.Stopped:
case PSInvocationState.Completed:
case PSInvocationState.Failed:
break;
}
PipelineState = copyState;
}
if (shouldRaiseEvents)
{
// send the state change notification to the client
DataStructureHandler.SendStateChangedInformationToClient(
new PSInvocationStateInfo(copyState, reason));
}
if (PipelineState == PSInvocationState.Completed
|| PipelineState == PSInvocationState.Stopped
|| PipelineState == PSInvocationState.Failed)
{
// Remove itself from the runspace pool
DataStructureHandler.RaiseRemoveAssociationEvent();
}
}
#endregion
}
}
|