/// <inheritdoc /> public IProcess GetProcessByName(string name) { logger.LogTrace("GetProcessByName: {0}...", name ?? throw new ArgumentNullException(nameof(name))); var procs = global::System.Diagnostics.Process.GetProcessesByName(name); global::System.Diagnostics.Process handle = null; foreach (var proc in procs) { if (handle == null) { handle = proc; } else { logger.LogTrace("Disposing extra found PID: {0}...", proc.Id); proc.Dispose(); } } if (handle == null) { return(null); } return(CreateFromExistingHandle(handle)); }
/// <inheritdoc /> public Task <string> GetExecutingUsername(global::System.Diagnostics.Process process, CancellationToken cancellationToken) { string query = $"SELECT * FROM Win32_Process WHERE ProcessId = {process?.Id ?? throw new ArgumentNullException(nameof(process))}"; using var searcher = new ManagementObjectSearcher(query); foreach (ManagementObject obj in searcher.Get()) { var argList = new string[] { String.Empty, String.Empty }; var returnString = obj.InvokeMethod( "GetOwner", argList) ?.ToString(); if (!Int32.TryParse(returnString, out var returnVal)) { return(Task.FromResult($"BAD RETURN PARSE: {returnString}")); } if (returnVal == 0) { // return DOMAIN\user string owner = argList.Last() + "\\" + argList.First(); return(Task.FromResult(owner)); } } return(Task.FromResult("NO OWNER")); }
/// <inheritdoc /> public void SuspendProcess(global::System.Diagnostics.Process process) { if (process == null) { throw new ArgumentNullException(nameof(process)); } try { foreach (ProcessThread thread in process.Threads) { var pOpenThread = NativeMethods.OpenThread(NativeMethods.ThreadAccess.SuspendResume, false, (uint)thread.Id); if (pOpenThread == IntPtr.Zero) { continue; } if (NativeMethods.SuspendThread(pOpenThread) == UInt32.MaxValue) { throw new Win32Exception(); } NativeMethods.CloseHandle(pOpenThread); } logger.LogTrace("Suspended PID {0}", process.Id); } catch (Exception e) { logger.LogError(e, "Failed to suspend PID {0}!", process.Id); throw; } }
private bool IsArm64Process() { if (Environment.OSVersion.Platform != PlatformID.Unix || !Environment.Is64BitProcess) { return(false); } try { var process = new global::System.Diagnostics.Process(); process.StartInfo.FileName = "uname"; process.StartInfo.Arguments = "-m"; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.Start(); process.WaitForExit(); var output = process.StandardOutput.ReadToEnd(); return(output.Trim() == "aarch64"); } catch { return(false); } }
/// <inheritdoc /> public Task CreateDump(global::System.Diagnostics.Process process, string outputFile, CancellationToken cancellationToken) => Task.Factory.StartNew( () => { try { if (process.HasExited)
/// <inheritdoc /> public void SuspendProcess(global::System.Diagnostics.Process process) { if (process == null) { throw new ArgumentNullException(nameof(process)); } foreach (ProcessThread thread in process.Threads) { var pOpenThread = NativeMethods.OpenThread(NativeMethods.ThreadAccess.SuspendResume, false, (uint)thread.Id); if (pOpenThread == IntPtr.Zero) { continue; } try { if (NativeMethods.SuspendThread(pOpenThread) == UInt32.MaxValue) { throw new Win32Exception(); } } finally { NativeMethods.CloseHandle(pOpenThread); } } }
/// 実行ボタンクリック時の動作 public void Execute() { global::System.Diagnostics.ProcessStartInfo psInfo = new global::System.Diagnostics.ProcessStartInfo(); psInfo.FileName = this.FileName; psInfo.WorkingDirectory = this.WorkingDirectory; psInfo.Arguments = this.Arguments; psInfo.CreateNoWindow = true; psInfo.UseShellExecute = false; psInfo.RedirectStandardInput = true; psInfo.RedirectStandardOutput = true; psInfo.RedirectStandardError = true; // Process p = Process.Start(psInfo); p = new global::System.Diagnostics.Process(); p.StartInfo = psInfo; p.OutputDataReceived += p_OutputDataReceived; p.ErrorDataReceived += p_ErrorDataReceived; // プロセスの実行 p.Start(); // 標準入力への書き込み //if (InputString.Length > 0) p_WriteInputData(InputString); //非同期で出力とエラーの読み取りを開始 p.BeginOutputReadLine(); p.BeginErrorReadLine(); // 終わるまでまつ p.WaitForExit(); this.ExitCode = p.ExitCode; this.StandardOutput = standardOutputStringBuilder.ToString(); }
// Token: 0x0600003E RID: 62 RVA: 0x00002728 File Offset: 0x00000928 public bool InjectDLL() { if (global::System.Diagnostics.Process.GetProcessesByName("RobloxPlayerBeta").Length == 0) { return(false); } global::System.Diagnostics.Process process = global::System.Diagnostics.Process.GetProcessesByName("RobloxPlayerBeta")[0]; byte[] bytes = new global::System.Text.ASCIIEncoding().GetBytes(global::System.AppDomain.CurrentDomain.BaseDirectory + "exploit-main.dll"); global::System.IntPtr hModule = global::MainDab.Classes.WeAreDevsAPI.ExploitAPI.BasicInject.LoadLibraryA("kernel32.dll"); global::System.UIntPtr procAddress = global::MainDab.Classes.WeAreDevsAPI.ExploitAPI.BasicInject.GetProcAddress(hModule, "LoadLibraryA"); ExploitAPI.BasicInject.FreeLibrary(hModule); if (procAddress == global::System.UIntPtr.Zero) { return(false); } global::System.IntPtr intPtr = ExploitAPI.BasicInject.OpenProcess(ExploitAPI.BasicInject.ProcessAccess.AllAccess, false, process.Id); if (intPtr == global::System.IntPtr.Zero) { return(false); } global::System.IntPtr intPtr2 = ExploitAPI.BasicInject.VirtualAllocEx(intPtr, (global::System.IntPtr) 0, (uint)bytes.Length, 0x3000U, 4U); global::System.UIntPtr uintPtr; global::System.IntPtr intPtr3; return(!(intPtr2 == global::System.IntPtr.Zero) && ExploitAPI.BasicInject.WriteProcessMemory(intPtr, intPtr2, bytes, (uint)bytes.Length, out uintPtr) && !(ExploitAPI.BasicInject.CreateRemoteThread(intPtr, (global::System.IntPtr) 0, 0U, procAddress, intPtr2, 0U, out intPtr3) == global::System.IntPtr.Zero)); }
/// <summary> /// Construct a <see cref="Process"/> /// </summary> /// <param name="handle">The value of <see cref="handle"/></param> /// <param name="lifetime">The value of <see cref="Lifetime"/></param> /// <param name="outputStringBuilder">The value of <see cref="outputStringBuilder"/></param> /// <param name="errorStringBuilder">The value of <see cref="errorStringBuilder"/></param> /// <param name="combinedStringBuilder">The value of <see cref="combinedStringBuilder"/></param> /// <param name="logger">The value of <see cref="logger"/></param> /// <param name="preExisting">If <paramref name="handle"/> was NOT just created</param> public Process( global::System.Diagnostics.Process handle, Task <int> lifetime, StringBuilder outputStringBuilder, StringBuilder errorStringBuilder, StringBuilder combinedStringBuilder, ILogger <Process> logger, bool preExisting) { this.handle = handle ?? throw new ArgumentNullException(nameof(handle)); this.outputStringBuilder = outputStringBuilder; this.errorStringBuilder = errorStringBuilder; this.combinedStringBuilder = combinedStringBuilder; this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); Lifetime = WrapLifetimeTask(lifetime ?? throw new ArgumentNullException(nameof(lifetime))); Id = handle.Id; if (preExisting) { Startup = Task.CompletedTask; return; } Startup = Task.Factory.StartNew(() => { try { handle.WaitForInputIdle(); } catch (InvalidOperationException) { } }, default, TaskCreationOptions.LongRunning, TaskScheduler.Current);
/// <inheritdoc /> public void SuspendProcess(global::System.Diagnostics.Process process) { var result = Syscall.kill(process.Id, Signum.SIGSTOP); if (result != 0) { throw new UnixIOException(result); } }
async Task <Task <int> > AttachExitHandlerBeforeLaunch(global::System.Diagnostics.Process handle, Task startupTask) { var id = -1; var result = AttachExitHandler(handle, () => id); await startupTask.ConfigureAwait(false); id = handle.Id; return(result); }
public static void ExecuteBatchScript(string fileName) { var process = new global::System.Diagnostics.Process { StartInfo = { FileName = fileName } }; process.Start(); process.WaitForExit(); }
Task <int> AttachExitHandler(global::System.Diagnostics.Process handle, Func <int> idProvider) { handle.EnableRaisingEvents = true; var tcs = new TaskCompletionSource <int>(); void ExitHandler(object sender, EventArgs args) { var id = idProvider(); try { if (tcs.Task.IsCompleted) { logger.LogTrace("Skipping PID {0} exit handler as the TaskCompletionSource is already set", id); return; } try { var exitCode = handle.ExitCode; // Try because this can be invoked twice for weird reasons if (tcs.TrySetResult(exitCode)) { logger.LogTrace("PID {0} termination event completed", id); } else { logger.LogTrace("Ignoring duplicate PID {0} termination event", id); } } catch (InvalidOperationException ex) { if (!tcs.Task.IsCompleted) { throw; } logger.LogTrace(ex, "Ignoring expected PID {0} exit handler exception!", id); } } catch (Exception ex) { logger.LogError(ex, "PID {0} exit handler exception!", id); } } handle.Exited += ExitHandler; return(tcs.Task); }
public override object __hx_setField(string field, int hash, object @value, bool handleProperties) { unchecked { #line 32 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" switch (hash) { case 572311959: { #line 32 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" this.native = ((global::System.Diagnostics.Process)(@value)); #line 32 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" return(@value); } case 68006728: { #line 32 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" this.stdin = ((global::haxe.io.Output)(@value)); #line 32 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" return(@value); } case 132916898: { #line 32 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" this.stderr = ((global::haxe.io.Input)(@value)); #line 32 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" return(@value); } case 133414859: { #line 32 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" this.stdout = ((global::haxe.io.Input)(@value)); #line 32 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" return(@value); } default: { #line 32 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" return(base.__hx_setField(field, hash, @value, handleProperties)); } } } #line default }
/// <summary> /// Start a process that runs the Notepad application. /// </summary> /// <param name="InProcess"></param> /// <param name="InFilePath"></param> /// <returns></returns> public static bool StartNotepad( this global::System.Diagnostics.Process InProcess, string InFilePath) { string exePath = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\notepad.exe"); InProcess.StartInfo.FileName = exePath; InProcess.StartInfo.Arguments = InFilePath; bool rc = InProcess.Start(); return(rc); }
// Token: 0x060005C3 RID: 1475 RVA: 0x0001BF90 File Offset: 0x0001A190 private static bool FilterInvalidProcesses(global::System.Diagnostics.Process p) { bool result; try { result = (p.ProcessName != null); } catch { result = false; } return(result); }
/// <summary> /// Construct a <see cref="Process"/> /// </summary> /// <param name="processFeatures">The value of <see cref="processFeatures"/></param> /// <param name="handle">The value of <see cref="handle"/></param> /// <param name="lifetime">The value of <see cref="Lifetime"/></param> /// <param name="standardOutputTask">The value of <see cref="standardOutputTask"/></param> /// <param name="standardErrorTask">The value of <see cref="standardErrorTask"/></param> /// <param name="combinedStringBuilder">The value of <see cref="combinedStringBuilder"/></param> /// <param name="logger">The value of <see cref="logger"/></param> /// <param name="preExisting">If <paramref name="handle"/> was NOT just created</param> public Process( IProcessFeatures processFeatures, global::System.Diagnostics.Process handle, Task <int> lifetime, Task <string> standardOutputTask, Task <string> standardErrorTask, StringBuilder combinedStringBuilder, ILogger <Process> logger, bool preExisting) { this.handle = handle ?? throw new ArgumentNullException(nameof(handle)); // Do this fast because the runtime will bitch if we try to access it after it ends Id = handle.Id; // https://stackoverflow.com/a/47656845 safeHandle = handle.SafeHandle; this.processFeatures = processFeatures ?? throw new ArgumentNullException(nameof(processFeatures)); this.standardOutputTask = standardOutputTask; this.standardErrorTask = standardErrorTask; this.combinedStringBuilder = combinedStringBuilder; this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); Lifetime = WrapLifetimeTask(lifetime ?? throw new ArgumentNullException(nameof(lifetime))); if (preExisting) { Startup = Task.CompletedTask; return; } Startup = Task.Factory.StartNew( () => { try { handle.WaitForInputIdle(); } catch (Exception ex) { logger.LogDebug(ex, "Error on WaitForInputIdle()!"); } },
private bool IsArm64Process () { if (Environment.OSVersion.Platform != PlatformID.Unix || !Environment.Is64BitProcess) return false; try { var process = new global::System.Diagnostics.Process (); process.StartInfo.FileName = "uname"; process.StartInfo.Arguments = "-m"; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.Start (); process.WaitForExit (); var output = process.StandardOutput.ReadToEnd (); return output.Trim () == "aarch64"; } catch { return false; } }
/// <summary> /// Create a <see cref="Task{TResult}"/> resulting in the exit code of a given <paramref name="handle"/> /// </summary> /// <param name="handle">The <see cref="global::System.Diagnostics.Process"/> to attach the <see cref="Task{TResult}"/> for</param> /// <returns>A new <see cref="Task{TResult}"/> resulting in the exit code of <paramref name="handle"/></returns> static Task <int> AttachExitHandler(global::System.Diagnostics.Process handle) { handle.EnableRaisingEvents = true; var tcs = new TaskCompletionSource <int>(); handle.Exited += (a, b) => { int exitCode; try { exitCode = handle.ExitCode; } catch (InvalidOperationException) { return; } tcs.SetResult(exitCode); }; return(tcs.Task); }
/// <summary> /// Create a <see cref="IProcess"/> given an existing <paramref name="handle"/>. /// </summary> /// <param name="handle">The <see cref="global::System.Diagnostics.Process"/> to create a <see cref="IProcess"/> from.</param> /// <returns>The <see cref="IProcess"/> based on <paramref name="handle"/>.</returns> private IProcess CreateFromExistingHandle(global::System.Diagnostics.Process handle) { try { var pid = handle.Id; return(new Process( processFeatures, handle, AttachExitHandler(handle, () => pid), null, null, null, loggerFactory.CreateLogger <Process>(), true)); } catch { handle.Dispose(); throw; } }
public static int command(string cmd, global::Array <string> args) { #line 106 "/opt/haxe/std/cs/_std/Sys.hx" global::System.Diagnostics.Process proc = global::sys.io.Process.createNativeProcess(cmd, args); global::System.Diagnostics.DataReceivedEventHandler this1 = ((global::System.Diagnostics.DataReceivedEventHandler)((((global::Sys_command_107__Fun.__hx_current != null)) ? (global::Sys_command_107__Fun.__hx_current) : (global::Sys_command_107__Fun.__hx_current = ((global::Sys_command_107__Fun)(new global::Sys_command_107__Fun())))).Delegate)); proc.OutputDataReceived += ((global::System.Diagnostics.DataReceivedEventHandler)(this1)); #line 112 "/opt/haxe/std/cs/_std/Sys.hx" global::haxe.io.Output stderr = ((global::haxe.io.Output)(new global::cs.io.NativeOutput(((global::System.IO.Stream)(global::System.Console.OpenStandardError()))))); global::System.Diagnostics.DataReceivedEventHandler this2 = ((global::System.Diagnostics.DataReceivedEventHandler)(new global::Sys_command_113__Fun(stderr).Delegate)); proc.ErrorDataReceived += ((global::System.Diagnostics.DataReceivedEventHandler)(this2)); #line 118 "/opt/haxe/std/cs/_std/Sys.hx" proc.Start(); proc.BeginOutputReadLine(); #line 120 "/opt/haxe/std/cs/_std/Sys.hx" proc.BeginErrorReadLine(); proc.WaitForExit(); #line 122 "/opt/haxe/std/cs/_std/Sys.hx" int exitCode = proc.ExitCode; (proc as global::System.ComponentModel.Component).Dispose(); #line 124 "/opt/haxe/std/cs/_std/Sys.hx" return(exitCode); }
private bool IsArm64Process() { if (!GDIPlus.RunningOnUnix()) { return(false); } try { var process = new global::System.Diagnostics.Process(); process.StartInfo.FileName = "uname"; process.StartInfo.Arguments = "-m"; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.Start(); process.WaitForExit(); var output = process.StandardOutput.ReadToEnd(); return(output.Trim() == "aarch64"); } catch { return(false); } }
/// <summary> /// Create a <see cref="Task{TResult}"/> resulting in the exit code of a given <paramref name="handle"/> /// </summary> /// <param name="handle">The <see cref="global::System.Diagnostics.Process"/> to attach the <see cref="Task{TResult}"/> for</param> /// <returns>A new <see cref="Task{TResult}"/> resulting in the exit code of <paramref name="handle"/></returns> static Task <int> AttachExitHandler(global::System.Diagnostics.Process handle) { handle.EnableRaisingEvents = true; var tcs = new TaskCompletionSource <int>(); handle.Exited += (a, b) => { int exitCode; try { exitCode = handle.ExitCode; } catch (InvalidOperationException) { return; } // Try because this can be invoked twice for weird reasons tcs.TrySetResult(exitCode); }; return(tcs.Task); }
public Process(global::System.Diagnostics.Process systemProcess) { Contract.Requires(systemProcess != null); _systemProcess = systemProcess; }
/// <inheritdoc /> public async Task CreateDump(global::System.Diagnostics.Process process, string outputFile, CancellationToken cancellationToken) { if (process == null) { throw new ArgumentNullException(nameof(process)); } if (outputFile == null) { throw new ArgumentNullException(nameof(outputFile)); } const string GCorePath = "/usr/bin/gcore"; if (!await ioManager.FileExists(GCorePath, cancellationToken).ConfigureAwait(false)) { throw new JobException(ErrorCode.MissingGCore); } int pid; try { if (process.HasExited) { throw new JobException(ErrorCode.DreamDaemonOffline); } pid = process.Id; } catch (InvalidOperationException ex) { throw new JobException(ErrorCode.DreamDaemonOffline, ex); } string output; int exitCode; using (var gcoreProc = lazyLoadedProcessExecutor.Value.LaunchProcess( GCorePath, Environment.CurrentDirectory, $"-o {outputFile} {process.Id}", true, true, true)) { using (cancellationToken.Register(() => gcoreProc.Terminate())) exitCode = await gcoreProc.Lifetime.ConfigureAwait(false); output = await gcoreProc.GetCombinedOutput(cancellationToken).ConfigureAwait(false); logger.LogDebug("gcore output:{0}{1}", Environment.NewLine, output); } if (exitCode != 0) { throw new JobException( ErrorCode.GCoreFailure, new JobException( $"Exit Code: {exitCode}{Environment.NewLine}Output:{Environment.NewLine}{output}")); } // gcore outputs name.pid so remove the pid part var generatedGCoreFile = $"{outputFile}.{pid}"; await ioManager.MoveFile(generatedGCoreFile, outputFile, cancellationToken).ConfigureAwait(false); }
public static global::System.Diagnostics.Process createNativeProcess(string cmd, global::haxe.root.Array args) { unchecked { #line 52 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" global::System.Diagnostics.Process native = new global::System.Diagnostics.Process(); native.StartInfo.CreateNoWindow = ((bool)(true)); #line 54 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" native.StartInfo.RedirectStandardError = ((bool)(native.StartInfo.RedirectStandardInput = ((bool)(native.StartInfo.RedirectStandardOutput = ((bool)(true)))))); if ((args != null)) { #line 57 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" if (((global::haxe.lang.StringExt.indexOf(cmd, "/", null) != -1) || (global::haxe.lang.StringExt.indexOf(cmd, "\\", null) != -1))) { #line 58 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" cmd = global::sys.FileSystem.fullPath(cmd); } #line 59 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" native.StartInfo.FileName = ((string)(cmd)); native.StartInfo.UseShellExecute = ((bool)(false)); #line 61 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" native.StartInfo.Arguments = ((string)(global::sys.io.Process.buildArgumentsString(args))); } else { #line 63 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" if ((global::haxe.root.Sys.systemName() == "Windows")) { #line 65 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" global::System.Diagnostics.ProcessStartInfo tmp = native.StartInfo; #line 65 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" string _g = global::System.Environment.GetEnvironmentVariable(((string)("COMSPEC"))); #line 65 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" string tmp1 = null; if ((_g == null)) { #line 65 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" tmp1 = "cmd.exe"; } else { #line 67 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" string comspec = _g; #line 65 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" tmp1 = comspec; } #line 65 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" tmp.FileName = ((string)(tmp1)); #line 69 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" native.StartInfo.Arguments = ((string)(global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.concat("/C \"", cmd), "\""))); } else { #line 71 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" native.StartInfo.FileName = ((string)("/bin/sh")); native.StartInfo.Arguments = ((string)(global::sys.io.Process.buildArgumentsString(new global::haxe.root.Array(new object[] { "-c", cmd })))); } #line 74 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" native.StartInfo.UseShellExecute = ((bool)(false)); } #line 76 "C:\\HaxeToolkit\\haxe\\std\\cs\\_std\\sys\\io\\Process.hx" return(native); } #line default }
/// <summary> /// Process is used to return a JSON object containing a variety of information about the host system /// which is running the WaveBox server /// </summary> public void Process(UriWrapper uri, IHttpProcessor processor, User user) { try { // Allocate an array of various statistics about the running process IDictionary <string, object> status = new Dictionary <string, object>(); // Gather data about WaveBox process global::System.Diagnostics.Process proc = global::System.Diagnostics.Process.GetCurrentProcess(); // Get current UNIX time long unixTime = DateTime.UtcNow.ToUnixTime(); // Get current query log ID long queryLogId = Injection.Kernel.Get <IDatabase>().LastQueryLogId; // Get process ID status["pid"] = proc.Id; // Get uptime of WaveBox instance status["uptime"] = unixTime - WaveBoxService.StartTime.ToUnixTime(); // Get last update time in UNIX format for status status["updated"] = unixTime; // Get hostname of machine status["hostname"] = System.Environment.MachineName; // Get WaveBox version status["version"] = WaveBoxService.BuildVersion; // Get build date status["buildDate"] = WaveBoxService.BuildDate.ToString("MMMM dd, yyyy"); // Get host platform status["platform"] = WaveBoxService.OS.ToDescription(); // Get current CPU usage status["cpuPercent"] = CpuUsage(); // Get current memory usage in MB status["memoryMb"] = (float)proc.WorkingSet64 / 1024f / 1024f; // Get peak memory usage in MB status["peakMemoryMb"] = (float)proc.PeakWorkingSet64 / 1024f / 1024f; // Get list of media types WaveBox can index and serve (removing "Unknown") status["mediaTypes"] = Enum.GetNames(typeof(FileType)).Where(x => x != "Unknown").ToList(); // Get list of transcoders available status["transcoders"] = Enum.GetNames(typeof(TranscodeType)).ToList(); // Get list of services status["services"] = ServiceManager.GetServices(); // Get last query log ID status["lastQueryLogId"] = queryLogId; // Call for extended status, which uses some database intensive calls if (uri.Parameters.ContainsKey("extended")) { if (uri.Parameters["extended"].IsTrue()) { // Check if any destructive queries have been performed since the last cache if ((statusCache.LastQueryId == null) || (queryLogId > statusCache.LastQueryId)) { // Update to the latest query log ID statusCache.LastQueryId = queryLogId; logger.IfInfo("Gathering extended status metrics from database"); // Get count of artists statusCache.Cache["artistCount"] = Injection.Kernel.Get <IArtistRepository>().CountArtists(); // Get count of album artists statusCache.Cache["albumArtistCount"] = Injection.Kernel.Get <IAlbumArtistRepository>().CountAlbumArtists(); // Get count of albums statusCache.Cache["albumCount"] = Injection.Kernel.Get <IAlbumRepository>().CountAlbums(); // Get count of songs statusCache.Cache["songCount"] = Injection.Kernel.Get <ISongRepository>().CountSongs(); // Get count of videos statusCache.Cache["videoCount"] = Injection.Kernel.Get <IVideoRepository>().CountVideos(); // Get total file size of songs (bytes) statusCache.Cache["songFileSize"] = Injection.Kernel.Get <ISongRepository>().TotalSongSize(); // Get total file size of videos (bytes) statusCache.Cache["videoFileSize"] = Injection.Kernel.Get <IVideoRepository>().TotalVideoSize(); // Get total song duration statusCache.Cache["songDuration"] = Injection.Kernel.Get <ISongRepository>().TotalSongDuration(); // Get total video duration statusCache.Cache["videoDuration"] = Injection.Kernel.Get <IVideoRepository>().TotalVideoDuration(); logger.IfInfo("Metric gathering complete, cached results!"); } // Append cached status dictionary to status status = status.Concat(statusCache.Cache).ToDictionary(x => x.Key, x => x.Value); } } // Return all status processor.WriteJson(new StatusResponse(null, status)); return; } catch (Exception e) { logger.Error(e); } // Return error processor.WriteJson(new StatusResponse("Could not retrieve server status", null)); return; }
/// <inheritdoc /> public IProcess LaunchProcess( string fileName, string workingDirectory, string arguments, bool readOutput, bool readError, bool noShellExecute) { if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); } if (workingDirectory == null) { throw new ArgumentNullException(nameof(workingDirectory)); } if (arguments == null) { throw new ArgumentNullException(nameof(arguments)); } if (!noShellExecute && (readOutput || readError)) { throw new InvalidOperationException("Requesting output/error reading requires noShellExecute to be true!"); } logger.LogDebug( "{0}aunching process in {1}: {2} {3}", noShellExecute ? "L" : "Shell l", workingDirectory, fileName, arguments); var handle = new global::System.Diagnostics.Process(); try { handle.StartInfo.FileName = fileName; handle.StartInfo.Arguments = arguments; handle.StartInfo.WorkingDirectory = workingDirectory; handle.StartInfo.UseShellExecute = !noShellExecute; StringBuilder combinedStringBuilder = null; Task <string> outputTask = null; Task <string> errorTask = null; var processStartTcs = new TaskCompletionSource <object>(); if (readOutput || readError) { combinedStringBuilder = new StringBuilder(); async Task <string> ConsumeReader(Func <TextReader> readerFunc) { var stringBuilder = new StringBuilder(); string text; await processStartTcs.Task.ConfigureAwait(false); var reader = readerFunc(); while ((text = await reader.ReadLineAsync().ConfigureAwait(false)) != null) { combinedStringBuilder.AppendLine(); combinedStringBuilder.Append(text); stringBuilder.AppendLine(); stringBuilder.Append(text); } return(stringBuilder.ToString()); } if (readOutput) { outputTask = ConsumeReader(() => handle.StandardOutput); handle.StartInfo.RedirectStandardOutput = true; } if (readError) { errorTask = ConsumeReader(() => handle.StandardError); handle.StartInfo.RedirectStandardError = true; } } var lifetimeTaskTask = AttachExitHandlerBeforeLaunch(handle, processStartTcs.Task); try { handle.Start(); processStartTcs.SetResult(null); } catch (Exception ex) { processStartTcs.SetException(ex); throw; } var process = new Process( processFeatures, handle, lifetimeTaskTask.GetAwaiter().GetResult(), // won't block outputTask, errorTask, combinedStringBuilder, loggerFactory.CreateLogger <Process>(), false); return(process); } catch { handle.Dispose(); throw; } }
/// <inheritdoc /> public IProcess LaunchProcess( string fileName, string workingDirectory, string arguments, bool readOutput, bool readError, bool noShellExecute) { if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); } if (workingDirectory == null) { throw new ArgumentNullException(nameof(workingDirectory)); } if (arguments == null) { throw new ArgumentNullException(nameof(arguments)); } if (!noShellExecute && (readOutput || readError)) { throw new InvalidOperationException("Requesting output/error reading requires noShellExecute to be true!"); } logger.LogDebug( "{0}aunching process in {1}: {2} {3}", noShellExecute ? "L" : "Shell l", workingDirectory, fileName, arguments); var handle = new global::System.Diagnostics.Process(); try { handle.StartInfo.FileName = fileName; handle.StartInfo.Arguments = arguments; handle.StartInfo.WorkingDirectory = workingDirectory; handle.StartInfo.UseShellExecute = !noShellExecute; StringBuilder outputStringBuilder = null, errorStringBuilder = null, combinedStringBuilder = null; TaskCompletionSource <object> outputReadTcs = null; TaskCompletionSource <object> errorReadTcs = null; if (readOutput || readError) { combinedStringBuilder = new StringBuilder(); if (readOutput) { outputStringBuilder = new StringBuilder(); handle.StartInfo.RedirectStandardOutput = true; outputReadTcs = new TaskCompletionSource <object>(); handle.OutputDataReceived += (sender, e) => { if (e.Data == null) { outputReadTcs.SetResult(null); return; } combinedStringBuilder.Append(Environment.NewLine); combinedStringBuilder.Append(e.Data); outputStringBuilder.Append(Environment.NewLine); outputStringBuilder.Append(e.Data); }; } if (readError) { errorStringBuilder = new StringBuilder(); handle.StartInfo.RedirectStandardError = true; errorReadTcs = new TaskCompletionSource <object>(); handle.ErrorDataReceived += (sender, e) => { if (e.Data == null) { errorReadTcs.SetResult(null); return; } combinedStringBuilder.Append(Environment.NewLine); combinedStringBuilder.Append(e.Data); errorStringBuilder.Append(Environment.NewLine); errorStringBuilder.Append(e.Data); }; } } var lifetimeTask = AttachExitHandler(handle); handle.Start();
/// <inheritdoc /> public IProcess LaunchProcess(string fileName, string workingDirectory, string arguments, bool readOutput, bool readError, bool noShellExecute) { logger.LogDebug("Launching process in {0}: {1} {2}", workingDirectory, fileName, arguments); var handle = new global::System.Diagnostics.Process(); try { handle.StartInfo.FileName = fileName; handle.StartInfo.Arguments = arguments; handle.StartInfo.WorkingDirectory = workingDirectory; handle.StartInfo.UseShellExecute = !(noShellExecute || readOutput || readError); StringBuilder outputStringBuilder = null, errorStringBuilder = null, combinedStringBuilder = null; if (readOutput || readError) { combinedStringBuilder = new StringBuilder(); if (readOutput) { outputStringBuilder = new StringBuilder(); handle.StartInfo.RedirectStandardOutput = true; handle.OutputDataReceived += (sender, e) => { combinedStringBuilder.Append(Environment.NewLine); combinedStringBuilder.Append(e.Data); outputStringBuilder.Append(Environment.NewLine); outputStringBuilder.Append(e.Data); }; } if (readError) { errorStringBuilder = new StringBuilder(); handle.StartInfo.RedirectStandardError = true; handle.ErrorDataReceived += (sender, e) => { combinedStringBuilder.Append(Environment.NewLine); combinedStringBuilder.Append(e.Data); errorStringBuilder.Append(Environment.NewLine); errorStringBuilder.Append(e.Data); }; } } var lifetimeTask = AttachExitHandler(handle); handle.Start(); try { if (readOutput) { handle.BeginOutputReadLine(); } } catch (InvalidOperationException) { } try { if (readError) { handle.BeginErrorReadLine(); } } catch (InvalidOperationException) { } return(new Process(handle, lifetimeTask, outputStringBuilder, errorStringBuilder, combinedStringBuilder, loggerFactory.CreateLogger <Process>(), false)); } catch { handle.Dispose(); throw; } }
/// <inheritdoc /> public Task <string> GetExecutingUsername(global::System.Diagnostics.Process process, CancellationToken cancellationToken) => throw new NotSupportedException();
public void AssignProcess(global::System.Diagnostics.Process process) { _handle.AssignProcess(process); }