Exemplo n.º 1
0
 public void Stop()
 {
     StopServer = true;
     //Listener.Close();
     PowerShellPool.Dispose();
     Log("Server Stopped.");
 }
Exemplo n.º 2
0
 public void Dispose()
 {
     if (m_posh_runspace_pool != null && m_posh_runspace_pool.IsDisposed == false)
     {
         m_posh_runspace_pool.Dispose();
     }
 }
        // In this function the activity action is performed
        private void PerformWork(ActivityActionData data)
        {
            bool      failed    = false;
            Exception exception = null;

            try
            {
                // setting up the streams
                data.command.Streams.Debug    = data.streams.DebugStream;
                data.command.Streams.Error    = data.streams.ErrorStream;
                data.command.Streams.Progress = data.streams.ProgressStream;
                data.command.Streams.Verbose  = data.streams.VerboseStream;
                data.command.Streams.Warning  = data.streams.WarningStream;


                // Custom WinRM Workflow Endpoint details
                // run CustomWorkflowEndpointSetup.ps1 in Powershell console as administrator, if you have not done.
                //
                WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
                connectionInfo.ShellUri = "http://schemas.microsoft.com/powershell/CustomeWorkflowEndpoint";

                // Create runspace pool on custom workflow endpoint where command will be invoked
                using (RunspacePool r = RunspaceFactory.CreateRunspacePool(1, 1, connectionInfo))
                {
                    try
                    {
                        r.Open();
                        data.command.RunspacePool = r;

                        // now executing the powershell command.
                        data.command.Invoke(data.streams.InputStream, data.streams.OutputStream, new PSInvocationSettings());
                    }
                    finally
                    {
                        r.Close();
                        r.Dispose();
                    }
                }
            }
            catch (Exception e)
            {
                // since work is getting performed on background thread so there should not be any exception.
                failed    = true;
                exception = e;
            }

            // Now since activity action has already been performed so now we need to resume the execution of the
            // workflow. This will be done by
            PSWorkflowJob job = _runtime.JobManager.GetJob(data.jobInstanceId);

            // Now resuming the job
            if (failed)
            {
                job.ResumeBookmark(data.bookmark, this.SupportDisconnectedPSStreams, data.streams, exception);
            }
            else
            {
                job.ResumeBookmark(data.bookmark, this.SupportDisconnectedPSStreams, data.streams);
            }
        }
Exemplo n.º 4
0
        public async Task ListenerLoop()
        {
            while (!StopServer)
            {
                var context = await Listener.GetContextAsync();

                if (StopServer)
                {
                    break;
                }

                HttpListenerRequest  rawRequest  = context.Request;
                HttpListenerResponse rawResponse = context.Response;

                Console.WriteLine("request came in: " + rawRequest.HttpMethod + " " + rawRequest.RawUrl);

                PolarisRequest  request  = new PolarisRequest(rawRequest);
                PolarisResponse response = new PolarisResponse();

                string     route = rawRequest.Url.AbsolutePath.TrimEnd('/').TrimStart('/');
                PowerShell PowerShellInstance = PowerShell.Create();
                PowerShellInstance.RunspacePool = PowerShellPool;
                try
                {
                    // this script has a sleep in it to simulate a long running script
                    PowerShellInstance.AddScript(ScriptBlockRoutes[route][rawRequest.HttpMethod]);
                    PowerShellInstance.AddParameter(nameof(request), request);
                    PowerShellInstance.AddParameter(nameof(response), response);

                    var res = PowerShellInstance.BeginInvoke <PSObject>(new PSDataCollection <PSObject>(), new PSInvocationSettings(), (result) => {
                        if (PowerShellInstance.InvocationStateInfo.State == PSInvocationState.Failed)
                        {
                            Console.WriteLine(PowerShellInstance.InvocationStateInfo.Reason);
                            response.Send(PowerShellInstance.InvocationStateInfo.Reason.ToString());
                            response.SetStatusCode(500);
                        }
                        Send(rawResponse, response);
                        PowerShellInstance.Dispose();
                    }, null);
                }
                catch (Exception e)
                {
                    if (e is KeyNotFoundException)
                    {
                        Send(rawResponse, System.Text.Encoding.UTF8.GetBytes("Not Found"), 404, "text/plain; charset=UTF-8");
                        Console.WriteLine("404 Not Found");
                    }
                    else
                    {
                        Console.WriteLine(e.Message);
                        throw e;
                    }
                }
            }

            Listener.Close();
            PowerShellPool.Dispose();
        }
Exemplo n.º 5
0
        protected override void Dispose(bool disposing)
        {
            Stop();

            RunspacePool.Close();
            RunspacePool.Dispose();
            RunspacePool = null;
            base.Dispose(disposing);
        }
        private bool _disposedValue = false; // To detect redundant calls

        /// <summary>
        /// Dispose of this object.
        /// </summary>
        /// <param name="disposing">True if the method is called by the Dispose method, false if called by the finalizer.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue)
            {
                if (disposing)
                {
                    _analysisRunspacePool.Dispose();
                    _analysisRunspacePool = null;
                }

                _disposedValue = true;
            }
        }
 public void Release()
 {
     if (null != _rsPool)
     {
         lock (this)
         {
             if (null != _rsPool)
             {
                 _rsPool.Close();
                 _rsPool.Dispose();
                 _rsPool = null;
             }
         }
     }
 }
Exemplo n.º 8
0
        internal static void CleanupObjs(PSCmdlet invokeAll, FunctionInfo proxyFunctionInfo, RunspacePool runspacePool, bool isFromPipelineStoppedException,
                                         bool isAsyncEnd = false, bool noFileLogging = false, bool quiet = false)
        {
            LogHelper.LogProgress("Completed", invokeAll, "Completed", quiet: quiet);
            LogHelper.Log(fileVerboseLogTypes, "In Cleanup", invokeAll, noFileLogging);
            if (!isFromPipelineStoppedException && proxyFunctionInfo != null)
            {
                ScriptBlock.Create(@"Remove-Item Function:" + proxyFunctionInfo.Name).Invoke();
            }

            if (!isAsyncEnd && runspacePool != null)
            {
                if (runspacePool.ConnectionInfo != null)
                {
                    //runspacePool.Disconnect();
                }
                runspacePool.Close();
                runspacePool.Dispose();
            }
        }
Exemplo n.º 9
0
 public void Dispose()
 {
     _runspace?.Dispose();
 }
Exemplo n.º 10
0
 public void Dispose()
 {
     Streams.Dispose();
     _availablePoolMembers.Dispose();
     _runspacePool?.Dispose();
 }
Exemplo n.º 11
0
 public void Dispose()
 {
     m_runspacePool.Dispose();
 }
Exemplo n.º 12
0
        public async Task ListenerLoop()
        {
            while (!StopServer)
            {
                var context = await Listener.GetContextAsync();

                if (StopServer)
                {
                    break;
                }

                HttpListenerRequest  rawRequest  = context.Request;
                HttpListenerResponse rawResponse = context.Response;

                Log("request came in: " + rawRequest.HttpMethod + " " + rawRequest.RawUrl);

                PolarisRequest  request  = new PolarisRequest(rawRequest);
                PolarisResponse response = new PolarisResponse();

                string     route = rawRequest.Url.AbsolutePath.TrimEnd('/').TrimStart('/');
                PowerShell PowerShellInstance = PowerShell.Create();
                PowerShellInstance.RunspacePool = PowerShellPool;
                try
                {
                    // Set up PowerShell instance by making request and response global
                    PowerShellInstance.AddScript(PolarisHelperScripts.InitializeRequestAndResponseScript);
                    PowerShellInstance.AddParameter("req", request);
                    PowerShellInstance.AddParameter("res", response);

                    // Run middleware in the order in which it was added
                    foreach (PolarisMiddleware middleware in RouteMiddleware)
                    {
                        PowerShellInstance.AddScript(middleware.ScriptBlock);
                    }

                    PowerShellInstance.AddScript(ScriptBlockRoutes[route][rawRequest.HttpMethod]);

                    var res = PowerShellInstance.BeginInvoke <PSObject>(new PSDataCollection <PSObject>(), new PSInvocationSettings(), (result) => {
                        if (PowerShellInstance.InvocationStateInfo.State == PSInvocationState.Failed)
                        {
                            Log(PowerShellInstance.InvocationStateInfo.Reason.ToString());
                            response.Send(PowerShellInstance.InvocationStateInfo.Reason.ToString());
                            response.SetStatusCode(500);
                        }
                        Send(rawResponse, response);
                        PowerShellInstance.Dispose();
                    }, null);
                }
                catch (Exception e)
                {
                    if (e is KeyNotFoundException)
                    {
                        Send(rawResponse, System.Text.Encoding.UTF8.GetBytes("Not Found"), 404, "text/plain; charset=UTF-8");
                        Log("404 Not Found");
                    }
                    else
                    {
                        Log(e.Message);
                        throw e;
                    }
                }
            }

            Listener.Close();
            PowerShellPool.Dispose();
        }
        protected override void BeginProcessing()
        {
            // Build the results
            ArrayList final = new ArrayList();
            int       c     = 0;
            int       count = InputObject.Count;

            if (MaxThreads < 20)
            {
                MaxThreads = 20;
            }
            using (RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(1, MaxThreads))
            {
                try
                {
                    runspacePool.Open();
                    ProgressRecord progressRecord = new ProgressRecord(1, "Action in progress...", "Processing...");

                    foreach (object obj in InputObject)
                    {
                        PowerShell powerShell = PowerShell.Create()
                                                .AddScript(ScriptBlock)
                                                .AddArgument(obj);

                        try
                        {
                            powerShell.AddParameters(ArgumentList);
                        }
                        catch (Exception)
                        {
                        }
                        powerShell.RunspacePool = runspacePool;

                        IAsyncResult psAsyncResult = powerShell.BeginInvoke();
                        c++;

                        int    pVal = (c / count) * 100;
                        string sVal = String.Format("{0:N0}", pVal);
                        int    perc = int.Parse(sVal);

                        string activity = c + " of " + count + " threads completed";
                        if (NoProgress.IsPresent == false)
                        {
                            progressRecord.PercentComplete   = perc;
                            progressRecord.Activity          = activity;
                            progressRecord.StatusDescription = perc + "% complete";
                            WriteProgress(progressRecord);
                        }

                        PSDataCollection <PSObject> psOutput = powerShell.EndInvoke(psAsyncResult);
                        final.Add(psOutput);
                        powerShell.Dispose();
                    } // End foreach

                    if (NoProgress.IsPresent == false)
                    {
                        progressRecord.PercentComplete   = 100;
                        progressRecord.StatusDescription = "100% complete";
                        WriteProgress(progressRecord);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                runspacePool.Close();
                runspacePool.Dispose();
            } // End using

            // Output to console
            WriteObject(final.ToArray(), true);
        } // End begin
Exemplo n.º 14
0
 public void closeRunspacePool()
 {
     runspacePool.Close();
     runspacePool.Dispose();
 }