File size: 11,066 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Dbg = System.Management.Automation.Diagnostics;

// Warning: Events StartSteppablePipeline and RunProcessRecord are never used
// They are actually used by the event manager in some dynamically generated IL
#pragma warning disable 0067

namespace System.Management.Automation
{
    /// <summary>
    /// Event handler argument.
    /// </summary>
    internal class ServerSteppablePipelineDriverEventArg : EventArgs
    {
        internal ServerSteppablePipelineDriver SteppableDriver;

        internal ServerSteppablePipelineDriverEventArg(ServerSteppablePipelineDriver driver)
        {
            this.SteppableDriver = driver;
        }
    }

    /// <summary>
    /// Steppable pipeline driver event handler class.
    /// </summary>
    internal class ServerSteppablePipelineSubscriber
    {
        #region Private data

        private readonly object _syncObject = new object();
        private bool _initialized = false;
        private PSLocalEventManager _eventManager;
        private PSEventSubscriber _startSubscriber;
        private PSEventSubscriber _processSubscriber;

        #endregion

        internal void SubscribeEvents(ServerSteppablePipelineDriver driver)
        {
            lock (_syncObject)
            {
                if (!_initialized)
                {
                    _eventManager = (object)driver.LocalPowerShell.Runspace.Events as PSLocalEventManager;

                    if (_eventManager != null)
                    {
                        _startSubscriber = _eventManager.SubscribeEvent(this, "StartSteppablePipeline", Guid.NewGuid().ToString(), null,
                            new PSEventReceivedEventHandler(this.HandleStartEvent), true, false, true);

                        _processSubscriber = _eventManager.SubscribeEvent(this, "RunProcessRecord", Guid.NewGuid().ToString(), null,
                            new PSEventReceivedEventHandler(this.HandleProcessRecord), true, false, true);
                    }

                    _initialized = true;
                }
            }
        }

        #region Events and Handlers

        public event EventHandler<EventArgs> StartSteppablePipeline;

        public event EventHandler<EventArgs> RunProcessRecord;

        /// <summary>
        /// Handles the start pipeline event, this is called by the event manager.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void HandleStartEvent(object sender, PSEventArgs args)
        {
            ServerSteppablePipelineDriverEventArg driverArg = (object)args.SourceEventArgs as ServerSteppablePipelineDriverEventArg;
            ServerSteppablePipelineDriver driver = driverArg.SteppableDriver;

            Exception exceptionOccurred = null;

            try
            {
                using (ExecutionContextForStepping ctxt =
                    ExecutionContextForStepping.PrepareExecutionContext(
                        driver.LocalPowerShell.GetContextFromTLS(),
                        driver.LocalPowerShell.InformationalBuffers,
                        driver.RemoteHost))
                {
                    driver.SteppablePipeline = driver.LocalPowerShell.GetSteppablePipeline();
                    driver.SteppablePipeline.Begin(!driver.NoInput);
                }

                if (driver.NoInput)
                {
                    driver.HandleInputEndReceived(this, EventArgs.Empty);
                }
            }
            catch (Exception e)
            {
                // We need to catch this so that we can set the pipeline execution;
                // state to "failed" and send the exception as an error to the user.
                // Otherwise, the event manager will swallow this exception and
                // cause the client to not respond.
                exceptionOccurred = e;
            }

            if (exceptionOccurred != null)
            {
                driver.SetState(PSInvocationState.Failed, exceptionOccurred);
            }
        }

        /// <summary>
        /// Handles process record event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void HandleProcessRecord(object sender, PSEventArgs args)
        {
            ServerSteppablePipelineDriverEventArg driverArg = (object)args.SourceEventArgs as ServerSteppablePipelineDriverEventArg;
            ServerSteppablePipelineDriver driver = driverArg.SteppableDriver;

            lock (driver.SyncObject)
            {
                // Make sure start event handler was called
                if (driver.SteppablePipeline == null)
                {
                    return;
                }

                // make sure only one thread does the processing
                if (driver.ProcessingInput)
                {
                    return;
                }

                driver.ProcessingInput = true;
                driver.Pulsed = false;
            }

            bool shouldDoComplete = false;
            Exception exceptionOccurred = null;
            try
            {
                using (ExecutionContextForStepping ctxt =
                ExecutionContextForStepping.PrepareExecutionContext(
                    driver.LocalPowerShell.GetContextFromTLS(),
                    driver.LocalPowerShell.InformationalBuffers,
                    driver.RemoteHost))
                {
                    bool isProcessCalled = false;
                    while (true)
                    {
                        if (driver.PipelineState != PSInvocationState.Running)
                        {
                            driver.SetState(driver.PipelineState, null);
                            return;
                        }

                        if (!driver.InputEnumerator.MoveNext())
                        {
                            shouldDoComplete = true;
                            if (!driver.NoInput || isProcessCalled)
                            {
                                // if there is noInput then we
                                // need to call process at least once
                                break;
                            }
                        }

                        isProcessCalled = true;
                        Array output;
                        if (driver.NoInput)
                        {
                            output = driver.SteppablePipeline.Process();
                        }
                        else
                        {
                            output = driver.SteppablePipeline.Process(driver.InputEnumerator.Current);
                        }

                        foreach (object o in output)
                        {
                            if (driver.PipelineState != PSInvocationState.Running)
                            {
                                driver.SetState(driver.PipelineState, null);
                                return;
                            }

                            // send the output data to the client
                            driver.DataStructureHandler.SendOutputDataToClient(PSObject.AsPSObject(o));
                        }

                        lock (driver.SyncObject)
                        {
                            driver.TotalObjectsProcessed++;
                            if (driver.TotalObjectsProcessed >= driver.Input.Count)
                            {
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                exceptionOccurred = e;
            }
            finally
            {
                lock (driver.SyncObject)
                {
                    driver.ProcessingInput = false;
                    driver.CheckAndPulseForProcessing(false);
                }
                // Check if should perform stop
                if (driver.PipelineState == PSInvocationState.Stopping)
                {
                    driver.PerformStop();
                }
            }

            if (shouldDoComplete)
            {
                try
                {
                    using (ExecutionContextForStepping ctxt =
                    ExecutionContextForStepping.PrepareExecutionContext(
                        driver.LocalPowerShell.GetContextFromTLS(),
                        driver.LocalPowerShell.InformationalBuffers,
                        driver.RemoteHost))
                    {
                        Array output = driver.SteppablePipeline.End();
                        foreach (object o in output)
                        {
                            if (driver.PipelineState != PSInvocationState.Running)
                            {
                                driver.SetState(driver.PipelineState, null);
                                return;
                            }

                            // send the output data to the client
                            driver.DataStructureHandler.SendOutputDataToClient(PSObject.AsPSObject(o));
                        }

                        driver.SetState(PSInvocationState.Completed, null);
                        return;
                    }
                }
                catch (Exception e)
                {
                    exceptionOccurred = e;
                }
                finally
                {
                    // Check if should perform stop
                    if (driver.PipelineState == PSInvocationState.Stopping)
                    {
                        driver.PerformStop();
                    }
                }
            }

            if (exceptionOccurred != null)
            {
                driver.SetState(PSInvocationState.Failed, exceptionOccurred);
            }
        }

        /// <summary>
        /// Fires the start event.
        /// </summary>
        /// <param name="driver">Steppable pipeline driver.</param>
        internal void FireStartSteppablePipeline(ServerSteppablePipelineDriver driver)
        {
            lock (_syncObject)
            {
                _eventManager?.GenerateEvent(_startSubscriber.SourceIdentifier, this,
                    new object[1] { new ServerSteppablePipelineDriverEventArg(driver) }, null, true, false);
            }
        }

        /// <summary>
        /// Fires the process record event.
        /// </summary>
        /// <param name="driver">Steppable pipeline driver.</param>
        internal void FireHandleProcessRecord(ServerSteppablePipelineDriver driver)
        {
            lock (_syncObject)
            {
                _eventManager?.GenerateEvent(_processSubscriber.SourceIdentifier, this,
                    new object[1] { new ServerSteppablePipelineDriverEventArg(driver) }, null, true, false);
            }
        }

        #endregion
    }
}