コード例 #1
0
        private async Task <int> Run(HostCommandContext context,
                                     string pipeName,
                                     long maxMemory,
                                     int affinityMask,
                                     int maxCpu)
        {
            var currentProcess = SDProcess.GetCurrentProcess();

            var logger = context.ServiceProvider.GetService <ILoggerFactory>().CreateLogger <HostProcessImpl>();

            logger.HostProcessStart(currentProcess.Id);

            string name = "pihost." + currentProcess.Id;

            var limits = new IsolationLimits(maxMemory, maxCpu, affinityMask);

            if (limits.IsAnyEnabled)
            {
                s_jobObject = new JobObject(name);
                s_jobObject.AddProcess(currentProcess);
                s_jobObject.Enable(limits, (l, v) => logger.ProcessLimitSet(l, v));
            }

            var host = new IpcServiceHostBuilder(context.ServiceProvider)
                       .AddNamedPipeEndpoint <IHostProcess>(name, pipeName, includeFailureDetailsInResponse: true)
                       .Build();

            logger.IpcServiceHostStarting(pipeName);
            context.SetStartComplete();
            await host.RunAsync(context.Token).ConfigureAwait(false);

            return(0);
        }
コード例 #2
0
 public void AddWorkerProcess(Process newInstanceWorkerProcess)
 {
     if (false == newInstanceWorkerProcess.HasExited &&
         false == jobObject.HasProcess(newInstanceWorkerProcess))
     {
         jobObject.AddProcess(newInstanceWorkerProcess);
         if (false == workerProcessStartDate.HasValue)
         {
             workerProcessStartDate = DateTime.Now;
         }
     }
 }
コード例 #3
0
        public static MongoDbConnector GetServer()
        {
            var lMongoConnector = new MongoDbConnector();

            var processId = SpawnNewProcess(lMongoConnector.DbName, lMongoConnector.Port);

            lMongoConnector.ProcessId = processId;

            if (processId == -1)
            {
                return(lMongoConnector);
            }

            var job = new JobObject();

            job.AddProcess(processId);

            return(lMongoConnector);
        }
コード例 #4
0
        public void Start(Configuration configuration)
        {
            if (_process == null)
            {
                var existingPrivoxy = Process.GetProcessesByName(ExeNameNoExt);
                foreach (var p in existingPrivoxy.Where(IsChildProcess))
                {
                    KillProcess(p);
                }
                var privoxyConfig = Resources.privoxy_conf;
                RunningPort   = GetFreePort();
                privoxyConfig = privoxyConfig.Replace(@"__SOCKS_PORT__", configuration.LocalPort.ToString());
                privoxyConfig = privoxyConfig.Replace(@"__PRIVOXY_BIND_PORT__", RunningPort.ToString());
                privoxyConfig = privoxyConfig.Replace(@"__PRIVOXY_BIND_IP__",
                                                      configuration.ShareOverLan ? Global.AnyHost : Global.LocalHost)
                                .Replace(@"__SOCKS_HOST__", Global.LocalHost);
                FileManager.ByteArrayToFile(Utils.GetTempPath(UNIQUE_CONFIG_FILE), Encoding.UTF8.GetBytes(privoxyConfig));

                _process = new Process
                {
                    // Configure the process using the StartInfo properties.
                    StartInfo =
                    {
                        FileName         = ExeName,
                        Arguments        = UNIQUE_CONFIG_FILE,
                        WorkingDirectory = Utils.GetTempPath(),
                        WindowStyle      = ProcessWindowStyle.Hidden,
                        UseShellExecute  = true,
                        CreateNoWindow   = true
                    }
                };
                _process.Start();

                /*
                 * Add this process to job obj associated with this ss process, so that
                 * when ss exit unexpectedly, this process will be forced killed by system.
                 */
                PRIVOXY_JOB.AddProcess(_process);
            }
        }
コード例 #5
0
        public static MongoDbConnector GetServer(string dbName, string hostname, int port)
        {
            if (string.IsNullOrEmpty(dbName))
            {
                throw new ArgumentNullException(dbName);
            }

            var lMongoConnector = new MongoDbConnector(dbName, hostname, port);

            var processId = SpawnNewProcess(lMongoConnector.DbName, lMongoConnector.Port);

            lMongoConnector.ProcessId = processId;

            if (processId == -1)
            {
                return(null);
            }

            var job = new JobObject();

            job.AddProcess(processId);

            return(lMongoConnector);
        }
コード例 #6
0
        public ProcessExecutionInfo Start(int timeLimit, int memoryLimit)
        {
            var executionInfo = new ProcessExecutionInfo();

            using (var job = new JobObject())
            {
                // Prepare job
                job.SetExtendedLimitInformation(PrepareJobObject.GetExtendedLimitInformation(timeLimit, memoryLimit));
                job.SetBasicUiRestrictions(PrepareJobObject.GetUiRestrictions());

                // Start process and assign it to job object
                this.process.Start();

                var memoryTaskCancellationToken = new CancellationTokenSource();
                var memoryTask = Task.Run(
                    () =>
                {
                    while (true)
                    {
                        // ReSharper disable once AccessToDisposedClosure
                        var peakWorkingSetSize = this.PeakWorkingSetSize;

                        executionInfo.MaxMemoryUsed = Math.Max(executionInfo.MaxMemoryUsed, peakWorkingSetSize);

                        if (memoryTaskCancellationToken.IsCancellationRequested)
                        {
                            return;
                        }

                        Thread.Sleep(30);
                    }
                },
                    memoryTaskCancellationToken.Token);

                job.AddProcess(this.process.Handle);
                this.process.PriorityClass = ProcessPriorityClass.RealTime;

                // Process input
                if (this.charsToWrite != null)
                {
                    try
                    {
                        this.process.StandardInput.WriteAsync(this.charsToWrite, 0, this.charsToWrite.Length)
                        .ContinueWith(
                            delegate
                        {
                            // this.process.StandardInput.AutoFlush = false;
                            this.process.StandardInput.FlushAsync();
                        });
                    }
                    catch (IOException)
                    {
                        // The pipe has been ended exception (when process is stopped before the write is done)
                    }
                }

                var exited = this.process.WaitForExit(timeLimit);
                if (!exited)
                {
                    // TODO: Fix: Console.WriteLine(job.GetExtendedLimitInformation().BasicLimitInformation.ActiveProcessLimit);
                    job.Close();
                    executionInfo.ProcessKilledBecauseOfTimeLimit = true; // Time limit
                }

                // Process output
                var output = this.process.StandardOutput.ReadToEnd();

                // Process error
                var errorOutput = this.process.StandardError.ReadToEnd();

                memoryTaskCancellationToken.Cancel();
                memoryTask.Wait(30); // To be sure that memory consumption will be evaluated correctly

                // Prepare execution info
                executionInfo.StandardOutputContent = output;
                executionInfo.StandardErrorContent  = errorOutput;
            }

            return(executionInfo);
        }
コード例 #7
0
        public HostProcessClient(IpcServiceClient <IHostProcess> client, string pipeName, IsolationOptions options)
        {
            m_client  = client;
            PipeName  = pipeName;
            m_process = new Process();

            var arguments = new StringBuilder();

            if (!options.StartWithExeLauncher)
            {
                HostBinary          = Path.GetFileName(s_locations.Value.HostAssemblyPath);
                m_process.StartInfo = new ProcessStartInfo(s_locations.Value.DotNetExecutablePath);
                arguments.Append(s_locations.Value.HostAssemblyPath);
            }
            else
            {
                HostBinary          = Path.GetFileName(s_locations.Value.HostExecutablePath);
                m_process.StartInfo = new ProcessStartInfo(s_locations.Value.HostExecutablePath);
            }

            if (options.CreateJobObject)
            {
                CreateJobObject = true;
                JobName         = PipeName; // For now, simply reuse pipe name
                m_jobObject     = new JobObject(JobName);

                if (options.DieOnCrash)
                {
                    // Normally, we don't want the controlling process to die when a host process
                    // crashes/exits. However, the user might want to bind their faiths together
                    // for easier management.
                    m_jobObject.AddProcess(Process.GetCurrentProcess());
                }
            }

            if (options.Limits != null && options.Limits.IsAnyEnabled)
            {
                if (options.Limits.MaxCpuUsage > 0)
                {
                    arguments.Append(" --max-cpu ").Append(options.Limits.MaxCpuUsage
                                                           .ToString(CultureInfo.InvariantCulture));
                }

                if (options.Limits.MaxMemory > 0)
                {
                    arguments.Append(" --max-memory ").Append(options.Limits.MaxMemory
                                                              .ToString(CultureInfo.InvariantCulture));
                }

                if (options.Limits.AffinityMask != IntPtr.Zero)
                {
                    arguments.Append(" --affinity-mask ").Append(options.Limits.AffinityMask
                                                                 .ToInt32().ToString(CultureInfo.InvariantCulture));
                }
            }

            Dictionary <string, string> environment = null;

            AddDebug(ref environment, options.Debug);
            AddLogLevel(ref environment, options.LogLevel);
            AddListenerThreads(ref environment, options.ListenerThreads);

            if (arguments.Length > 0)
            {
                arguments.Append(" ");
            }

            arguments.Append(pipeName);

            m_process.StartInfo.Arguments = arguments.ToString();
            if (environment != null)
            {
                foreach (var kvp in environment)
                {
                    m_process.StartInfo.Environment.Add(kvp);
                }
            }

            m_process.StartInfo.UseShellExecute        = false;
            m_process.StartInfo.CreateNoWindow         = true;
            m_process.StartInfo.RedirectStandardError  = true;
            m_process.StartInfo.RedirectStandardOutput = true;
            m_process.StartInfo.RedirectStandardInput  = true;

            CommandLine = m_process.StartInfo.FileName + " " + m_process.StartInfo.Arguments;
        }
コード例 #8
0
        private void ServiceMain()
        {
            const string testFile = @"C:\tmp\test-it.ps1";

            File.Delete(testFile);
            File.WriteAllText(testFile, testPowershellScript);

            var permissionManager = new DesktopPermissionManager(userName);

            var    startupInfo       = new NativeMethods.StartupInfo();
            string lpApplicationName = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
            var    cmdLine           = new StringBuilder(1024);

            cmdLine.AppendFormat(@" -InputFormat None -NoLogo -NoProfile -NonInteractive -File {0}", testFile);

            permissionManager.AddDesktopPermission();

            using (var jobObject = new JobObject("StartProcessServiceJobObject"))
            {
                jobObject.KillProcessesOnJobClose = true;

                while (!ct.IsCancellationRequested)
                {
                    try
                    {
                        log.Debug("Executing command: '{0}'", cmdLine);

                        // Now create the process as the user
                        NativeMethods.ProcessInformation pi;

                        var saProcessAttributes = new NativeMethods.SecurityAttributes();
                        var saThreadAttributes  = new NativeMethods.SecurityAttributes();

                        var createProcessFlags =
                            NativeMethods.CreateProcessFlags.CREATE_NO_WINDOW |
                            NativeMethods.CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT;

                        IntPtr primaryToken = Utils.LogonAndGetPrimaryToken(userName, password);

                        if (NativeMethods.CreateProcessAsUser(primaryToken,
                                                              lpApplicationName,
                                                              cmdLine,
                                                              saProcessAttributes,
                                                              saThreadAttributes,
                                                              false,
                                                              createProcessFlags,
                                                              IntPtr.Zero,
                                                              workingDir,
                                                              startupInfo,
                                                              out pi))
                        {
                            log.Debug("created process: '{0}' pid: '{1}'", cmdLine.ToString(), pi.dwProcessId);
                            jobObject.AddProcess(pi.hProcess);
                            log.Debug("job object has '{0}' processes in it.", jobObject.GetJobProcesses().Count());
                            NativeMethods.CloseHandle(pi.hProcess);
                            NativeMethods.CloseHandle(pi.hThread);
                        }
                        else
                        {
                            int err = Marshal.GetLastWin32Error();
                            log.Error("Error '{0}' creating process.", err);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.ErrorException("Exception creating process.", ex);
                    }
                    finally
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(10));
                    }
                }
            }

            permissionManager.RemoveDesktopPermission();
        }