Beispiel #1
0
        private Process CreateProcess(ProcessSpec processSpec)
        {
            var process = new Process
            {
                EnableRaisingEvents = true,
                StartInfo           =
                {
                    FileName               = processSpec.Executable,
                    Arguments              = processSpec.EscapedArguments != null ? processSpec.EscapedArguments : ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(processSpec.Arguments),
                    UseShellExecute        = false,
                    WorkingDirectory       = processSpec.WorkingDirectory,
                    RedirectStandardOutput = processSpec.IsOutputCaptured || (processSpec.OnOutput != null),
                    RedirectStandardError  = processSpec.IsOutputCaptured,
                }
            };

            foreach (var env in processSpec.EnvironmentVariables)
            {
                process.StartInfo.Environment.Add(env.Key, env.Value);
            }

            SetEnvironmentVariable(process.StartInfo, "DOTNET_STARTUP_HOOKS", processSpec.EnvironmentVariables.DotNetStartupHooks, Path.PathSeparator);
            SetEnvironmentVariable(process.StartInfo, "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES", processSpec.EnvironmentVariables.AspNetCoreHostingStartupAssemblies, ';');

            return(process);
        }
Beispiel #2
0
        private void WatchRun(Func <MiruSolution, string> func)
        {
            var solutionFinder = new SolutionFinder(new FileSystem());
            var solution       = solutionFinder.FromDir(Directory.GetCurrentDirectory());

            var processRunner = new ProcessRunner(_reporter);

            // FIXME: npm and dotnet path finder:
            //  Win: where
            //  bash: which
            var webpack = new ProcessSpec()
            {
                Executable       = OS.IsWindows ? "c:\\Program Files\\nodejs\\npm.cmd" : "npm",
                WorkingDirectory = solution.Solution.AppDir,
                Arguments        = new[] { "--prefix", solution.Solution.AppDir.ToString(), "run", "watch" },
            };

            var dotnet = new ProcessSpec()
            {
                Executable       = "dotnet",
                WorkingDirectory = solution.Solution.AppDir,
                Arguments        = new[] { "watch", "run" }
            };

            var dotnetRunner  = processRunner.RunAsync(dotnet, _cts.Token);
            var webpackRunner = processRunner.RunAsync(webpack, _cts.Token);

            Task.WaitAll(dotnetRunner);
            Task.WaitAll(dotnetRunner, webpackRunner);
        }
        public void Start(IEnumerable <string> arguments, [CallerMemberName] string name = null)
        {
            if (!_prepared)
            {
                throw new InvalidOperationException($"Call {nameof(PrepareAsync)} first");
            }

            var args = new List <string>
            {
                Scenario.DotNetWatchPath,
            };

            args.AddRange(arguments);

            var spec = new ProcessSpec
            {
                Executable           = DotNetMuxer.MuxerPathOrDefault(),
                Arguments            = args,
                WorkingDirectory     = SourceDirectory,
                EnvironmentVariables =
                {
                    ["DOTNET_CLI_CONTEXT_VERBOSE"]      = bool.TrueString,
                    ["DOTNET_USE_POLLING_FILE_WATCHER"] = UsePollingWatcher.ToString(),
                },
            };

            Process = new AwaitableProcess(spec, _logger);
            Process.Start();
        }
Beispiel #4
0
            public void Stop_StillWorks_Eventually()
            {
                Container1 = CreateContainer(Container1Handle);
                string userid = null;

                Container1.ImpersonateContainerUser(() =>
                {
                    userid = WindowsIdentity.GetCurrent().User.ToString();
                });
                var pSpec = new ProcessSpec
                {
                    ExecutablePath     = "cmd.exe",
                    DisablePathMapping = true,
                    Arguments          = new string[] { @"/C ""FOR /L %% IN () DO ping 127.0.0.1 -n 2""" },
                };

                // START THE LONG RUNNING PROCESS
                var io          = new StringProcessIO();
                var process     = Container1.Run(pSpec, io);
                var realProcess = Process.GetProcessById(process.Id);

                Process containerHost = FindProcessByUserAndName(userid, "IronFrame.Host");

                ProcessInfoHelper.SuspendProcess(containerHost.Id);

                Container1.Stop(true);

                Assert.True(realProcess.HasExited);
            }
Beispiel #5
0
            public void StartAndStopLongRunningProcess()
            {
                Container1 = CreateContainer(Container1Handle);
                var pSpec = new ProcessSpec
                {
                    ExecutablePath     = "ping.exe",
                    DisablePathMapping = true,
                    Arguments          = new string[] { "127.0.0.1", "-n", "-1" },
                };

                // START THE LONG RUNNING PROCESS
                var io      = new StringProcessIO();
                var process = Container1.Run(pSpec, io);

                int  exitCode;
                bool exited = process.TryWaitForExit(500, out exitCode);

                // VERIFY IT HASNT EXITED YET
                Assert.False(exited);

                var actualProcess = Process.GetProcessById(process.Id);

                Assert.False(actualProcess.HasExited);

                // KILL THE PROCESS AND WAIT FOR EXIT
                process.Kill();
                exited = process.TryWaitForExit(2000, out exitCode);

                // VERIFY THE PROCESS WAS KILLED
                Assert.True(exited);
                Assert.True(actualProcess.HasExited);
                Assert.True(io.Output.ToString().Length > 0);
            }
Beispiel #6
0
            public void UniqueUserPerContainer()
            {
                Container1 = CreateContainer(Container1Handle);
                Container2 = CreateContainer(Container2Handle);

                var pSpec = new ProcessSpec
                {
                    ExecutablePath     = "whoami.exe",
                    DisablePathMapping = true,
                    Privileged         = false
                };

                var io1 = new StringProcessIO();
                var io2 = new StringProcessIO();

                Container1.Run(pSpec, io1).WaitForExit();
                Container2.Run(pSpec, io2).WaitForExit();

                var user1 = io1.Output.ToString();
                var user2 = io2.Output.ToString();

                Assert.NotEmpty(user1);
                Assert.NotEmpty(user2);
                Assert.NotEqual(user1, user2);
            }
Beispiel #7
0
        public void Start(IEnumerable <string> arguments, [CallerMemberName] string name = null)
        {
            if (!_prepared)
            {
                throw new InvalidOperationException($"Call {nameof(PrepareAsync)} first");
            }

            var args = new List <string>
            {
                Scenario.DotNetWatchPath,
            };

            args.AddRange(arguments);

            var dotnetPath = typeof(WatchableApp).Assembly.GetCustomAttributes <AssemblyMetadataAttribute>()
                             .Single(s => s.Key == "DotnetPath").Value;

            var spec = new ProcessSpec
            {
                Executable           = dotnetPath,
                Arguments            = args,
                WorkingDirectory     = SourceDirectory,
                EnvironmentVariables =
                {
                    ["DOTNET_CLI_CONTEXT_VERBOSE"]      = bool.TrueString,
                    ["DOTNET_USE_POLLING_FILE_WATCHER"] = UsePollingWatcher.ToString(),
                    ["DOTNET_ROOT"] = Directory.GetParent(dotnetPath).FullName,
                },
            };

            Process = new AwaitableProcess(spec, _logger);
            Process.Start();
        }
Beispiel #8
0
        public async Task <string> SendCommandAsync(string[] arguments, CancellationToken cancel)
        {
            string responseString;
            var    fileName = Path.Combine(hwiFolder, "hwi");

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
                !fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
            {
                fileName += ".exe";
            }

            ProcessSpec processSpec = new ProcessSpec()
            {
                Executable    = fileName,
                OutputCapture = new OutputCapture(),
            };

            processSpec.Arguments = new ReadOnlyCollection <string>(arguments);

            try
            {
                ProcessRunner processRunner = new ProcessRunner();
                var           exitCode      = await processRunner.RunAsync(processSpec, cancel);

                responseString = string.Concat(processSpec.OutputCapture.Lines);
                Logger.LogDebug($"Exit code: exit code: {exitCode}, Output: {responseString}");
            }
            catch (Exception ex)
            {
                Logger.LogError(default, ex, "Failed to call hwi");
Beispiel #9
0
            public void StartShortLivedTask()
            {
                Container1 = CreateContainer(Container1Handle);

                var pSpec = new ProcessSpec
                {
                    ExecutablePath     = "cmd.exe",
                    DisablePathMapping = true,
                    Arguments          = new string[] { "/C \"set CONTAINER_HANDLE && set PROC_ENV\"" },
                    Environment        = new Dictionary <string, string>
                    {
                        { "PROC_ENV", "VAL1" }
                    },
                };

                // RUN THE SHORT LIVED PROCESS
                var io      = new StringProcessIO();
                var process = Container1.Run(pSpec, io);

                int  exitCode;
                bool exited = process.TryWaitForExit(2000, out exitCode);

                var output = io.Output.ToString().Trim();
                var error  = io.Error.ToString().Trim();

                // VERIFY THE PROCESS RAN AND EXITED
                Assert.True(exited);
                Assert.Equal(exitCode, 0);

                // VERIFY THE ENVIRONMENT WAS SET
                Assert.Contains("CONTAINER_HANDLE=" + Container1.Handle, output);
                Assert.Contains("PROC_ENV=VAL1", output);
            }
Beispiel #10
0
        public async Task InitializeAsync_ConfiguresEnvironmentVariables()
        {
            // Arrange
            var applier = new DefaultDeltaApplier(Mock.Of <IReporter>())
            {
                SuppressNamedPipeForTests = true
            };
            var process = new ProcessSpec();
            var fileSet = new FileSet(null, new[]
            {
                new FileItem {
                    FilePath = "Test.cs"
                },
            });
            var context = new DotNetWatchContext {
                ProcessSpec = process, FileSet = fileSet, Iteration = 0
            };

            // Act
            await applier.InitializeAsync(context, default);

            // Assert
            Assert.Equal("debug", process.EnvironmentVariables["DOTNET_MODIFIABLE_ASSEMBLIES"]);
            Assert.NotEmpty(process.EnvironmentVariables["DOTNET_HOTRELOAD_NAMEDPIPE_NAME"]);
            Assert.NotEmpty(process.EnvironmentVariables.DotNetStartupHooks);
        }
Beispiel #11
0
        public async ValueTask ProcessAsync(DotNetWatchContext context, CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                var arguments = context.Iteration == 0 || (context.ChangedFile?.FilePath is string changedFile && changedFile.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase)) ?
                                new[] { "msbuild", "/t:Build", "/restore", "/nologo" } :
                new[] { "msbuild", "/t:Build", "/nologo" };

                var processSpec = new ProcessSpec
                {
                    Executable       = _muxer,
                    Arguments        = arguments,
                    WorkingDirectory = context.ProcessSpec.WorkingDirectory,
                };

                _reporter.Output("Building...");
                var exitCode = await _processRunner.RunAsync(processSpec, cancellationToken);

                context.FileSet = await _fileSetFactory.CreateAsync(cancellationToken);

                if (exitCode == 0)
                {
                    return;
                }

                // If the build fails, we'll retry until we have a successful build.
                using var fileSetWatcher = new FileSetWatcher(context.FileSet, _reporter);
                await fileSetWatcher.GetChangedFileAsync(cancellationToken, () => _reporter.Warn("Waiting for a file to change before restarting dotnet..."));
            }
        }
        public void WriteTarStreamToPath(Stream stream, IContainer container, string filePath)
        {
            var localPath = container.Directory.MapBinPath("tar.exe");

            if (!File.Exists(localPath))
            {
                File.Copy(TarArchiverPath("tar.exe"), localPath);
                File.Copy(TarArchiverPath("zlib1.dll"), container.Directory.MapBinPath("zlib1.dll"));
            }

            var tmpFilePath = container.Directory.MapBinPath(Path.GetRandomFileName());

            Directory.CreateDirectory(filePath);

            using (var tmpFile = File.Create(tmpFilePath))
            {
                stream.CopyTo(tmpFile);
            }
            var pSpec = new ProcessSpec()
            {
                ExecutablePath = localPath,
                Arguments      = new [] { "xf", tmpFilePath, "-C", filePath },
            };
            var process  = container.Run(pSpec, null);
            var exitCode = process.WaitForExit();

            if (exitCode != 0)
            {
                throw new Exception("Failed to extract stream");
            }
            File.Delete(tmpFilePath);
        }
Beispiel #13
0
            public void UserHasAProfileLoaded()
            {
                Container1 = CreateContainer(Container1Handle);
                var exePath        = Container1.Directory.MapUserPath("x509app.exe");
                var compilerPath   = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "csc.exe");
                var srcPath        = Path.Combine(Environment.CurrentDirectory, "..", "..", "fixtures", "x509app.cs");
                var compileProcess = new Process()
                {
                    StartInfo = new ProcessStartInfo()
                    {
                        FileName  = compilerPath,
                        Arguments = "/out:" + exePath + " " + srcPath,
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        UseShellExecute        = false,
                    }
                };

                compileProcess.Start();

                string output = compileProcess.StandardOutput.ReadToEnd();
                string err    = compileProcess.StandardOutput.ReadToEnd();

                compileProcess.WaitForExit();

                if (compileProcess.ExitCode != 0)
                {
                    logger.WriteLine(output);
                    logger.WriteLine(err);
                }

                Assert.Equal(0, compileProcess.ExitCode);

                var pSpec = new ProcessSpec
                {
                    ExecutablePath     = exePath,
                    DisablePathMapping = true,
                };

                var io = new StringProcessIO();

                Container1.Run(pSpec, io).WaitForExit();
                output = io.Output.ToString();
                err    = io.Error.ToString();

                if (output.Contains("FAILURE"))
                {
                    logger.WriteLine(output);
                    logger.WriteLine(err);
                }

                Assert.Contains("SUCCESS", output);
                var username = "******" + Container1.Id;

                Container1.Destroy();
                Container1Handle = null;
                var userDir = Path.Combine(Environment.GetEnvironmentVariable("SYSTEMDRIVE") + @"\", "Users", username);

                Assert.False(Directory.Exists(userDir));
            }
Beispiel #14
0
            public void Enforced()
            {
                Container1 = CreateContainer(Container1Handle);
                Container1.LimitDisk(10 * 1024);

                var pSpec = new ProcessSpec
                {
                    ExecutablePath     = "cmd",
                    DisablePathMapping = true,
                    Privileged         = false,
                    WorkingDirectory   = Container1.Directory.UserPath,
                };
                var io1 = new StringProcessIO();

                var passed = 0;
                var failed = 0;

                for (int i = 0; i < 20; i++)
                {
                    pSpec.Arguments = new[] { "/C", "echo Hi Bob > bob" + i + ".txt" };
                    var proc     = Container1.Run(pSpec, io1);
                    var exitCode = proc.WaitForExit();

                    if (exitCode == 0)
                    {
                        passed++;
                    }
                    else
                    {
                        failed++;
                    }
                }
                Assert.Equal(13, passed);
                Assert.Equal(7, failed);
            }
Beispiel #15
0
        public async ValueTask ProcessAsync(DotNetWatchContext context, CancellationToken cancellationToken)
        {
            using var fileSetWatcher = new FileSetWatcher(context.FileSet, _reporter);
            while (!cancellationToken.IsCancellationRequested)
            {
                var arguments = context.RequiresMSBuildRevaluation ?
                                new[] { "msbuild", "/t:Build", "/restore", "/nologo" } :
                new[] { "msbuild", "/t:Build", "/nologo" };

                var processSpec = new ProcessSpec
                {
                    Executable       = _muxer,
                    Arguments        = arguments,
                    WorkingDirectory = context.ProcessSpec.WorkingDirectory,
                };

                _reporter.Output("Building...");
                var exitCode = await _processRunner.RunAsync(processSpec, cancellationToken);

                if (exitCode == 0)
                {
                    return;
                }

                // If the build fails, we'll retry until we have a successful build.
                context.ChangedFile = await fileSetWatcher.GetChangedFileAsync(cancellationToken, () => _reporter.Warn("Waiting for a file to change before restarting dotnet..."));
            }
        }
Beispiel #16
0
 public AwaitableProcess(ProcessSpec spec, ITestOutputHelper logger)
 {
     _spec   = spec;
     _logger = logger;
     _source = new BufferBlock <string>();
     _lines  = new List <string>();
     _exited = new TaskCompletionSource <int>();
 }
Beispiel #17
0
 private void OverrideEnvPort(ProcessSpec processSpec)
 {
     if (processSpec.Environment.ContainsKey("PORT"))
     {
         var hostport = container.GetProperty("ContainerPort:" + processSpec.Environment["PORT"]);
         processSpec.Environment["PORT"] = hostport;
     }
 }
 public AwaitableProcess(ProcessSpec spec, ITestOutputHelper logger)
 {
     _spec   = spec;
     _logger = logger;
     _source = new BufferBlock <string>();
     _lines  = new List <string>();
     _exited = new TaskCompletionSource <int>(TaskCreationOptions.RunContinuationsAsynchronously);
 }
Beispiel #19
0
        public static async Task <Project> FromFileAsync(string file, string framework = null, string configuration = null, string runtime = null, CancellationToken cancellationToken = default)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            var args = new List <string>
            {
                "msbuild",
                file,
                "/nologo",
                "/v:n",
                "/t:" + GetMetadataTargetName,
            };

            if (framework != null)
            {
                args.Add("/p:TargetFramework=" + framework);
            }

            if (configuration != null)
            {
                args.Add("/p:Configuration=" + configuration);
            }

            if (runtime != null)
            {
                args.Add("/p:RuntimeIdentifier=" + runtime);
            }

            var capture = new OutputCapture();

            var processSpec = new ProcessSpec
            {
                Executable    = "dotnet",
                Arguments     = args,
                OutputCapture = capture
            };

            Reporter.WriteVerbose($"Running MSBuild target '{GetMetadataTargetName}' on '{file}'");

            var exitCode = await ProcessRunner.Default.RunAsync(processSpec, cancellationToken);

            if (exitCode != 0)
            {
                DumpMSBuildOutput(capture);
                throw new CommandException("Unable to retrieve project metadata. Please ensure it's an MSBuild-based .NET Core project which references " + BundleBuilderProxy.BundlingAssemblyName + " 3.0.0 or newer explicitly. " +
                                           "If it's a multi-targeted project, you need to select one of the target frameworks by the '--framework' option.");
            }

            var metadata = capture.Lines
                           .Select(line => Regex.Match(line, @"^\s*Bundling\.(\w+)=(.*)$"))
                           .Where(match => match.Success)
                           .ToDictionary(match => match.Groups[1].Value, match => match.Groups[2].Value);

            return(FromMetadata(metadata, file, framework, configuration, runtime));
        }
Beispiel #20
0
        public async Task BuildAsync(CancellationToken cancellationToken)
        {
            var args = new List <string> {
                "build"
            };

            if (_file != null)
            {
                args.Add(_file);
            }

            // TODO: Only build for the first framework when unspecified
            if (_framework != null)
            {
                args.Add("--framework");
                args.Add(_framework);
            }

            if (_configuration != null)
            {
                args.Add("--configuration");
                args.Add(_configuration);
            }

            if (_runtime != null)
            {
                args.Add("--runtime");
                args.Add(_runtime);
            }

            args.Add("/v:q");
            args.Add("/nologo");

            var capture = new OutputCapture();

            var processSpec = new ProcessSpec
            {
                Executable    = "dotnet",
                Arguments     = args,
                OutputCapture = capture
            };

            Reporter.WriteInformation("Build started...");

            var exitCode = await ProcessRunner.Default.RunAsync(processSpec, cancellationToken);

            if (exitCode != 0)
            {
                DumpMSBuildOutput(capture);
                throw new CommandException("Build failed.");
            }

            Reporter.WriteInformation("Build succeeded.");
            Reporter.WriteInformation(string.Empty);
        }
Beispiel #21
0
            public void StartAndStopLauncher()
            {
                Container1 = CreateContainer(Container1Handle);
                var pSpec = new ProcessSpec
                {
                    ExecutablePath     = @"cmd.exe",
                    DisablePathMapping = true,
                    Arguments          = new string[] { "/C ping.exe 127.0.0.1 -n 1000" },
                };

                // START THE LONG RUNNING PROCESS
                var io      = new StringProcessIO();
                var process = Container1.Run(pSpec, io);

                int  exitCode;
                bool exited = process.TryWaitForExit(500, out exitCode);

                // VERIFY IT HASNT EXITED YET
                Assert.False(exited);

                var actualProcess = Process.GetProcessById(process.Id);

                var childProcess = Process.GetProcesses().FirstOrDefault(x =>
                {
                    // Get some basic information about the process
                    PROCESS_BASIC_INFORMATION pbi = new PROCESS_BASIC_INFORMATION();
                    try
                    {
                        uint bytesWritten;
                        NtQueryInformationProcess(x.Handle,
                                                  0, ref pbi, (uint)Marshal.SizeOf(pbi),
                                                  out bytesWritten); // == 0 is OK

                        // Is it a child process of the process we're trying to terminate?
                        return((int)pbi.InheritedFromUniqueProcessId == process.Id);
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                });

                Assert.False(actualProcess.HasExited);
                Assert.False(childProcess.HasExited);

                // KILL THE PROCESS AND WAIT FOR EXIT
                process.Kill();
                exited = process.TryWaitForExit(2000, out exitCode);

                // VERIFY THE PROCESS WAS KILLED
                Assert.True(exited);
                Assert.True(actualProcess.HasExited);
                Assert.True(childProcess.HasExited);
                Assert.True(io.Output.ToString().Length > 0);
            }
Beispiel #22
0
 private static void CopyProcessSpecEnvVariables(ProcessSpec processSpec, string[] envStrings)
 {
     if (envStrings == null)
     {
         return;
     }
     foreach (var kv in envStrings)
     {
         string[] arr = kv.Split(new Char[] { '=' }, 2);
         processSpec.Environment[arr[0]] = arr[1];
     }
 }
Beispiel #23
0
        private void Form1_Load(object sender, EventArgs e)
        {
            Chart_spec.Series(0).Clear();
            Chart_spec.Series(1).Clear();

            Chart_spec.Series(1).VerticalAxisCustom = 0;
            processSpec                = new ProcessSpec();
            processSpec.OnAddLines    += chart_Spectrum_addLine;
            processSpec.setMinMaxWave += resetChartMinMax;
            processSpec.addSpecLine   += addSpecSeries;

            fittingControl1.stopGetSpec      += StopThread;
            fittingControl1.selectTablePage2 += selectTablePage;
            fittingControl1.setRemarks       += setRemarks;
            fittingControl1.addSpecLine      += addSpecSeries;
            fittingControl1.setSignEvent     += addSignFittingChart;
            string str = "select max(ID) from JewDataTable  ";
            string obj = SqliteHelper.ExecuteScalar(str).ToString();

            //int id = (int.Parse(obj) + 1);
            processSpec.JewID = (int.Parse(obj) + 1);
            addJewDataControl1.processSpec = processSpec;
            addJewDataControl1.loadCreatorClass();
            fittingControl1.processSpec = processSpec;


            bool connectState = processSpec.connectSpectrometer();

            if (connectState)
            {
                settoolStripStatusLabel1Text("成功连接光谱仪");
            }
            else
            {
                settoolStripStatusLabel1Text("未发现光谱仪");
            }

            int gridindex = this.dataGridView1.Rows.Add();

            this.dataGridView1.Rows[gridindex].Cells[0].Value           = true;
            this.dataGridView1.Rows[gridindex].Cells[1].Style.BackColor = Color.Red;
            this.dataGridView1.Rows[gridindex].Cells[2].Value           = "当前谱图";
            this.dataGridView1.Rows[gridindex].Cells[2].ReadOnly        = true;
            if (processSpec.IsConn)
            {
                start             = true;
                getSpectrumThread = new Thread(new ThreadStart(run));
                getSpectrumThread.Start();
                getSpectrumThread.IsBackground = true;
                dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black;
            }
            Chart_spec.Tools.Items[0].Active = false;
        }
Beispiel #24
0
            public StartGuard()
            {
                Container1 = CreateContainer(Container1Handle);
                var pSpec = new ProcessSpec
                {
                    ExecutablePath     = @"cmd.exe",
                    DisablePathMapping = true,
                    Arguments          = new string[] { "/C ping.exe 127.0.0.1 -n 1000" },
                };
                var io = new StringProcessIO();

                Container1.Run(pSpec, io);
            }
Beispiel #25
0
        // May not be necessary in the future. See https://github.com/dotnet/corefx/issues/12039
        public async Task <int> RunAsync(ProcessSpec processSpec, CancellationToken cancellationToken)
        {
            Ensure.NotNull(processSpec, nameof(processSpec));

            int exitCode;

            var stopwatch = new Stopwatch();

            using (var process = CreateProcess(processSpec))
                using (var processState = new ProcessState(process, _reporter))
                {
                    cancellationToken.Register(() => processState.TryKill());

                    process.OutputDataReceived += (_, a) =>
                    {
                        if (!string.IsNullOrEmpty(a.Data))
                        {
                            processSpec.OutputCapture.AddLine(a.Data);
                        }
                    };
                    process.ErrorDataReceived += (_, a) =>
                    {
                        if (!string.IsNullOrEmpty(a.Data))
                        {
                            processSpec.OutputCapture.AddLine(a.Data);
                        }
                    };

                    stopwatch.Start();
                    process.Start();

                    _reporter.Verbose($"Started '{processSpec.Executable}' with process id {process.Id}");

                    if (processSpec.IsOutputCaptured)
                    {
                        process.BeginErrorReadLine();
                        process.BeginOutputReadLine();
                        await processState.Task;
                    }
                    else
                    {
                        await processState.Task;
                    }

                    exitCode = process.ExitCode;
                    stopwatch.Stop();
                    _reporter.Verbose($"Process id {process.Id} ran for {stopwatch.ElapsedMilliseconds}ms");
                }

            return(exitCode);
        }
Beispiel #26
0
        protected TaskCommandResult RunProcess(string workingDirectory, string executable, string[] processArguments)
        {
            string exePath = this.Container.ConvertToUserPathWithin(executable);

            string workingDir = String.IsNullOrWhiteSpace(workingDirectory)
                ? this.Container.Directory.UserPath
                : this.Container.ConvertToUserPathWithin(workingDirectory);

            var environment = this.CommandArgs.Environment.ToDictionary(kv => kv.Key,
                                                                        kv => this.Container.ConvertToUserPathWithin(kv.Value));

            var privileged = this.CommandArgs.Privileged;

            var processArgs = processArguments ?? new string[0];

            log.Trace("Running process{0} (WorkingDir {1}): {2} Args: {3}",
                      privileged ? " (privileged)" : " (non-privileged)",
                      workingDir,
                      exePath,
                      string.Join(" ", processArgs)
                      );

            var spec = new ProcessSpec
            {
                ExecutablePath     = exePath,
                Arguments          = processArguments,
                WorkingDirectory   = workingDir,
                Environment        = environment,
                DisablePathMapping = true,
                Privileged         = privileged,
            };

            IContainerProcess process = null;

            process = this.Container.Run(spec, this.IO);

            log.Trace("Process ID: '{0}'", process.Id);

            // These aren't in a using block intentionally - we don't want to
            // delete the files because they might be useful for debugging
            // if the app crashes.
            CreatePidLog(process.Id);
            CreateProcessEnvLog(process.Environment);

            int exitCode = process.WaitForExit();

            log.Trace("Process ended with exit code: {0}", exitCode);

            return(new TaskCommandResult(exitCode, null, null));
        }
            public void CanGetExitCode()
            {
                var spec = new ProcessSpec
                {
                    ExecutablePath = "run.bat",
                    Arguments      = new[] { "exit 100" }
                };
                var io = new TestProcessIO();

                var process  = Container.Run(spec, io);
                var exitCode = process.WaitForExit();

                Assert.Equal(100, exitCode);
            }
Beispiel #28
0
        public void Start(IEnumerable <string> arguments, [CallerMemberName] string name = null)
        {
            if (!_prepared)
            {
                throw new InvalidOperationException($"Call {nameof(PrepareAsync)} first");
            }

            var args = new List <string>
            {
                Scenario.DotNetWatchPath,
            };

            args.AddRange(DotnetWatchArgs);
            args.AddRange(arguments);

            var dotnetPath = "dotnet";

            // Fallback to embedded path to dotnet when not on helix
            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("helix")))
            {
                dotnetPath = typeof(WatchableApp).Assembly.GetCustomAttributes <AssemblyMetadataAttribute>()
                             .Single(s => s.Key == "DotnetPath").Value;
            }

            var spec = new ProcessSpec
            {
                Executable           = dotnetPath,
                Arguments            = args,
                WorkingDirectory     = SourceDirectory,
                EnvironmentVariables =
                {
                    ["DOTNET_USE_POLLING_FILE_WATCHER"] = UsePollingWatcher.ToString(),
                    ["__DOTNET_WATCH_RUNNING_AS_TEST"]  = "true",
                },
            };

            foreach (var env in EnvironmentVariables)
            {
                spec.EnvironmentVariables.Add(env.Key, env.Value);
            }

            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("helix")))
            {
                spec.EnvironmentVariables["DOTNET_ROOT"] = Directory.GetParent(dotnetPath).FullName;
            }

            Process = new AwaitableProcess(spec, _logger);
            Process.Start();
        }
Beispiel #29
0
        public override async Task Run(IConsole console, CommandArguments arguments, CancellationToken token)
        {
            var siteName = arguments.Name ?? _envAppName;
            var sitePort = arguments.Port ?? _envPort;

            if (string.IsNullOrEmpty(siteName))
            {
                throw new Exception("Argument 'name' is required.");
            }

            if (!sitePort.HasValue)
            {
                throw new Exception("Argument 'port' is required.");
            }

            var iisExpressPath = await IISExpressDiscovery.GetIISExpressPath();

            var siteConfig = new SiteConfig(siteName, arguments.Path.FullName, sitePort.Value);
            var configPath = await siteConfig.Create(TempDirectory.Value);

            if (!arguments.NoBuild)
            {
                var buildRes = await _msBuild.BuildAndGetArtifactPath(arguments.Path.FullName, arguments.SolutionPath?.FullName);

                if (!buildRes.Success)
                {
                    if (!string.IsNullOrEmpty(buildRes.Error))
                    {
                        throw new Exception(buildRes.Error);
                    }

                    throw new Exception("Failed to build website");
                }
            }

            var spec = new ProcessSpec
            {
                Executable       = iisExpressPath,
                Arguments        = $"/config:{configPath} /site:{siteName}",
                WorkingDirectory = arguments.Path.FullName,
                OutputData       = data => console.Out.WriteLine(data),
                ErrorData        = data => console.Error.WriteLine(data),
                OnStart          = pid => console.Out.WriteLine($"IIS Express Started at PID {pid}"),
                OnStop           = code => console.Out.WriteLine($"IIS Express Stopped with status code {code}"),
                CreateWindow     = false
            };

            await ProcessUtil.RunAsync(spec, token, throwOnError : false);
        }
Beispiel #30
0
        private Task <ProcessResult> StartProcess(IConsole console, CommandArguments arguments, string dir, string file, CancellationToken token)
        {
            var spec = new ProcessSpec
            {
                Executable       = Path.Join(dir, file),
                Arguments        = arguments.Arguments,
                WorkingDirectory = dir,
                OutputData       = data => console.Out.WriteLine(data),
                ErrorData        = data => console.Error.WriteLine(data),
                OnStart          = pid => console.Out.WriteLine($"{file} Started at PID {pid}"),
                OnStop           = code => console.Out.WriteLine($"{file} Stopped with status code {code}")
            };

            return(ProcessUtil.RunAsync(spec, token, throwOnError: false));
        }
            public void FindAndKillProcess()
            {
                Container1 = CreateContainer(Container1Handle);
                var pSpec = new ProcessSpec
                {
                    ExecutablePath = "cmd.exe",
                    DisablePathMapping = true,
                    Arguments = new string[] { @"/C ""FOR /L %% IN () DO ping 127.0.0.1 -n 2""" },
                };

                // START THE LONG RUNNING PROCESS
                var io = new StringProcessIO();
                var process = Container1.Run(pSpec, io);
                var foundProcessByPid = Container1.FindProcessById(process.Id);

                // KILL THE PROCESS AND WAIT FOR EXIT
                foundProcessByPid.Kill();
                int exitCode;
                var exited = process.TryWaitForExit(2000, out exitCode);

                // VERIFY THE PROCESS WAS KILLED
                Assert.True(exited);
            }
            public void Enforced()
            {
                Container1 = CreateContainer(Container1Handle);
                Container1.LimitDisk(10 * 1024);

                var pSpec = new ProcessSpec
                {
                    ExecutablePath = "cmd",
                    DisablePathMapping = true,
                    Privileged = false,
                    WorkingDirectory = Container1.Directory.UserPath,
                };
                var io1 = new StringProcessIO();

                var passed = 0;
                var failed = 0;
                for (int i = 0; i < 20; i++)
                {
                    pSpec.Arguments = new[] { "/C", "echo Hi Bob > bob" + i + ".txt" };
                    var proc = Container1.Run(pSpec, io1);
                    var exitCode = proc.WaitForExit();

                    if (exitCode == 0)
                    {
                        passed++;
                    }
                    else
                    {
                        failed++;
                    }
                }
                Assert.Equal(13, passed);
                Assert.Equal(7, failed);
            }
            public void RunExecutablePathsWithDriveLetter()
            {
                Container1 = CreateContainer(Container1Handle);

                var pSpec = new ProcessSpec
                {
                    ExecutablePath = @"C:\Windows\System32\cmd.exe",
                    DisablePathMapping = false,
                    Arguments = new string[] { "/c", "echo", "test-run" }
                };

                var io = new StringProcessIO();
                Container1.Run(pSpec, io).WaitForExit();
                var output = io.Output.ToString();

                Assert.Contains("test-run", output);
            }
            public void StartAndStopLauncher()
            {
                Container1 = CreateContainer(Container1Handle);
                var pSpec = new ProcessSpec
                {
                    ExecutablePath = @"cmd.exe",
                    DisablePathMapping = true,
                    Arguments = new string[] { "/C ping.exe 127.0.0.1 -n 1000" },
                };

                // START THE LONG RUNNING PROCESS
                var io = new StringProcessIO();
                var process = Container1.Run(pSpec, io);

                int exitCode;
                bool exited = process.TryWaitForExit(500, out exitCode);

                // VERIFY IT HASNT EXITED YET
                Assert.False(exited);

                var actualProcess = Process.GetProcessById(process.Id);

                var childProcess = Process.GetProcesses().FirstOrDefault(x =>
                {
                    // Get some basic information about the process
                    PROCESS_BASIC_INFORMATION pbi = new PROCESS_BASIC_INFORMATION();
                    try
                    {
                        uint bytesWritten;
                        NtQueryInformationProcess(x.Handle,
                            0, ref pbi, (uint)Marshal.SizeOf(pbi),
                            out bytesWritten); // == 0 is OK

                        // Is it a child process of the process we're trying to terminate?
                        return (int)pbi.InheritedFromUniqueProcessId == process.Id;
                    }
                    catch (Exception)
                    {
                        return false;
                    }
                });

                Assert.False(actualProcess.HasExited);
                Assert.False(childProcess.HasExited);

                // KILL THE PROCESS AND WAIT FOR EXIT
                process.Kill();
                exited = process.TryWaitForExit(2000, out exitCode);

                // VERIFY THE PROCESS WAS KILLED
                Assert.True(exited);
                Assert.True(actualProcess.HasExited);
                Assert.True(childProcess.HasExited);
                Assert.True(io.Output.ToString().Length > 0);
            }
            public void StartAndStopLongRunningProcess()
            {
                Container1 = CreateContainer(Container1Handle);
                var pSpec = new ProcessSpec
                {
                    ExecutablePath = "ping.exe",
                    DisablePathMapping = true,
                    Arguments = new string[] { "127.0.0.1", "-n", "-1" },
                };

                // START THE LONG RUNNING PROCESS
                var io = new StringProcessIO();
                var process = Container1.Run(pSpec, io);

                int exitCode;
                bool exited = process.TryWaitForExit(500, out exitCode);

                // VERIFY IT HASNT EXITED YET
                Assert.False(exited);

                var actualProcess = Process.GetProcessById(process.Id);
                Assert.False(actualProcess.HasExited);

                // KILL THE PROCESS AND WAIT FOR EXIT
                process.Kill();
                exited = process.TryWaitForExit(2000, out exitCode);

                // VERIFY THE PROCESS WAS KILLED
                Assert.True(exited);
                Assert.True(actualProcess.HasExited);
                Assert.True(io.Output.ToString().Length > 0);
            }
            public void StartShortLivedTask()
            {
                Container1 = CreateContainer(Container1Handle);

                var pSpec = new ProcessSpec
                {
                    ExecutablePath = "cmd.exe",
                    DisablePathMapping = true,
                    Arguments = new string[] { "/C \"set CONTAINER_HANDLE && set PROC_ENV\"" },
                    Environment = new Dictionary<string, string>
                    {
                        {"PROC_ENV", "VAL1"}
                    },
                };

                // RUN THE SHORT LIVED PROCESS
                var io = new StringProcessIO();
                var process = Container1.Run(pSpec, io);

                int exitCode;
                bool exited = process.TryWaitForExit(2000, out exitCode);

                var output = io.Output.ToString().Trim();
                var error = io.Error.ToString().Trim();

                // VERIFY THE PROCESS RAN AND EXITED
                Assert.True(exited);
                Assert.Equal(exitCode, 0);

                // VERIFY THE ENVIRONMENT WAS SET
                Assert.Contains("CONTAINER_HANDLE=" + Container1.Handle, output);
                Assert.Contains("PROC_ENV=VAL1", output);
            }
            public void Stop_StillWorks_Eventually()
            {
                Container1 = CreateContainer(Container1Handle);
                string userid = null;
                Container1.ImpersonateContainerUser(() =>
                {
                    userid = WindowsIdentity.GetCurrent().User.ToString();
                });
                var pSpec = new ProcessSpec
                {
                    ExecutablePath = "cmd.exe",
                    DisablePathMapping = true,
                    Arguments = new string[] { @"/C ""FOR /L %% IN () DO ping 127.0.0.1 -n 2""" },
                };

                // START THE LONG RUNNING PROCESS
                var io = new StringProcessIO();
                var process = Container1.Run(pSpec, io);
                var realProcess = Process.GetProcessById(process.Id);

                Process containerHost = FindProcessByUserAndName(userid, "IronFrame.Host");
                ProcessInfoHelper.SuspendProcess(containerHost.Id);

                Container1.Stop(true);

                Assert.True(realProcess.HasExited);
            }
 public StartGuard()
 {
     Container1 = CreateContainer(Container1Handle);
     var pSpec = new ProcessSpec
     {
         ExecutablePath = @"cmd.exe",
         DisablePathMapping = true,
         Arguments = new string[] { "/C ping.exe 127.0.0.1 -n 1000" },
     };
     var io = new StringProcessIO();
     Container1.Run(pSpec, io);
 }
            public void UniqueUserPerContainer()
            {
                Container1 = CreateContainer(Container1Handle);
                Container2 = CreateContainer(Container2Handle);

                var pSpec = new ProcessSpec
                {
                    ExecutablePath = "whoami.exe",
                    DisablePathMapping = true,
                    Privileged = false
                };

                var io1 = new StringProcessIO();
                var io2 = new StringProcessIO();

                Container1.Run(pSpec, io1).WaitForExit();
                Container2.Run(pSpec, io2).WaitForExit();

                var user1 = io1.Output.ToString();
                var user2 = io2.Output.ToString();

                Assert.NotEmpty(user1);
                Assert.NotEmpty(user2);
                Assert.NotEqual(user1, user2);
            }
            public void ContainerUserInContainerGroup()
            {
                Container1 = CreateContainer(Container1Handle);

                var pSpec = new ProcessSpec
                {
                    ExecutablePath = "whoami.exe",
                    DisablePathMapping = true,
                    Arguments = new string[] { "/GROUPS" }
                };

                var io = new StringProcessIO();
                Container1.Run(pSpec, io).WaitForExit();
                var groupOutput = io.Output.ToString();

                Assert.Contains(UserGroupName, groupOutput);
            }