private int DoRunProcessGetExit(string escapedCommand, IEnumerable <KeyValuePair <string, object?> > args) { var finalCommand = $"{escapedCommand};exit $LASTEXITCODE"; var startInfo = SetupArgs(finalCommand, args); var exitCode = runner.Run(startInfo); return(exitCode); }
/// <summary> /// Get the files that need to be synced. /// </summary> /// <returns>A SyncInfo with the info.</returns> public async Task <SyncInfo> SyncInfo() { return(await Task.Run <SyncInfo>(() => { var startInfo = new ProcessStartInfo("git") { ArgumentList = { "fetch", "--all" }, WorkingDirectory = repo.Info.WorkingDirectory }; var exit = processRunner.Run(startInfo); if (exit != 0) { throw new InvalidOperationException($"Exit code {exit} running git fetch"); } var head = repo.Head.Commits.First(); //No tracked branch, cannot sync anything, return empty result if (repo.Head.TrackedBranch == null) { return new SyncInfo() { HasUncomittedChanges = commitRepo.HasUncommittedChanges(), AheadBy = 0, BehindBy = 0, AheadHistory = Enumerable.Empty <History>(), BehindHistory = Enumerable.Empty <History>() }; } //Head has a tracked branch, can handle sync var tracked = repo.Head.TrackedBranch.Commits.First(); var divergence = repo.ObjectDatabase.CalculateHistoryDivergence(head, tracked); var aheadCommits = repo.Commits.QueryBy(new CommitFilter() { SortBy = CommitSortStrategies.Reverse | CommitSortStrategies.Time, IncludeReachableFrom = divergence.One, ExcludeReachableFrom = divergence.CommonAncestor }); var behindCommits = repo.Commits.QueryBy(new CommitFilter() { SortBy = CommitSortStrategies.Reverse | CommitSortStrategies.Time, IncludeReachableFrom = divergence.Another, ExcludeReachableFrom = divergence.CommonAncestor }); return new SyncInfo() { HasUncomittedChanges = commitRepo.HasUncommittedChanges(), AheadBy = divergence.AheadBy.GetValueOrDefault(), BehindBy = divergence.BehindBy.GetValueOrDefault(), AheadHistory = aheadCommits.Select(c => new History(c)), BehindHistory = behindCommits.Select(c => new History(c)) }; })); }
/// <summary> /// Add a rule to track. /// </summary> /// <param name="networkRule"></param> /// <exception cref="Exception"></exception> public void AddRule(NetworkRule networkRule) { // Build standard process options. var commandOptions = NetworkBuilder.BuildProcessOptions("iptables"); // Get local interface information var interfaceInformation = GetDefaultInterface(); // Determine how to handle the rule. switch (networkRule.Type) { // MASQUERADE case NetworkRuleType.Masquerade: // Assign the argument. commandOptions.Arguments = ("-A " + NetworkBuilder.BuildTemplate( NetworkRuleTemplates.MASQUERADE, networkRule, interfaceInformation ) ) // Convert to string array. .Split(" "); // Tell the console _logger.LogInformation("Created MASQUERADE rule for {0}", networkRule.Network); break; // SNAT case NetworkRuleType.SourceNetworkAddressTranslation: // Assign the argument commandOptions.Arguments = ("-A " + NetworkBuilder.BuildTemplate( NetworkRuleTemplates.SNAT, networkRule, interfaceInformation ) ) // Convert to string array. .Split(" "); // Tell the console. _logger.LogInformation("Created SNAT rule for {0}", networkRule.Network); break; // Unhandled Exception default: _logger.LogError("Firewall environment was provided undefined rule type."); throw FirewallExceptions.UnhandledNetworkRuleException(); } // Run the process. _processRunner.Run(commandOptions); // Track the rule. _rules.Add(networkRule); }
public void ConfigureTentacle() { var tentacleDeploymentsPath = _config.TentacleDeploymentsPath; _processRunner.Run(_tentaclePath, string.Format("create-instance {0} --config \"{1}\" --console", InstanceArg, Path.Combine(_tentacleInstallPath, "Tentacle.config"))); _processRunner.Run(_tentaclePath, string.Format("new-certificate {0} --console", InstanceArg)); _processRunner.Run(_tentaclePath, string.Format("configure {0} --home \"{1}\" --console", InstanceArg, tentacleDeploymentsPath.Substring(0, tentacleDeploymentsPath.Length - 1))); _processRunner.Run(_tentaclePath, string.Format("configure {0} --app \"{1}\" --console", InstanceArg, Path.Combine(tentacleDeploymentsPath, "Applications"))); _processRunner.Run(_tentaclePath, string.Format("register-with {0} --server \"{1}\" --environment \"{2}\" --role \"{3}\" --apiKey \"{4}\" --name \"{5}\" --comms-style TentacleActive --force --console", InstanceArg, _config.OctopusServer, _config.TentacleEnvironment, _config.TentacleRole, _config.OctopusApiKey, _machineName)); _processRunner.Run(_tentaclePath, string.Format("service {0} --install --start --console", InstanceArg)); }
public void StandardOutput() { ProcessResult result = m_runner.Run( @"C:\Windows\System32\cmd.exe", "/C echo hello world", TimeSpan.FromSeconds(10) ); Assert.AreEqual(0, result.ExitCode); Assert.AreEqual("hello world", result.StandardOutput.Trim()); Assert.IsEmpty(result.StandardError); }
public async Task GenerateReturnsImagesForSuccessfulProcesses() { int i = 0; _fileService.Exists(Arg.Any <string>()).Returns(true); _processRunner.Run(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <TimeSpan>()) .Returns(x => new ProcessResult { ExitCode = i++ == 0 ? 1 : 0 }); var result = await _imageGenerator.Generate(_transcodeJob); Assert.AreEqual(_imageCount - 1, result?.Count); }
public async Task <Stream> GetPng(string id) { var imagePath = await Task.Factory.StartNew(() => { // image path from hash var imageFsPath = GetCachePath(id, pngExtension); lock (cacheDir) { // image exists ? if (!File.Exists(imageFsPath)) { var pumlFsPath = GetCachePath(id, pumlExtension); var r = processRunner.Run(javaExe, new[] { "-jar", plantumlJar, "-o", cacheDir, pumlFsPath }).Result; if (r.ExitCode != 0) { throw new Exception($@"plantuml failed: ExitCode: {r.ExitCode} Output: {r.Output} Error: {r.Error} " ); } } } return(imageFsPath); }); return(File.OpenRead(imagePath)); }
public int Run(ProcessStartInfo startInfo, ProcessEvents?events = null) { return(child.Run(startInfo, new ProcessEvents() { ProcessCreated = events?.ProcessCreated, ProcessCompleted = events?.ProcessCompleted, ErrorDataReceived = (s, e) => { events?.ErrorDataReceived?.Invoke(s, e); if (e.AllowOutput && !String.IsNullOrEmpty(e.DataReceivedEventArgs.Data)) { logger.LogWarning(e.DataReceivedEventArgs.Data); } }, OutputDataReceived = (s, e) => { events?.OutputDataReceived?.Invoke(s, e); if (e.AllowOutput && !String.IsNullOrEmpty(e.DataReceivedEventArgs.Data)) { logger.LogInformation(e.DataReceivedEventArgs.Data); } } })); }
public Task <CreateProcessResult> ExecuteAsync(CreateProcessParams p) { var runSpec = new ProcessRunSpec { ExecutablePath = p.executablePath, Arguments = p.arguments, Environment = p.environment, WorkingDirectory = p.workingDirectory, OutputCallback = (data) => { processTracker.HandleProcessData(p.key, ProcessDataType.STDOUT, data); }, ErrorCallback = (data) => { processTracker.HandleProcessData(p.key, ProcessDataType.STDERR, data); }, }; var process = processRunner.Run(runSpec); processTracker.TrackProcess(p.key, process); var result = new CreateProcessResult { id = process.Id, }; return(Task.FromResult(result)); }
async Task<T> RunFFprobe<T>(string fileName, string options) { T result = default(T); var escapedFileName = _processUtility.EscapeFilePath(fileName); var arguments = $"-loglevel error -print_format json {options} -i {escapedFileName}"; try { var processResult = await _processRunner.Run(_ffprobeFileName, arguments, _timeout); if (!string.IsNullOrWhiteSpace(processResult.OutputData)) { result = DeserializeOutput<T>(processResult.OutputData, true); } else { Trace.WriteLine("No ffprobe data on stdout to parse."); } } catch (ArgumentException ex) { Trace.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); } catch (InvalidOperationException ex) { Trace.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); } return result; }
public IContainerHostClient StartContainerHost(string containerId, IContainerDirectory directory, JobObject jobObject, NetworkCredential credentials) { CopyHostToContainer(directory); var hostRunSpec = new ProcessRunSpec { ExecutablePath = directory.MapBinPath(dependencyHelper.ContainerHostExe), Arguments = new[] { containerId }, BufferedInputOutput = true, WorkingDirectory = directory.UserPath, Credentials = credentials, }; // Order here is important. // - Start the process // - Add the process to the job object // - Verify that the process is healthy // - Start the RPC message pump // // We need to ensure that the host process cannot create any new processes before // it's added to the job object. var hostProcess = processRunner.Run(hostRunSpec); jobObject.AssignProcessToJob(hostProcess.Handle); WaitForProcessToStart(hostProcess, HostProcessStartTimeout); var messageTransport = MessageTransport.Create(hostProcess.StandardOutput, hostProcess.StandardInput); var messagingClient = MessagingClient.Create(async message => { await messageTransport.PublishRequestAsync(message); }); messageTransport.SubscribeResponse(message => { messagingClient.PublishResponse(message); return(Task.FromResult(0)); }); messageTransport.SubscribeEvent(@event => { try { messagingClient.PublishEvent(@event); } catch (Exception e) { log.Log(LogLevel.Error, e.ToString(), e); } return(Task.FromResult(0)); }); var containerHostClient = new ContainerHostClient(hostProcess, messageTransport, messagingClient, jobObject); messageTransport.Start(); return(containerHostClient); }
public async Task <IList <string> > Generate(TranscodeJob job) { if (job == null) { throw new ArgumentNullException(nameof(job)); } if (job.SourceInfo?.Duration <= TimeSpan.Zero) { throw new ArgumentException( $"{nameof(job)}.{nameof(job.SourceInfo)}.{nameof(job.SourceInfo.Duration)} is invalid.", nameof(job)); } var dictionary = new ConcurrentDictionary <TimeSpan, string>(); var positions = GetPositions(job.SourceInfo.Duration); string tempPath = _fileSystem.Path.GetTempPath(); var tasks = positions.Select(async position => { var ffmpegJob = Map(job, _configManager?.Config); ffmpegJob.LogLevel = "panic"; ffmpegJob.OutputFileName = _fileSystem.Path.Combine(tempPath, $"{Guid.NewGuid()}.png"); ffmpegJob.StartTime = position; ffmpegJob.FrameCount = 1; string arguments = _argumentGenerator.GenerateArguments(ffmpegJob); try { var processResult = await _processRunner.Run(_ffmpegFileName, arguments, _timeout); if ((processResult.ExitCode == 0) && _fileSystem.File.Exists(ffmpegJob.OutputFileName)) { dictionary[position] = ffmpegJob.OutputFileName; } else { Trace.WriteLine("Failed to generate preview image."); } } catch (ArgumentException ex) { Trace.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); } catch (InvalidOperationException ex) { Trace.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); } }); await Task.WhenAll(tasks); return(dictionary.OrderBy(p => p.Key).Select(p => p.Value).ToArray()); }
public async Task <bool> Detect(MediaInfo mediaInfo) { if (mediaInfo == null) { throw new ArgumentNullException(nameof(mediaInfo)); } if (string.IsNullOrWhiteSpace(mediaInfo.FileName)) { throw new ArgumentException($"{nameof(mediaInfo)}.FileName must not be empty or whitespace.", nameof(mediaInfo)); } if (mediaInfo.Duration <= TimeSpan.Zero) { throw new ArgumentException($"{nameof(mediaInfo)}.Duration is invalid.", nameof(mediaInfo)); } var job = new FFmpegJob() { HideBanner = true, StartTime = TimeSpan.FromMilliseconds(mediaInfo.Duration.TotalMilliseconds / 2), InputFileName = mediaInfo.FileName, FrameCount = FRAME_COUNT, Filters = new IFilter[] { new Filter("idet") } }; var arguments = _argumentGenerator.GenerateArguments(job); FrameStatistics statistics = null; try { var processResult = await _processRunner.Run(_ffmpegFileName, arguments, _timeout); //The interlace detection data is written to standard error. if (!string.IsNullOrWhiteSpace(processResult.ErrorData)) { statistics = Parse(processResult.ErrorData); } else { Trace.WriteLine("No ffmpeg data on stderr to parse."); } } catch (ArgumentException ex) { Trace.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); } catch (InvalidOperationException ex) { Trace.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); } return(statistics != null && (statistics.TffCount + statistics.BffCount) > (statistics.ProgressiveCount + statistics.UndeterminedCount)); }
public async Task DetectReturnsTrueWhenMediaIsInterlaced() { string output = @"[Parsed_idet_0 @ 0x7fd17c62c980] Repeated Fields: Neither: 0 Top: 0 Bottom: 0 [Parsed_idet_0 @ 0x7fd17c62c980] Single frame detection: TFF: 0 BFF: 0 Progressive: 0 Undetermined: 0 [Parsed_idet_0 @ 0x7fd17c62c980] Multi frame detection: TFF: 0 BFF: 0 Progressive: 0 Undetermined: 0 frame= 100 fps=0.0 q=-0.0 Lsize=N/A time=00:00:03.39 bitrate=N/A speed=49.5x [Parsed_idet_0 @ 0x7fd17c40ec40] Repeated Fields: Neither: 96 Top: 4 Bottom: 1 [Parsed_idet_0 @ 0x7fd17c40ec40] Single frame detection: TFF: 62 BFF: 0 Progressive: 8 Undetermined: 31 [Parsed_idet_0 @ 0x7fd17c40ec40] Multi frame detection: TFF: 101 BFF: 0 Progressive: 0 Undetermined: 0"; _processRunner.Run(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <TimeSpan?>()) .Returns(new ProcessResult() { ErrorData = output }); Assert.IsTrue(await _detector.Detect(_mediaInfo)); }
public CommandResult Execute(SetDateTimeCommand command, CommandContext context) { var localTime = command.NewDateTimeUtc.ToLocalTime(); _processRunner.Run(_configuration[SetDateTimeCommandConfigPath].FormatWith(command.NewDateTimeUtc, localTime), _configuration[SetDateTimeArgumentsConfigPath].FormatWith(command.NewDateTimeUtc, localTime)) .Wait(2000); return(CommandResult.Empty); }
public static void RunVoid(this IProcessRunner processRunner, ProcessStartInfo startInfo, Func <int, string?> handleExitCode) { var exit = processRunner.Run(startInfo); var error = handleExitCode(exit); if (error != null) { throw new InvalidOperationException($"{error}. Got exit code '{exit}'."); } }
private void RunProcess(ReturnValue executeReturnValue) { var runProcessAction = ((ReturnValue <RunProcessAction>)executeReturnValue).Data; executeReturnValue = _processRunner.Run(runProcessAction); if (executeReturnValue.IsSuccess) { runProcessAction.Action?.Invoke(executeReturnValue.Message); } }
public void Execute(ScheduledTask directive, HostManifest host, IPackageLog log) { var psi = new ProcessStartInfo("schtasks"); var args = @"/create /tn {0} /sc {1} /mo {2} /ru {3} /tr {4};".ToFormat(directive.Name, directive.ScheduleType, directive.Modifier, directive.UserAccount, directive.TaskToRun); psi.Arguments = args; log.Trace(args); _runner.Run(psi, new TimeSpan(0, 0, 1, 0)); }
public async Task Prep(CancellationToken cancel) { DeleteEntireDirectory.DeleteEntireFolder(Pathing.BaseFolder); FileSystem.Directory.CreateDirectory(Pathing.BaseFolder); CreateSolutionFile.Create(Pathing.SolutionFile); CreateProject.Create(GameCategory.Skyrim, Pathing.ProjectFile, insertOldVersion: true, targetFramework: "net5.0"); AddProjectToSolution.Add(Pathing.SolutionFile, Pathing.ProjectFile); await _processRunner.Run( _dotNetCommandStartConstructor.Construct("restore", Pathing.ProjectFile), cancel : cancel).ConfigureAwait(false); }
private int Run() { try { return(_processRunner.Run()); } catch (ToolException toolException) { _console.WriteErrLine(toolException.Message); return(1); } }
static Task <ProcessResult> GetVaults(IProcessRunner processRunner, string organization, string sessionToken) { var processSettings = new ProcessSettings { Arguments = new ProcessArgumentBuilder() .Append("list") .Append("vaults"), EnvironmentVariables = new Dictionary <string, string>() .AddValue($"OP_SESSION_{organization}", sessionToken) }; return(processRunner.Run(ToolPath, processSettings)); }
public static ProcessResult Run( this IProcessRunner runner, string process, string arguments, TimeSpan timeout ) { return(runner.Run( workingDirectory: Environment.CurrentDirectory, process: process, arguments: arguments, timeout: timeout )); }
public static ProcessResult Run( this IProcessRunner runner, DirectoryInfo workingDirectory, FileInfo process, string arguments, TimeSpan timeout ) { return(runner.Run( workingDirectory: process.Directory.FullName, process: process.FullName, arguments: arguments, timeout: timeout )); }
public int Run(ProcessStartInfo startInfo, ProcessEvents?events = null) { jsonBuilder.Clear(); HadJsonOutput = false; bool readJsonLines = ReadAllLinesAsJson; LastExitCode = child.Run(startInfo, new ProcessEvents() { ProcessCreated = events?.ProcessCreated, ProcessCompleted = events?.ProcessCompleted, ErrorDataReceived = (s, e) => { events?.ErrorDataReceived?.Invoke(s, e); }, OutputDataReceived = (s, e) => { if (!String.IsNullOrEmpty(e.DataReceivedEventArgs.Data)) { if (e.DataReceivedEventArgs.Data == JsonStart) { readJsonLines = true; e.AllowOutput = false; } else if (e.DataReceivedEventArgs.Data == JsonEnd) { readJsonLines = false; e.AllowOutput = false; } else if (readJsonLines) //Else is intentional, want to skip start and end lines. { //Skip any lines that start with text in the skip lines collection if (!StartWithSkipLines.Any(i => e.DataReceivedEventArgs.Data.StartsWith(i))) { HadJsonOutput = true; jsonBuilder.AppendLine(e.DataReceivedEventArgs.Data); e.AllowOutput = false; } } } events?.OutputDataReceived?.Invoke(s, e); } }); return(LastExitCode); }
/// <summary> /// Start the daemon /// /// Now, we call this with MedallionShell and store the command descriptor. /// Before Startup, we need to set the effective working directory to "3rdParty/OpenVPN" /// </summary> /// <param name="configPath"></param> private void StartDaemon(string configPath) => _processRunner.Run( // Instructions new ProcessOptions() { Executable = DetermineBinaryPath(), Arguments = new[] { configPath }, Daemonized = true, Monitor = true, MonitoringInterval = 10, DisposeOnExit = false, InvokeAsSuperuser = true, AttachLogToConsole = true, WorkingDirectory = Path.Combine(Program.GetAssemblyLocation(), "3rdParty/OpenVPN") }, // The calling object. this );
private void TextBox_KeyDown_Handle_Return(string userInput) { if (userInput.Equals("exit") || userInput.Equals("quit")) { Application.Current.Shutdown(); } var matchedEntry = LaunchInformation.SingleOrDefault(i => i.Key.Contains(userInput)); if (matchedEntry.Value != null) { processRunner.Run(matchedEntry.Value); this.WindowState = System.Windows.WindowState.Minimized; TextBox.Text = string.Empty; UpdateScreen(); return; } }
/// <summary> /// Get the current status of the compiler. /// </summary> /// <returns></returns> public async Task <PublishEntryPoint> GetPublishInfo(ISyncRepository syncRepo) { var publishRepoPath = projectFinder.PublishedProjectPath; var masterRepoPath = projectFinder.MasterRepoPath; var compilerStatus = new PublishEntryPoint() { BehindBy = -1, BehindHistory = null }; if (publishRepoPath != masterRepoPath) { using (var repo = new Repository(publishRepoPath)) { var startInfo = new ProcessStartInfo("git") { ArgumentList = { "fetch", "--all" }, WorkingDirectory = repo.Info.WorkingDirectory }; processRunner.Run(startInfo); var head = repo.Head.Commits.First(); var tracked = repo.Head.TrackedBranch.Commits.First(); var divergence = repo.ObjectDatabase.CalculateHistoryDivergence(head, tracked); var behindCommits = repo.Commits.QueryBy(new CommitFilter() { SortBy = CommitSortStrategies.Reverse | CommitSortStrategies.Time, IncludeReachableFrom = divergence.Another, ExcludeReachableFrom = divergence.CommonAncestor }); compilerStatus.BehindBy = divergence.BehindBy.GetValueOrDefault(); compilerStatus.BehindHistory = behindCommits.Select(c => new History(c)).ToList(); var syncInfo = await syncRepo.SyncInfo(); compilerStatus.HasUncommittedChanges = syncInfo.HasUncomittedChanges; compilerStatus.HasUnsyncedChanges = syncInfo.NeedsPull || syncInfo.NeedsPush; } } return(compilerStatus); }
public void Execute(TopshelfService directive, HostManifest host, IPackageLog log) { //copy out TS host _bottles.ExplodeTo("bottlehost", directive.InstallLocation); //copy out service bottle exploded var location = FileSystem.Combine(directive.InstallLocation, "svc"); _bottles.ExplodeTo(directive.HostBottle, location); var args = buildInstallArgs(directive); var psi = new ProcessStartInfo("Bottles.Host.exe") { Arguments = args, WorkingDirectory = directive.InstallLocation }; _runner.Run(psi); }
public static String RunStringProcess(this IProcessRunner processRunner, ProcessStartInfo startInfo, Func <int, string?> handleExitCode) { var sb = new StringBuilder(); var exit = processRunner.Run(startInfo, new ProcessEvents() { OutputDataReceived = (o, i) => { i.AllowOutput = false; sb.Append(i.DataReceivedEventArgs.Data); } }); var error = handleExitCode(exit); if (error != null) { throw new InvalidOperationException($"{error}. Got exit code '{exit}'."); } return(sb.ToString()); }
public async Task <int[]> GetI2cDevices() { var detectResult = await _processRunner.Run("i2cdetect", "-y 1"); try { var addresses = detectResult.Split('\n') .Where(x => x.Contains(':')) .Select(x => x.Split(':')[1]) .SelectMany(x => x.Split(' ')) .Where(x => !string.IsNullOrWhiteSpace(x) && x != "--" && x != "UU") .Select(x => int.Parse(x, NumberStyles.AllowHexSpecifier)) .ToArray(); return(addresses); } catch (Exception exception) { throw new ParseException(exception, detectResult); } }