forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremoterunspace.cs
More file actions
3042 lines (2675 loc) · 112 KB
/
Copy pathremoterunspace.cs
File metadata and controls
3042 lines (2675 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Management.Automation.Runspaces;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Tracing;
using Dbg = System.Management.Automation.Diagnostics;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation.Remoting;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Microsoft.PowerShell.Commands;
using System.Security.Principal;
using System.Management.Automation.Runspaces.Internal;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
namespace System.Management.Automation
{
/// <summary>
/// Remote runspace which will be created on the client side. This
/// runspace is wrapped on a RunspacePool(1).
/// </summary>
internal class RemoteRunspace : Runspace, IDisposable
{
#region Private Members
private ArrayList _runningPipelines = new ArrayList();
private object _syncRoot = new object();
private RunspaceStateInfo _runspaceStateInfo = new RunspaceStateInfo(RunspaceState.BeforeOpen);
private bool _bSessionStateProxyCallInProgress = false;
private RunspaceConnectionInfo _connectionInfo;
private RemoteDebugger _remoteDebugger;
private PSPrimitiveDictionary _applicationPrivateData;
private bool _disposed = false;
// the following two variables have been added for supporting
// the Invoke-Command | Invoke-Command scenario
private InvokeCommandCommand _currentInvokeCommand = null;
private long _currentLocalPipelineId = 0;
/// <summary>
/// This is queue of all the state change event which have occured for
/// this runspace. RaiseRunspaceStateEvents raises event for each
/// item in this queue. We don't raise events from with SetRunspaceState
/// because SetRunspaceState is often called from with in the a lock.
/// Raising event with in a lock introduces chances of deadlock in GUI
/// applications.
/// </summary>
private Queue<RunspaceEventQueueItem> _runspaceEventQueue = new Queue<RunspaceEventQueueItem>();
protected class RunspaceEventQueueItem
{
public RunspaceEventQueueItem(RunspaceStateInfo runspaceStateInfo, RunspaceAvailability currentAvailability, RunspaceAvailability newAvailability)
{
this.RunspaceStateInfo = runspaceStateInfo;
this.CurrentRunspaceAvailability = currentAvailability;
this.NewRunspaceAvailability = newAvailability;
}
public RunspaceStateInfo RunspaceStateInfo;
public RunspaceAvailability CurrentRunspaceAvailability;
public RunspaceAvailability NewRunspaceAvailability;
}
/// <summary>
/// In RemoteRunspace, it is required to invoke pipeline
/// as part of open call (i.e. while state is Opening).
/// If this property is true, runspace state check is
/// not performed in AddToRunningPipelineList call.
/// </summary>
private bool _bypassRunspaceStateCheck;
/// <summary>
/// In RemoteRunspace, it is required to invoke pipeline
/// as part of open call (i.e. while state is Opening).
/// If this property is true, runspace state check is
/// not performed in AddToRunningPipelineList call.
/// </summary>
protected bool ByPassRunspaceStateCheck
{
get
{
return _bypassRunspaceStateCheck;
}
set
{
_bypassRunspaceStateCheck = value;
}
}
/// <summary>
/// Temporary place to remember whether to close this runspace on pop or not.
/// Used by Start-PSSession.
/// </summary>
internal bool ShouldCloseOnPop { get; set; } = false;
#endregion Private Members
#region Constructors
/// <summary>
/// Construct a remote runspace based on the connection information
/// and the specified host
/// </summary>
/// <param name="typeTable">
/// The TypeTable to use while deserializing/serializing remote objects.
/// TypeTable has the following information used by serializer:
/// 1. SerializationMethod
/// 2. SerailizationDepth
/// 3. SpecificSerializationProperties
/// TypeTable has the following inforamtion used by deserializer:
/// 1. TargetTypeForDeserializaiton
/// 2. TypeConverter
/// </param>
/// <param name="connectionInfo">connection information which identifies
/// the remote computer</param>
/// <param name="host">host on the client</param>
/// <param name="applicationArguments">
/// <param name="name">Friendly name for remote runspace session.</param>
/// <param name="id">Id for remote runspace.</param>
/// Application arguments the server can see in <see cref="System.Management.Automation.Remoting.PSSenderInfo.ApplicationArguments"/>
/// </param>
internal RemoteRunspace(TypeTable typeTable, RunspaceConnectionInfo connectionInfo, PSHost host, PSPrimitiveDictionary applicationArguments, string name = null, int id = -1)
{
PSEtwLog.SetActivityIdForCurrentThread(this.InstanceId);
PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor,
PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational,
InstanceId.ToString());
_connectionInfo = connectionInfo.InternalCopy();
OriginalConnectionInfo = connectionInfo.InternalCopy();
RunspacePool = new RunspacePool(1, 1, typeTable, host, applicationArguments, connectionInfo, name);
this.PSSessionId = id;
SetEventHandlers();
}
/// <summary>
/// Constructs a RemoteRunspace object based on the passed in RunspacePool object,
/// with a starting state of Disconnected.
/// </summary>
/// <param name="runspacePool"></param>
internal RemoteRunspace(RunspacePool runspacePool)
{
// The RemoteRunspace object can only be constructed this way with a RunspacePool that
// is in the disconnected state.
if ((runspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Disconnected) ||
!(runspacePool.ConnectionInfo is WSManConnectionInfo))
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.InvalidRunspacePool);
}
RunspacePool = runspacePool;
// The remote runspace pool object can only have the value one set for min/max pools.
// This sets the runspace pool object min/max pool values to one. The PSRP/WSMan stack
// will fail during connection if the min/max pool values do not match.
RunspacePool.RemoteRunspacePoolInternal.SetMinRunspaces(1);
RunspacePool.RemoteRunspacePoolInternal.SetMaxRunspaces(1);
_connectionInfo = runspacePool.ConnectionInfo.InternalCopy();
// Update runspace DisconnectedOn and ExpiresOn property from WSManConnectionInfo
UpdateDisconnectExpiresOn();
// Initial state must be Disconnected.
SetRunspaceState(RunspaceState.Disconnected, null);
// Normal Availability for a disconnected runspace is "None", which means it can be connected.
// However, we can also have disconnected runspace objects that are *not* avaialable for
// connection and in this case the Availability is set to "Busy".
_runspaceAvailability = RunspacePool.RemoteRunspacePoolInternal.AvailableForConnection ?
Runspaces.RunspaceAvailability.None : Runspaces.RunspaceAvailability.Busy;
SetEventHandlers();
PSEtwLog.SetActivityIdForCurrentThread(this.InstanceId);
PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor,
PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational,
this.InstanceId.ToString());
}
/// <summary>
/// Helper function to set event handlers.
/// </summary>
private void SetEventHandlers()
{
// RemoteRunspace must have the same instanceID as its contained RunspacePool instance because
// the PSRP/WinRS layer tracks remote runspace Ids.
this.InstanceId = RunspacePool.InstanceId;
_eventManager = new PSRemoteEventManager(_connectionInfo.ComputerName, this.InstanceId);
RunspacePool.StateChanged +=
new EventHandler<RunspacePoolStateChangedEventArgs>(HandleRunspacePoolStateChanged);
RunspacePool.RemoteRunspacePoolInternal.HostCallReceived +=
new EventHandler<RemoteDataEventArgs<RemoteHostCall>>(HandleHostCallReceived);
RunspacePool.RemoteRunspacePoolInternal.URIRedirectionReported +=
new EventHandler<RemoteDataEventArgs<Uri>>(HandleURIDirectionReported);
RunspacePool.ForwardEvent +=
new EventHandler<PSEventArgs>(HandleRunspacePoolForwardEvent);
RunspacePool.RemoteRunspacePoolInternal.SessionCreateCompleted +=
new EventHandler<CreateCompleteEventArgs>(HandleSessionCreateCompleted);
}
#endregion Constructors
#region Properties
/// <summary>
/// runspaceConfiguration information for this runspace
/// </summary>
#if CORECLR
internal
#else
public
#endif
override RunspaceConfiguration RunspaceConfiguration
{
get
{
#pragma warning disable 56503
throw PSTraceSource.NewNotImplementedException();
#pragma warning restore 56503
}
}
/// <summary>
/// initialsessionstate information for this runspace
/// </summary>
public override InitialSessionState InitialSessionState
{
get
{
#pragma warning disable 56503
throw PSTraceSource.NewNotImplementedException();
#pragma warning restore 56503
}
}
/// <summary>
/// Manager for JobSourceAdapters registered in this runspace.
/// </summary>
public override JobManager JobManager
{
get
{
#pragma warning disable 56503
throw PSTraceSource.NewNotImplementedException();
#pragma warning restore 56503
}
}
/// <summary>
/// Return version of this runspace
/// </summary>
public override Version Version { get; } = PSVersionInfo.PSVersion;
/// <summary>
/// PS Version running on server.
/// </summary>
internal Version ServerVersion { get; private set; }
/// <summary>
/// Retrieve information about current state of the runspace
/// </summary>
public override RunspaceStateInfo RunspaceStateInfo
{
get
{
lock (_syncRoot)
{
//Do not return internal state.
return _runspaceStateInfo.Clone();
}
}
}
/// <summary>
/// This property determines whether a new thread is create for each invocation
/// </summary>
/// <remarks>
/// Any updates to the value of this property must be done before the Runspace is opened
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// An attempt to change this property was made after opening the Runspace
/// </exception>
/// <exception cref="InvalidOperationException">
/// The thread options cannot be changed to the requested value
/// </exception>
public override PSThreadOptions ThreadOptions
{
get
{
return _createThreadOptions;
}
set
{
lock (_syncRoot)
{
if (value != _createThreadOptions)
{
if (this.RunspaceStateInfo.State != RunspaceState.BeforeOpen)
{
throw new InvalidRunspaceStateException(StringUtil.Format(RunspaceStrings.ChangePropertyAfterOpen));
}
_createThreadOptions = value;
}
}
}
}
private PSThreadOptions _createThreadOptions = PSThreadOptions.Default;
/// <summary>
/// Gets the current availability of the Runspace
/// </summary>
public override RunspaceAvailability RunspaceAvailability
{
get { return _runspaceAvailability; }
protected set { _runspaceAvailability = value; }
}
private RunspaceAvailability _runspaceAvailability = RunspaceAvailability.None;
/// <summary>
/// Event raised when RunspaceState changes.
/// </summary>
public override event EventHandler<RunspaceStateEventArgs> StateChanged;
/// <summary>
/// Event raised when the availability of the Runspace changes.
/// </summary>
public override event EventHandler<RunspaceAvailabilityEventArgs> AvailabilityChanged;
/// <summary>
/// Returns true if there are any subscribers to the AvailabilityChanged event
/// </summary>
internal override bool HasAvailabilityChangedSubscribers
{
get { return this.AvailabilityChanged != null; }
}
/// <summary>
/// Raises the AvailabilityChanged event
/// </summary>
protected override void OnAvailabilityChanged(RunspaceAvailabilityEventArgs e)
{
EventHandler<RunspaceAvailabilityEventArgs> eh = this.AvailabilityChanged;
if (eh != null)
{
try
{
eh(this, e);
}
catch (Exception exception) // ignore non-severe exceptions
{
CommandProcessorBase.CheckForSevereException(exception);
}
}
}
/// <summary>
/// Connection information to this runspace
/// </summary>
public override RunspaceConnectionInfo ConnectionInfo
{
get
{
return _connectionInfo;
}
}
/// <summary>
/// ConnectionInfo originally supplied by the user
/// </summary>
public override RunspaceConnectionInfo OriginalConnectionInfo { get; }
/// <summary>
/// Gets the event manager
/// </summary>
public override PSEventManager Events
{
get
{
return _eventManager;
}
}
private PSRemoteEventManager _eventManager;
#pragma warning disable 56503
/// <summary>
/// Gets the execution context for this runspace
/// </summary>
internal override ExecutionContext GetExecutionContext
{
get
{
throw PSTraceSource.NewNotImplementedException();
}
}
/// <summary>
/// Returns true if the internal host is in a nested prompt
/// </summary>
internal override bool InNestedPrompt
{
get
{
return false; // nested prompts are not supported on remote runspaces
}
}
#pragma warning restore 56503
/// <summary>
/// Gets the client remote session associated with this
/// runspace
/// </summary>
/// <remarks>This member is actually not required
/// for the product code. However, there are
/// existing transport manager tests which depend on
/// the same. Once transport manager is modified,
/// this needs to be removed</remarks>
internal ClientRemoteSession ClientRemoteSession
{
get
{
try
{
return RunspacePool.RemoteRunspacePoolInternal.DataStructureHandler.RemoteSession;
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
}
/// <summary>
/// Gets command information on a currently running remote command.
/// If no command is running then null is returned.
/// </summary>
internal ConnectCommandInfo RemoteCommand
{
get
{
if (RunspacePool.RemoteRunspacePoolInternal.ConnectCommands == null)
{
return null;
}
Dbg.Assert(RunspacePool.RemoteRunspacePoolInternal.ConnectCommands.Length < 2, "RemoteRunspace should have no more than one remote running command.");
if (RunspacePool.RemoteRunspacePoolInternal.ConnectCommands.Length > 0)
{
return RunspacePool.RemoteRunspacePoolInternal.ConnectCommands[0];
}
else
{
return null;
}
}
}
/// <summary>
/// Gets friendly name for the remote PSSession.
/// </summary>
internal string PSSessionName
{
get { return RunspacePool.RemoteRunspacePoolInternal.Name; }
set { RunspacePool.RemoteRunspacePoolInternal.Name = value; }
}
/// <summary>
/// Gets the Id value for the remote PSSession.
/// </summary>
internal int PSSessionId { get; set; } = -1;
/// <summary>
/// Returns true if Runspace supports disconnect.
/// </summary>
internal bool CanDisconnect
{
get { return RunspacePool.RemoteRunspacePoolInternal.CanDisconnect; }
}
/// <summary>
/// Returns true if Runspace can be connected.
/// </summary>
internal bool CanConnect
{
get { return RunspacePool.RemoteRunspacePoolInternal.AvailableForConnection; }
}
/// <summary>
/// Debugger
/// </summary>
public override Debugger Debugger
{
get
{
return _remoteDebugger;
}
}
#endregion Properties
#region Open
/// <summary>
/// Open the runspace Asynchronously.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not BeforeOpen
/// </exception>
public override void OpenAsync()
{
AssertIfStateIsBeforeOpen();
try
{
RunspacePool.BeginOpen(null, null);
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
/// <summary>
/// Open the runspace synchronously.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not BeforeOpen
/// </exception>
public override void Open()
{
AssertIfStateIsBeforeOpen();
try
{
RunspacePool.ThreadOptions = this.ThreadOptions;
#if !CORECLR // No ApartmentState In CoreCLR
RunspacePool.ApartmentState = this.ApartmentState;
#endif
RunspacePool.Open();
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
#endregion Open
#region Close
/// <summary>
/// Close the runspace Asynchronously.
/// </summary>
public override void CloseAsync()
{
try
{
RunspacePool.BeginClose(null, null);
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
/// <summary>
/// Close the runspace synchronously.
/// </summary>
/// <remarks>
/// Attempts to execute pipelines after a call to close will fail.
/// </remarks>
public override void Close()
{
try
{
IAsyncResult result = RunspacePool.BeginClose(null, null);
WaitForFinishofPipelines();
// It is possible for the result ASyncResult object to be null if the runspace
// pool is already being closed from a server initiated close event.
if (result != null)
{
RunspacePool.EndClose(result);
}
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
/// <summary>
/// Dispose this runspace
/// </summary>
/// <param name="disposing">true if called from Dispose</param>
protected override void Dispose(bool disposing)
{
try
{
if (_disposed)
{
return;
}
lock (_syncRoot)
{
if (_disposed)
{
return;
}
_disposed = true;
}
if (disposing)
{
try
{
Close();
}
catch (PSRemotingTransportException)
{
//
// If the WinRM listener has been removed before the runspace is closed, then calling
// Close() will cause a PSRemotingTransportException. We don't want this exception
// surfaced. Most developers don't expect an exception from calling Dispose.
// See [Windows 8 Bugs] 968184.
//
}
if (_remoteDebugger != null)
{
// Release RunspacePool event forwarding handlers.
_remoteDebugger.Dispose();
}
try
{
RunspacePool.StateChanged -=
new EventHandler<RunspacePoolStateChangedEventArgs>(HandleRunspacePoolStateChanged);
RunspacePool.RemoteRunspacePoolInternal.HostCallReceived -=
new EventHandler<RemoteDataEventArgs<RemoteHostCall>>(HandleHostCallReceived);
RunspacePool.RemoteRunspacePoolInternal.URIRedirectionReported -=
new EventHandler<RemoteDataEventArgs<Uri>>(HandleURIDirectionReported);
RunspacePool.ForwardEvent -=
new EventHandler<PSEventArgs>(HandleRunspacePoolForwardEvent);
RunspacePool.RemoteRunspacePoolInternal.SessionCreateCompleted -=
new EventHandler<CreateCompleteEventArgs>(HandleSessionCreateCompleted);
_eventManager = null;
RunspacePool.Dispose();
//_runspacePool = null;
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
}
finally
{
base.Dispose(disposing);
}
}
#endregion Close
#region Reset Runspace State
/// <summary>
/// Resets the runspace state to allow for fast reuse. Not all of the runspace
/// elements are reset. The goal is to minimize the chance of the user taking
/// accidental dependencies on prior runspace state.
/// </summary>
/// <exception cref="PSInvalidOperationException">
/// Thrown when runspace is not in proper state or avaialablity or if the
/// reset operation fails in the remote session.
/// </exception>
public override void ResetRunspaceState()
{
PSInvalidOperationException invalidOperation = null;
if (this.RunspaceStateInfo.State != Runspaces.RunspaceState.Opened)
{
invalidOperation = PSTraceSource.NewInvalidOperationException(
RunspaceStrings.RunspaceNotInOpenedState, this.RunspaceStateInfo.State);
}
else if (this.RunspaceAvailability != Runspaces.RunspaceAvailability.Available)
{
invalidOperation = PSTraceSource.NewInvalidOperationException(
RunspaceStrings.ConcurrentInvokeNotAllowed);
}
else
{
bool success = RunspacePool.RemoteRunspacePoolInternal.ResetRunspaceState();
if (!success)
{
invalidOperation = PSTraceSource.NewInvalidOperationException();
}
}
if (invalidOperation != null)
{
invalidOperation.Source = "ResetRunspaceState";
throw invalidOperation;
}
}
#endregion
#region Disconnect-Connect
/// <summary>
/// Queries the server for disconnected runspaces and creates an array of runspace
/// objects associated with each disconnected runspace on the server. Each
/// runspace object in the returned array is in the Disconnected state and can be
/// connected to the server by calling the Connect() method on the runspace.
/// </summary>
/// <param name="connectionInfo">Connection object for the target server.</param>
/// <param name="host">Client host object.</param>
/// <param name="typeTable">TypeTable object.</param>
/// <returns>Array of Runspace objects each in the Disconnected state.</returns>
internal static Runspace[] GetRemoteRunspaces(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable)
{
List<Runspace> runspaces = new List<Runspace>();
RunspacePool[] runspacePools = RemoteRunspacePoolInternal.GetRemoteRunspacePools(connectionInfo, host, typeTable);
// We don't yet know how many runspaces there are in these runspace pool objects. This information isn't updated
// until a Connect() is performed. But we can use the ConnectCommands list to prune runspace pool objects that
// clearly have more than one command/runspace.
foreach (RunspacePool runspacePool in runspacePools)
{
if (runspacePool.RemoteRunspacePoolInternal.ConnectCommands.Length < 2)
{
runspaces.Add(new RemoteRunspace(runspacePool));
}
}
return runspaces.ToArray();
}
/// <summary>
/// Creates a single disconnected remote Runspace object based on connection information and
/// session / command identifiers.
/// </summary>
/// <param name="connectionInfo">Connection object for target machine</param>
/// <param name="sessionId">Session Id to connect to</param>
/// <param name="commandId">Optional command Id to connect to</param>
/// <param name="host">Optional PSHost</param>
/// <param name="typeTable">Optional TypeTable</param>
/// <returns>Disconnect remote Runspace object</returns>
internal static Runspace GetRemoteRunspace(RunspaceConnectionInfo connectionInfo, Guid sessionId, Guid? commandId, PSHost host, TypeTable typeTable)
{
RunspacePool runspacePool = RemoteRunspacePoolInternal.GetRemoteRunspacePool(
connectionInfo,
sessionId,
commandId,
host,
typeTable);
return new RemoteRunspace(runspacePool);
}
/// <summary>
/// Disconnects the runspace synchronously.
/// </summary>
/// <remarks>
/// Disconnects the remote runspace and any running command from the server
/// machine. Any data generated by the running command on the server is
/// cached on the server machine. This runspace object goes to the disconnected
/// state. This object can be reconnected to the server by calling the
/// Connect() method.
/// If the remote runspace on the server remains disconnected for the IdleTimeout
/// value (as defined in the WSManConnectionInfo object) then it is closed and
/// torn down on the server.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Opened.
/// </exception>
public override void Disconnect()
{
if (!CanDisconnect)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.DisconnectNotSupportedOnServer);
}
UpdatePoolDisconnectOptions();
try
{
RunspacePool.Disconnect();
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
/// <summary>
/// Disconnects the runspace asynchronously.
/// </summary>
/// <remarks>
/// Disconnects the remote runspace and any running command from the server
/// machine. Any data generated by the running command on the server is
/// cached on the server machine. This runspace object goes to the disconnected
/// state. This object can be reconnected to the server by calling the
/// Connect() method.
/// If the remote runspace on the server remains disconnected for the IdleTimeout
/// value (as defined in the WSManConnectionInfo object) then it is closed and
/// torn down on the server.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Opened.
/// </exception>
public override void DisconnectAsync()
{
if (!CanDisconnect)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.DisconnectNotSupportedOnServer);
}
UpdatePoolDisconnectOptions();
try
{
RunspacePool.BeginDisconnect(null, null);
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
/// <summary>
/// Connects the runspace to its remote counterpart synchronously.
/// </summary>
/// <remarks>
/// Connects the runspace object to its corresponding runspace on the target
/// server machine. The target server machine is identified by the connection
/// object passed in during construction. The remote runspace is identified
/// by the internal runspace Guid value.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Disconnected.
/// </exception>
public override void Connect()
{
if (!CanConnect)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.CannotConnect);
}
UpdatePoolDisconnectOptions();
try
{
RunspacePool.Connect();
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
/// <summary>
/// Connects a runspace to its remote counterpart asynchronously.
/// </summary>
/// <remarks>
/// Connects the runspace object to its corresponding runspace on the target
/// server machine. The target server machine is identified by the connection
/// object passed in during construction. The remote runspace is identified
/// by the internal runspace Guid value.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Disconnected.
/// </exception>
public override void ConnectAsync()
{
if (!CanConnect)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.CannotConnect);
}
UpdatePoolDisconnectOptions();
try
{
RunspacePool.BeginConnect(null, null);
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
/// <summary>
/// Creates a PipeLine object in the disconnected state for the currently disconnected
/// remote running command associated with this runspace.
/// </summary>
/// <returns>Pipeline object in disconnected state.</returns>
public override Pipeline CreateDisconnectedPipeline()
{
if (RemoteCommand == null)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.NoDisconnectedCommand);
}
return new RemotePipeline(this);
}
/// <summary>
/// Creates a PowerShell object in the disconnected state for the currently disconnected
/// remote running command associated with this runspace.
/// </summary>
/// <returns>PowerShell object in disconnected state.</returns>
public override PowerShell CreateDisconnectedPowerShell()
{
if (RemoteCommand == null)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.NoDisconnectedCommand);
}
return new PowerShell(RemoteCommand, this);
}
/// <summary>
/// Returns Runspace capabilities.
/// </summary>
/// <returns>RunspaceCapability</returns>
public override RunspaceCapability GetCapabilities()
{
RunspaceCapability returnCaps = RunspaceCapability.Default;
if (CanDisconnect)
{
returnCaps |= RunspaceCapability.SupportsDisconnect;
}
if (_connectionInfo is NamedPipeConnectionInfo)
{
returnCaps |= RunspaceCapability.NamedPipeTransport;
}
else if (_connectionInfo is VMConnectionInfo)
{
returnCaps |= RunspaceCapability.VMSocketTransport;
}
else if (_connectionInfo is SSHConnectionInfo)
{
returnCaps |= RunspaceCapability.SSHTransport;
}
else
{
ContainerConnectionInfo containerConnectionInfo = _connectionInfo as ContainerConnectionInfo;
if ((containerConnectionInfo != null) &&
(containerConnectionInfo.ContainerProc.RuntimeId == Guid.Empty))
{
returnCaps |= RunspaceCapability.NamedPipeTransport;
}
}
return returnCaps;
}
/// <summary>
/// Update the pool disconnect options so that any changes will be
/// passed to the server during the disconnect/connect operations.
/// </summary>
private void UpdatePoolDisconnectOptions()
{