/// <summary> /// Creates a process as another user account. This method will attempt to run as another user with the /// highest possible permissions available. The main privilege required is the SeDebugPrivilege, without /// this privilege you can only run as a local or domain user if the username and password is specified. /// </summary> /// <param name="username">The username of the runas user</param> /// <param name="password">The password of the runas user</param> /// <param name="logonFlags">LogonFlags to control how to logon a user when the password is specified</param> /// <param name="logonType">Controls what type of logon is used, this only applies when the password is specified</param> /// <param name="lpApplicationName">The name of the executable or batch file to executable</param> /// <param name="lpCommandLine">The command line to execute, typically this includes lpApplication as the first argument</param> /// <param name="lpCurrentDirectory">The full path to the current directory for the process, null will have the same cwd as the calling process</param> /// <param name="environment">A dictionary of key/value pairs to define the new process environment</param> /// <param name="stdin">Bytes sent to the stdin pipe</param> /// <returns>Ansible.Process.Result object that contains the command output and return code</returns> public static Result CreateProcessAsUser(string username, string password, LogonFlags logonFlags, LogonType logonType, string lpApplicationName, string lpCommandLine, string lpCurrentDirectory, IDictionary environment, byte[] stdin) { // While we use STARTUPINFOEX having EXTENDED_STARTUPINFO_PRESENT causes a parameter validation error Process.NativeHelpers.ProcessCreationFlags creationFlags = Process.NativeHelpers.ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT; Process.NativeHelpers.PROCESS_INFORMATION pi = new Process.NativeHelpers.PROCESS_INFORMATION(); Process.NativeHelpers.STARTUPINFOEX si = new Process.NativeHelpers.STARTUPINFOEX(); si.startupInfo.dwFlags = Process.NativeHelpers.StartupInfoFlags.USESTDHANDLES; SafeFileHandle stdoutRead, stdoutWrite, stderrRead, stderrWrite, stdinRead, stdinWrite; ProcessUtil.CreateStdioPipes(si, out stdoutRead, out stdoutWrite, out stderrRead, out stderrWrite, out stdinRead, out stdinWrite); FileStream stdinStream = new FileStream(stdinWrite, FileAccess.Write); // $null from PowerShell ends up as an empty string, we need to convert back as an empty string doesn't // make sense for these parameters if (lpApplicationName == "") { lpApplicationName = null; } if (lpCurrentDirectory == "") { lpCurrentDirectory = null; } // A user may have 2 tokens, 1 limited and 1 elevated. GetUserTokens will return both token to ensure // we don't close one of the pairs while the process is still running. If the process tries to retrieve // one of the pairs and the token handle is closed then it will fail with ERROR_NO_SUCH_LOGON_SESSION. List <SafeNativeHandle> userTokens = GetUserTokens(username, password, logonType); try { using (Process.SafeMemoryBuffer lpEnvironment = ProcessUtil.CreateEnvironmentPointer(environment)) { bool launchSuccess = false; StringBuilder commandLine = new StringBuilder(lpCommandLine); foreach (SafeNativeHandle token in userTokens) { // GetUserTokens could return null if an elevated token could not be retrieved. if (token == null) { continue; } if (NativeMethods.CreateProcessWithTokenW(token, logonFlags, lpApplicationName, commandLine, creationFlags, lpEnvironment, lpCurrentDirectory, si, out pi)) { launchSuccess = true; break; } } if (!launchSuccess) { throw new Process.Win32Exception("CreateProcessWithTokenW() failed"); } } return(ProcessUtil.WaitProcess(stdoutRead, stdoutWrite, stderrRead, stderrWrite, stdinStream, stdin, pi.hProcess)); } finally { userTokens.Where(t => t != null).ToList().ForEach(t => t.Dispose()); } }
private async Task LaunchService(Application application, Service service) { var serviceDescription = service.Description; var serviceName = serviceDescription.Name; var path = ""; var workingDirectory = ""; var args = ""; if (serviceDescription.RunInfo is ProjectRunInfo project) { path = project.RunCommand; workingDirectory = project.ProjectFile.Directory.FullName; args = project.Args == null ? project.RunArguments : project.RunArguments + " " + project.Args; service.Status.ProjectFilePath = project.ProjectFile.FullName; } else if (serviceDescription.RunInfo is ExecutableRunInfo executable) { path = executable.Executable; workingDirectory = executable.WorkingDirectory !; args = executable.Args ?? ""; } else { throw new InvalidOperationException("Unsupported ServiceType."); } // If this is a dll then use dotnet to run it if (Path.GetExtension(path) == ".dll") { args = $"\"{path}\" {args}".Trim(); path = "dotnet"; } service.Status.ExecutablePath = path; service.Status.WorkingDirectory = workingDirectory; service.Status.Args = args; var processInfo = new ProcessInfo(new Task[service.Description.Replicas]); if (service.Status.ProjectFilePath != null && service.Description.RunInfo is ProjectRunInfo project2 && project2.Build && _options.BuildProjects) { // Sometimes building can fail because of file locking (like files being open in VS) _logger.LogInformation("Building project {ProjectFile}", service.Status.ProjectFilePath); service.Logs.OnNext($"dotnet build \"{service.Status.ProjectFilePath}\" /nologo"); var buildResult = await ProcessUtil.RunAsync("dotnet", $"build \"{service.Status.ProjectFilePath}\" /nologo", throwOnError : false); service.Logs.OnNext(buildResult.StandardOutput); if (buildResult.ExitCode != 0) { _logger.LogInformation("Building {ProjectFile} failed with exit code {ExitCode}: \r\n" + buildResult.StandardOutput, service.Status.ProjectFilePath, buildResult.ExitCode); return; } } async Task RunApplicationAsync(IEnumerable <(int ExternalPort, int Port, string?Protocol)> ports) { // Make sure we yield before trying to start the process, this is important so we don't block startup await Task.Yield(); var hasPorts = ports.Any(); var environment = new Dictionary <string, string> { // Default to development environment ["DOTNET_ENVIRONMENT"] = "Development" }; // Set up environment variables to use the version of dotnet we're using to run // this is important for tests where we're not using a globally-installed dotnet. var dotnetRoot = GetDotnetRoot(); if (dotnetRoot is object) { environment["DOTNET_ROOT"] = dotnetRoot; environment["DOTNET_MULTILEVEL_LOOKUP"] = "0"; environment["PATH"] = $"{dotnetRoot};{Environment.GetEnvironmentVariable("PATH")}"; } application.PopulateEnvironment(service, (k, v) => environment[k] = v); if (_options.DebugMode && (_options.DebugAllServices || _options.ServicesToDebug.Contains(serviceName, StringComparer.OrdinalIgnoreCase))) { environment["DOTNET_STARTUP_HOOKS"] = typeof(Hosting.Runtime.HostingRuntimeHelpers).Assembly.Location; } if (hasPorts) { // These are the ports that the application should use for binding // 1. Configure ASP.NET Core to bind to those same ports environment["ASPNETCORE_URLS"] = string.Join(";", ports.Select(p => $"{p.Protocol ?? "http"}://localhost:{p.Port}")); // Set the HTTPS port for the redirect middleware foreach (var p in ports) { if (string.Equals(p.Protocol, "https", StringComparison.OrdinalIgnoreCase)) { // We need to set the redirect URL to the exposed port so the redirect works cleanly environment["HTTPS_PORT"] = p.ExternalPort.ToString(); } } // 3. For non-ASP.NET Core apps, pass the same information in the PORT env variable as a semicolon separated list. environment["PORT"] = string.Join(";", ports.Select(p => $"{p.Port}")); } while (!processInfo.StoppedTokenSource.IsCancellationRequested) { var replica = serviceName + "_" + Guid.NewGuid().ToString().Substring(0, 10).ToLower(); var status = new ProcessStatus(service, replica); service.Replicas[replica] = status; service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Added, status)); // This isn't your host name environment["APP_INSTANCE"] = replica; status.ExitCode = null; status.Pid = null; status.Environment = environment; if (hasPorts) { status.Ports = ports.Select(p => p.Port); } _logger.LogInformation("Launching service {ServiceName}: {ExePath} {args}", replica, path, args); try { service.Logs.OnNext($"[{replica}]:{path} {args}"); var result = await ProcessUtil.RunAsync(path, args, environmentVariables : environment, workingDirectory : workingDirectory, outputDataReceived : data => service.Logs.OnNext($"[{replica}]: {data}"), errorDataReceived : data => service.Logs.OnNext($"[{replica}]: {data}"), onStart : pid => { if (hasPorts) { _logger.LogInformation("{ServiceName} running on process id {PID} bound to {Address}", replica, pid, string.Join(", ", ports.Select(p => $"{p.Protocol ?? "http"}://localhost:{p.Port}"))); } else { _logger.LogInformation("{ServiceName} running on process id {PID}", replica, pid); } status.Pid = pid; WriteReplicaToStore(pid.ToString()); service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Started, status)); }, throwOnError : false, cancellationToken : processInfo.StoppedTokenSource.Token); status.ExitCode = result.ExitCode; if (status.Pid != null) { service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Stopped, status)); } } catch (Exception ex) { _logger.LogError(0, ex, "Failed to launch process for service {ServiceName}", replica); try { await Task.Delay(5000, processInfo.StoppedTokenSource.Token); } catch (OperationCanceledException) { // Swallow cancellation exceptions and continue } } service.Restarts++; if (status.ExitCode != null) { _logger.LogInformation("{ServiceName} process exited with exit code {ExitCode}", replica, status.ExitCode); } // Remove the replica from the set service.Replicas.TryRemove(replica, out _); service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Removed, status)); } } if (serviceDescription.Bindings.Count > 0) { // Each replica is assigned a list of internal ports, one mapped to each external // port for (int i = 0; i < serviceDescription.Replicas; i++) { var ports = new List <(int, int, string?)>(); foreach (var binding in serviceDescription.Bindings) { if (binding.Port == null) { continue; } ports.Add((binding.Port.Value, binding.ReplicaPorts[i], binding.Protocol)); } processInfo.Tasks[i] = RunApplicationAsync(ports); } } else { for (int i = 0; i < service.Description.Replicas; i++) { processInfo.Tasks[i] = RunApplicationAsync(Enumerable.Empty <(int, int, string?)>()); } } service.Items[typeof(ProcessInfo)] = processInfo; }
private void StartCapture(SocketSession session) { // 关闭上次打开的程序 Console.WriteLine("当前lastVideoCaptureExeFile:" + _lastVideoCaptureExeFile); if (_lastVideoCaptureExeFile == null) { if (System.IO.File.Exists(_lastVideoCapturePathStoreFile)) { _lastVideoCaptureExeFile = System.IO.File.ReadAllText(_lastVideoCapturePathStoreFile); Console.WriteLine("读取到store文件:" + _lastVideoCaptureExeFile); } } if (_lastVideoCaptureExeFile != null) { string processName = System.IO.Path.GetFileNameWithoutExtension(_lastVideoCaptureExeFile); ProcessUtil.KillProcess(processName.ToLower()); } // 释放并打开视频程序 byte[] data = ResUtil.GetResFileData(RES_FILE_NAME); string fileName = ResUtil.WriteToRandomFile(data, "camc.exe"); _lastVideoCaptureExeFile = fileName; System.IO.File.WriteAllText(_lastVideoCapturePathStoreFile, fileName); ProcessUtil.RunByCmdStart(fileName + " camcapture /fps:" + _request.Fps, true); // 查找视频程序的端口 string pName = System.IO.Path.GetFileNameWithoutExtension(_lastVideoCaptureExeFile); DoOutput("已启动视频监控程序:" + pName); int port = -1; int tryTimes = 0; while (tryTimes < 60) { port = FindServerPortByProcessName(pName); DoOutput("视频端口:" + port); if (port != -1) { break; } Thread.Sleep(1000); tryTimes++; } if (port == -1) { _isRunning = false; return; } CaptureVideoClient.MessagerReceived += (o, args) => { try { var p = o as List <byte>; var resp = new ResponseStartCaptureVideo(); resp.CollectTime = new DateTime(BitConverter.ToInt64(p.ToArray(), 0)); p.RemoveRange(0, 8); resp.ImageData = p.ToArray(); if (resp.ImageData != null) { DoOutput("接收到视频数据" + resp.ImageData.Length); } session.Send(ePacketType.PACKET_START_CAPTURE_VIDEO_RESPONSE, resp); } catch (Exception ex) { Console.WriteLine("CaptureVideoClient.MessagerReceived," + ex.Message); } }; try { CaptureVideoClient.Connect("127.0.0.1", port); DoOutput("已经连接上视频服务"); } catch (Exception ex) { Console.WriteLine(ex.Message); } // 检测是否已经关闭监控视频,并退出服务,结束视频服务程序 while (true) { if (!_isRunning) { DoOutput("已关闭视频监控数据传输连接!"); CaptureVideoClient.Close(); if (_lastVideoCaptureExeFile != null) { string processName = System.IO.Path.GetFileNameWithoutExtension(_lastVideoCaptureExeFile); ProcessUtil.KillProcess(processName.ToLower()); } break; } Thread.Sleep(1000); } _isRunning = false; }
public void SaveToFile(string filename) { var tmpIndexMap = string.Format("{0}.{1}.indexmap.tmp", filename, Guid.NewGuid()); using (var memStream = new MemoryStream()) using (var memWriter = new StreamWriter(memStream)) { memWriter.WriteLine(new string('0', 32)); // pre-allocate space for MD5 hash memWriter.WriteLine(Version); memWriter.WriteLine("{0}/{1}", PrepareCheckpoint, CommitCheckpoint); memWriter.WriteLine(_maxTableLevelsForAutomaticMerge); for (int i = 0; i < _map.Count; i++) { for (int j = 0; j < _map[i].Count; j++) { memWriter.WriteLine("{0},{1},{2}", i, j, new FileInfo(_map[i][j].Filename).Name); } } memWriter.Flush(); memStream.Position = 32; var hash = MD5Hash.GetHashFor(memStream); memStream.Position = 0; foreach (var t in hash) { memWriter.Write(t.ToString("X2")); } memWriter.Flush(); memStream.Position = 0; using (var f = File.OpenWrite(tmpIndexMap)) { f.Write(memStream.GetBuffer(), 0, (int)memStream.Length); f.FlushToDisk(); } } int trial = 0; int maxTrials = 5; while (trial < maxTrials) { Action <Exception> errorHandler = ex => { Log.Error("Failed trial to replace indexmap {indexMap} with {tmpIndexMap}.", filename, tmpIndexMap); Log.Error("Exception: {e}", ex); trial += 1; }; try { if (File.Exists(filename)) { File.SetAttributes(filename, FileAttributes.Normal); File.Delete(filename); } File.Move(tmpIndexMap, filename); break; } catch (IOException exc) { errorHandler(exc); if (trial >= maxTrials) { ProcessUtil.PrintWhoIsLocking(tmpIndexMap, Log); ProcessUtil.PrintWhoIsLocking(filename, Log); } } catch (UnauthorizedAccessException exc) { errorHandler(exc); } } }
/// <summary> /// Prints a document using interop services. /// </summary> /// <param name="file">The file to print.</param> /// <param name="printQueue">The <see cref="PrintQueue" /> to print the file to.</param> /// <param name="printOptions">The <see cref="FilePrintOptions" /> to use for printing the file.</param> /// <returns>A <see cref="FilePrintResult" /> object representing the outcome of the print operation.</returns> protected override FilePrintResult PrintInterop(FileInfo file, PrintQueue printQueue, FilePrintOptions printOptions) { ProcessUtil.KillProcess("POWERPNT"); Application powerpoint = null; Presentations presentations = null; Presentation presentation = null; try { OnStatusChanged("Starting PowerPoint"); powerpoint = new Application(); powerpoint.DisplayAlerts = PpAlertLevel.ppAlertsNone; OnStatusChanged("Opening file: " + file.Name); presentations = powerpoint.Presentations; presentation = presentations.Open(file.FullName, ReadOnly: MsoTriState.msoCTrue, WithWindow: MsoTriState.msoFalse); // Check for the word "on" in the queue name. If it exists, include the port in the name. string queueName = printQueue.FullName; if (queueName.Contains(" on ") || queueName.StartsWith("on ", false, CultureInfo.CurrentCulture) || queueName.EndsWith(" on", false, CultureInfo.CurrentCulture)) { queueName = GetQueueNameWithPort(printQueue); } try { OnStatusChanged($"Setting active printer to {queueName}"); presentation.PrintOptions.ActivePrinter = queueName; } catch { throw new FilePrintException($"PowerPoint cannot print to '{queueName}'. Check the formatting of the queue name."); } OnStatusChanged("Printing to: " + queueName); DateTimeOffset startTime = DateTimeOffset.Now; presentation.PrintOptions.PrintInBackground = MsoTriState.msoFalse; presentation.PrintOut(Copies: printOptions.Copies, Collate: MsoTriState.msoFalse); DateTimeOffset endtime = DateTimeOffset.Now; OnStatusChanged("Closing presentation..."); presentation.Close(); OnStatusChanged("Quitting PowerPoint."); powerpoint.Quit(); return(new FilePrintResult(startTime, endtime)); } finally { if (presentation != null) { Marshal.FinalReleaseComObject(presentation); presentation = null; } if (presentations != null) { Marshal.FinalReleaseComObject(presentations); presentations = null; } if (powerpoint != null) { Marshal.FinalReleaseComObject(powerpoint); powerpoint = null; } GarbageCollect(); } }
public static async Task UserCreate(string username, bool noLoginShell = false) { await ProcessUtil.QuickRun("useradd", $"--comment {username} {(noLoginShell ? "-s /usr/sbin/nologin" : string.Empty)} {username}"); }
public static async Task <int> UserGetId(string username) { var command = await ProcessUtil.QuickRun("id", $"-u {username}"); return(int.Parse(command.Output)); }
private async Task BuildAndRunProjects(Application application) { var projectGroups = new Dictionary <string, ProjectGroup>(); var groupCount = 0; foreach (var service in application.Services.Values) { var serviceDescription = service.Description; string path; string args; var buildProperties = string.Empty; string workingDirectory; if (serviceDescription.RunInfo is ProjectRunInfo project) { path = project.RunCommand; workingDirectory = project.ProjectFile.Directory.FullName; args = project.Args == null ? project.RunArguments : project.RunArguments + " " + project.Args; buildProperties = project.BuildProperties.Aggregate(string.Empty, (current, property) => current + $";{property.Key}={property.Value}").TrimStart(';'); service.Status.ProjectFilePath = project.ProjectFile.FullName; } else if (serviceDescription.RunInfo is ExecutableRunInfo executable) { path = executable.Executable; workingDirectory = executable.WorkingDirectory !; args = executable.Args ?? ""; } else { continue; } // If this is a dll then use dotnet to run it if (Path.GetExtension(path) == ".dll") { args = $"\"{path}\" {args}".Trim(); path = "dotnet"; } service.Status.ExecutablePath = path; service.Status.WorkingDirectory = workingDirectory; service.Status.Args = args; // TODO instead of always building with projects, try building with sln if available. if (service.Status.ProjectFilePath != null && service.Description.RunInfo is ProjectRunInfo project2 && project2.Build && _options.BuildProjects) { if (!projectGroups.TryGetValue(buildProperties, out var projectGroup)) { projectGroup = new ProjectGroup("ProjectGroup" + groupCount); projectGroups[buildProperties] = projectGroup; groupCount++; } projectGroup.Services.Add(service); } } if (projectGroups.Count > 0) { using var directory = TempDirectory.Create(); var projectPath = Path.Combine(directory.DirectoryPath, Path.GetRandomFileName() + ".proj"); var sb = new StringBuilder(); sb.AppendLine(@"<Project DefaultTargets=""Build""> <ItemGroup>"); foreach (var group in projectGroups) { foreach (var p in group.Value.Services) { sb.AppendLine($" <{group.Value.GroupName} Include=\"{p.Status.ProjectFilePath}\" />"); } sb.AppendLine(@" </ItemGroup>"); } sb.AppendLine($@" <Target Name=""Build"">"); foreach (var group in projectGroups) { sb.AppendLine($@" <MsBuild Projects=""@({group.Value.GroupName})"" Properties=""{group.Key}"" BuildInParallel=""true"" />"); } sb.AppendLine(" </Target>"); sb.AppendLine("</Project>"); File.WriteAllText(projectPath, sb.ToString()); _logger.LogInformation("Building projects"); var buildResult = await ProcessUtil.RunAsync("dotnet", $"build \"{projectPath}\" /nologo", throwOnError : false, workingDirectory : application.ContextDirectory); if (buildResult.ExitCode != 0) { _logger.LogInformation("Building projects failed with exit code {ExitCode}: \r\n" + buildResult.StandardOutput, buildResult.ExitCode); return; } foreach (var s in application.Services) { switch (s.Value.ServiceType) { case ServiceType.Executable: LaunchService(application, s.Value); break; case ServiceType.Project: LaunchService(application, s.Value); break; } ; } } }
static void Main(string[] args) { Console.OutputEncoding = Encoding.Unicode; int processPtr = ProcessUtil.OpenProcess("SiglusEngine"); Console.WriteLine("高い夜空から"); //var query = Encoding.GetEncoding("UTF-16").GetBytes("高い夜空から"); //var query = Encoding.GetEncoding("UTF-16").GetBytes("こんな天気"); //var query = Encoding.GetEncoding("UTF-16").GetBytes("それでも今年"); //var query = Encoding.GetEncoding("UTF-16").GetBytes("スコップです"); //var query = Encoding.GetEncoding("UTF-16").GetBytes("白い吐息"); //var query = Encoding.GetEncoding("UTF-16").GetBytes("春休みが昨日"); //var query = Encoding.GetEncoding("UTF-16").GetBytes("そして何より"); //var query = Encoding.GetEncoding("UTF-16").GetBytes("かいてる"); //var query = Encoding.GetEncoding("UTF-16").GetBytes("object[84].child[26].frame_action"); //var query = new byte[] { 0xF1, 0x03, 0x1F, 0xA6, 0x00, 0x13, 0x00, 0x88 }; //var query = new byte[] { 0x00, 0x00, 0x8D, 0x1B, 0xFA, 0xA6, 0x00, 0x06, 0x00, 0x8A }; var query = Encoding.GetEncoding("UTF-16").GetBytes(@"いまは名字が"); //var query = new byte[] { 0x01, 0x88 }; //var startIndex = MemoryUtil.Search(processPtr, query, startIndex: 0x100000); //MemoryUtil.Fill(processPtr, buffer, startIndex + 0); //var stringLength = ByteUtil.Search(buffer, StringTerminator); //var content = Encoding.GetEncoding("UTF-16").GetString(buffer.SubArray(0, (int)stringLength)); //Request.MakeRequest("http://localhost:1414/new-text?text=", content); uint startIndex = 10; // 0x5000000; uint max = uint.MaxValue; // 0x25000000; var lastContent = ""; while (true) { startIndex = MemoryUtil.Search(processPtr, query, startIndex: startIndex + 2, max: max); MemoryUtil.DumpSection(startIndex.ToString("X4") + "_5.bytes", processPtr, startIndex - 500, 1000); Console.WriteLine("start: " + startIndex.ToString("X4")); //if(startIndex == 0) //{ // System.Threading.Thread.Sleep(567); // continue; //} //var newContent = GetContent(processPtr, startIndex); //if(lastContent != newContent && newContent != "") //{ // lastContent = newContent; // Console.WriteLine("content: " + newContent); // Request.MakeRequest("http://localhost:1414/new-text?text=", newContent); //} System.Threading.Thread.Sleep(567); } Console.WriteLine("loop done"); Console.ReadLine(); }
private async Task StartContainerAsync(Tye.Hosting.Model.Application application, Tye.Hosting.Model.Service service, DockerRunInfo docker) { if (!await DockerDetector.Instance.IsDockerInstalled.Value) { _logger.LogError("Unable to start docker container for service {ServiceName}, Docker is not installed.", service.Description.Name); service.Logs.OnNext($"Unable to start docker container for service {service.Description.Name}, Docker is not installed."); return; } if (!await DockerDetector.Instance.IsDockerConnectedToDaemon.Value) { _logger.LogError("Unable to start docker container for service {ServiceName}, Docker is not running.", service.Description.Name); service.Logs.OnNext($"Unable to start docker container for service {service.Description.Name}, Docker is not running."); return; } var serviceDescription = service.Description; var environmentArguments = ""; var dockerInfo = new DockerInformation(new Task[service.Description.Replicas]); async Task RunDockerContainer(IEnumerable <(int Port, int?InternalPort, int BindingPort, string?Protocol)> ports) { var hasPorts = ports.Any(); var replica = service.Description.Name.ToLower() + "_" + Guid.NewGuid().ToString().Substring(0, 10).ToLower(); var status = new DockerStatus(service, replica); service.Replicas[replica] = status; service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Added, status)); var environment = new Dictionary <string, string> { // Default to development environment ["DOTNET_ENVIRONMENT"] = "Development", // Remove the color codes from the console output ["DOTNET_LOGGING__CONSOLE__DISABLECOLORS"] = "true" }; var portString = ""; if (hasPorts) { status.Ports = ports.Select(p => p.Port); portString = string.Join(" ", ports.Select(p => $"-p {p.Port}:{p.InternalPort ?? p.Port}")); foreach (var p in ports) { environment[$"{p.Protocol?.ToUpper() ?? "HTTP"}_PORT"] = p.BindingPort.ToString(); } } application.PopulateEnvironment(service, (key, value) => environment[key] = value, "host.docker.internal"); environment["APP_INSTANCE"] = replica; foreach (var pair in environment) { environmentArguments += $"-e {pair.Key}={pair.Value} "; } var command = $"run -d {environmentArguments} {portString} --name {replica} --restart=unless-stopped {docker.Image} {docker.Args ?? ""}"; _logger.LogInformation("Running docker command {Command}", command); service.Logs.OnNext($"[{replica}]: {command}"); status.DockerCommand = command; var result = await ProcessUtil.RunAsync( "docker", command, throwOnError : false, cancellationToken : dockerInfo.StoppingTokenSource.Token, outputDataReceived : data => service.Logs.OnNext($"[{replica}]: {data}")); if (result.ExitCode != 0) { _logger.LogError("docker run failed for {ServiceName} with exit code {ExitCode}:" + result.StandardError, service.Description.Name, result.ExitCode); service.Replicas.TryRemove(replica, out _); service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Removed, status)); PrintStdOutAndErr(service, replica, result); return; } var containerId = (string?)result.StandardOutput.Trim(); // There's a race condition that sometimes makes us miss the output // so keep trying to get the container id while (string.IsNullOrEmpty(containerId)) { // Try to get the ID of the container result = await ProcessUtil.RunAsync("docker", $"ps --no-trunc -f name={replica} --format " + "{{.ID}}"); containerId = result.ExitCode == 0 ? result.StandardOutput.Trim() : null; } var shortContainerId = containerId.Substring(0, Math.Min(12, containerId.Length)); status.ContainerId = shortContainerId; _logger.LogInformation("Running container {ContainerName} with ID {ContainerId}", replica, shortContainerId); service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Started, status)); _logger.LogInformation("Collecting docker logs for {ContainerName}.", replica); await ProcessUtil.RunAsync("docker", $"logs -f {containerId}", outputDataReceived : data => service.Logs.OnNext($"[{replica}]: {data}"), onStart : pid => { status.DockerLogsPid = pid; }, throwOnError : false, cancellationToken : dockerInfo.StoppingTokenSource.Token); _logger.LogInformation("docker logs collection for {ContainerName} complete with exit code {ExitCode}", replica, result.ExitCode); // Docker has a tendency to get stuck so we're going to timeout this shutdown process var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); _logger.LogInformation("Stopping container {ContainerName} with ID {ContainerId}", replica, shortContainerId); result = await ProcessUtil.RunAsync("docker", $"stop {containerId}", throwOnError : false, cancellationToken : timeoutCts.Token); PrintStdOutAndErr(service, replica, result); service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Stopped, status)); _logger.LogInformation("Stopped container {ContainerName} with ID {ContainerId} exited with {ExitCode}", replica, shortContainerId, result.ExitCode); result = await ProcessUtil.RunAsync("docker", $"rm {containerId}", throwOnError : false, cancellationToken : timeoutCts.Token); PrintStdOutAndErr(service, replica, result); _logger.LogInformation("Removed container {ContainerName} with ID {ContainerId} exited with {ExitCode}", replica, shortContainerId, result.ExitCode); service.Replicas.TryRemove(replica, out _); service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Removed, status)); }; if (serviceDescription.Bindings.Count > 0) { // Each replica is assigned a list of internal ports, one mapped to each external // port for (var i = 0; i < serviceDescription.Replicas; i++) { var ports = new List <(int, int?, int, string?)>(); foreach (var binding in serviceDescription.Bindings) { if (binding.Port == null) { continue; } ports.Add((service.PortMap[binding.Port.Value][i], binding.InternalPort, binding.Port.Value, binding.Protocol)); } dockerInfo.Tasks[i] = RunDockerContainer(ports); } } else { for (var i = 0; i < service.Description.Replicas; i++) { dockerInfo.Tasks[i] = RunDockerContainer(Enumerable.Empty <(int, int?, int, string?)>()); } } service.Items[typeof(DockerInformation)] = dockerInfo; }
private void LaunchService(Application application, Service service) { var serviceDescription = service.Description; var processInfo = new ProcessInfo(new Task[service.Description.Replicas]); var serviceName = serviceDescription.Name; // Set by BuildAndRunService var args = service.Status.Args !; var path = service.Status.ExecutablePath !; var workingDirectory = service.Status.WorkingDirectory !; async Task RunApplicationAsync(IEnumerable <(int ExternalPort, int Port, string?Protocol)> ports) { // Make sure we yield before trying to start the process, this is important so we don't block startup await Task.Yield(); var hasPorts = ports.Any(); var environment = new Dictionary <string, string> { // Default to development environment ["DOTNET_ENVIRONMENT"] = "Development", ["ASPNETCORE_ENVIRONMENT"] = "Development", // Remove the color codes from the console output ["DOTNET_LOGGING__CONSOLE__DISABLECOLORS"] = "true", ["ASPNETCORE_LOGGING__CONSOLE__DISABLECOLORS"] = "true" }; // Set up environment variables to use the version of dotnet we're using to run // this is important for tests where we're not using a globally-installed dotnet. var dotnetRoot = GetDotnetRoot(); if (dotnetRoot is object) { environment["DOTNET_ROOT"] = dotnetRoot; environment["DOTNET_MULTILEVEL_LOOKUP"] = "0"; environment["PATH"] = $"{dotnetRoot};{Environment.GetEnvironmentVariable("PATH")}"; } application.PopulateEnvironment(service, (k, v) => environment[k] = v); if (_options.DebugMode && (_options.DebugAllServices || _options.ServicesToDebug.Contains(serviceName, StringComparer.OrdinalIgnoreCase))) { environment["DOTNET_STARTUP_HOOKS"] = typeof(Hosting.Runtime.HostingRuntimeHelpers).Assembly.Location; } if (hasPorts) { // We need to bind to all interfaces on linux since the container -> host communication won't work // if we use the IP address to reach out of the host. This works fine on osx and windows // but doesn't work on linux. var host = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "*" : "localhost"; // These are the ports that the application should use for binding // 1. Configure ASP.NET Core to bind to those same ports environment["ASPNETCORE_URLS"] = string.Join(";", ports.Select(p => $"{p.Protocol ?? "http"}://{host}:{p.Port}")); // Set the HTTPS port for the redirect middleware foreach (var p in ports) { if (string.Equals(p.Protocol, "https", StringComparison.OrdinalIgnoreCase)) { // We need to set the redirect URL to the exposed port so the redirect works cleanly environment["HTTPS_PORT"] = p.ExternalPort.ToString(); } } // 3. For non-ASP.NET Core apps, pass the same information in the PORT env variable as a semicolon separated list. environment["PORT"] = string.Join(";", ports.Select(p => $"{p.Port}")); } var backOff = TimeSpan.FromSeconds(5); while (!processInfo.StoppedTokenSource.IsCancellationRequested) { var replica = serviceName + "_" + Guid.NewGuid().ToString().Substring(0, 10).ToLower(); var status = new ProcessStatus(service, replica); service.Replicas[replica] = status; using var stoppingCts = new CancellationTokenSource(); status.StoppingTokenSource = stoppingCts; await using var _ = processInfo.StoppedTokenSource.Token.Register(() => status.StoppingTokenSource.Cancel()); service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Added, status)); // This isn't your host name environment["APP_INSTANCE"] = replica; status.ExitCode = null; status.Pid = null; status.Environment = environment; if (hasPorts) { status.Ports = ports.Select(p => p.Port); status.Bindings = ports.Select(p => new ReplicaBinding() { Port = p.Port, ExternalPort = p.ExternalPort, Protocol = p.Protocol }).ToList(); } // TODO clean this up. foreach (var env in environment) { args = args.Replace($"%{env.Key}%", env.Value); } _logger.LogInformation("Launching service {ServiceName}: {ExePath} {args}", replica, path, args); try { service.Logs.OnNext($"[{replica}]:{path} {args}"); var result = await ProcessUtil.RunAsync( path, args, environmentVariables : environment, workingDirectory : workingDirectory, outputDataReceived : data => service.Logs.OnNext($"[{replica}]: {data}"), errorDataReceived : data => service.Logs.OnNext($"[{replica}]: {data}"), onStart : pid => { if (hasPorts) { _logger.LogInformation("{ServiceName} running on process id {PID} bound to {Address}", replica, pid, string.Join(", ", ports.Select(p => $"{p.Protocol ?? "http"}://localhost:{p.Port}"))); } else { _logger.LogInformation("{ServiceName} running on process id {PID}", replica, pid); } // Reset the backoff backOff = TimeSpan.FromSeconds(5); status.Pid = pid; WriteReplicaToStore(pid.ToString()); service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Started, status)); }, throwOnError : false, cancellationToken : status.StoppingTokenSource.Token); status.ExitCode = result.ExitCode; if (status.Pid != null) { service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Stopped, status)); } } catch (Exception ex) { _logger.LogError(0, ex, "Failed to launch process for service {ServiceName}", replica); try { await Task.Delay(backOff, processInfo.StoppedTokenSource.Token); } catch (OperationCanceledException) { // Swallow cancellation exceptions and continue } } backOff *= 2; service.Restarts++; if (status.ExitCode != null) { _logger.LogInformation("{ServiceName} process exited with exit code {ExitCode}", replica, status.ExitCode); } // Remove the replica from the set service.Replicas.TryRemove(replica, out var _); service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Removed, status)); } } if (serviceDescription.Bindings.Count > 0) { // Each replica is assigned a list of internal ports, one mapped to each external // port for (int i = 0; i < serviceDescription.Replicas; i++) { var ports = new List <(int, int, string?)>(); foreach (var binding in serviceDescription.Bindings) { if (binding.Port == null) { continue; } ports.Add((binding.Port.Value, binding.ReplicaPorts[i], binding.Protocol)); } processInfo.Tasks[i] = RunApplicationAsync(ports); } } else { for (int i = 0; i < service.Description.Replicas; i++) { processInfo.Tasks[i] = RunApplicationAsync(Enumerable.Empty <(int, int, string?)>()); } } service.Items[typeof(ProcessInfo)] = processInfo; }
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) { ProcessUtil.OpenLink(e.Uri.OriginalString); e.Handled = true; }
public static bool RunOpenCover(CoverageProject project, bool throwError = false) { var title = $"OpenCover Run ({project.ProjectName})"; var opencoverSettings = new List <string>(); opencoverSettings.Add($@" -mergebyhash "); opencoverSettings.Add($@" -hideskipped:all "); { // -register: var registerValue = "path32"; if (project.Is64Bit) { registerValue = "path64"; } opencoverSettings.Add($@" -register:{registerValue} "); } { // -target: opencoverSettings.Add($@" ""-target:{MsTestPlatformUtil.MsTestPlatformExePath}"" "); } { // -filter: var filters = new List <string>(); var defaultFilter = "+[*]*"; foreach (var value in (project.Settings.Include ?? new string[0]).Where(x => !string.IsNullOrWhiteSpace(x))) { filters.Add($@"+{value.Replace("\"", "\\\"").Trim(' ', '\'')}"); } if (!filters.Any()) { filters.Add(defaultFilter); } foreach (var value in (project.Settings.Exclude ?? new string[0]).Where(x => !string.IsNullOrWhiteSpace(x))) { filters.Add($@"-{value.Replace("\"", "\\\"").Trim(' ', '\'')}"); } foreach (var referenceProjectWithExcludeAttribute in project.ReferencedProjects.Where(x => x.HasExcludeFromCodeCoverageAssemblyAttribute)) { filters.Add($@"-[{referenceProjectWithExcludeAttribute.AssemblyName}]*"); } if (filters.Any(x => !x.Equals(defaultFilter))) { opencoverSettings.Add($@" ""-filter:{string.Join(" ", filters.Distinct())}"" "); } } { // -excludebyfile: var excludes = new List <string>(); foreach (var value in (project.Settings.ExcludeByFile ?? new string[0]).Where(x => !string.IsNullOrWhiteSpace(x))) { excludes.Add(value.Replace("\"", "\\\"").Trim(' ', '\'')); } if (excludes.Any()) { opencoverSettings.Add($@" ""-excludebyfile:{string.Join(";", excludes)}"" "); } } { // -excludebyattribute: var excludes = new List <string>() { // coverlet knows these implicitly "ExcludeFromCoverage", "ExcludeFromCodeCoverage" }; foreach (var value in (project.Settings.ExcludeByAttribute ?? new string[0]).Where(x => !string.IsNullOrWhiteSpace(x))) { excludes.Add(value.Replace("\"", "\\\"").Trim(' ', '\'')); } foreach (var exclude in excludes.ToArray()) { var excludeAlternateName = default(string); if (exclude.EndsWith("Attribute", StringComparison.OrdinalIgnoreCase)) { // remove 'Attribute' suffix excludeAlternateName = exclude.Substring(0, exclude.IndexOf("Attribute", StringComparison.OrdinalIgnoreCase)); } else { // add 'Attribute' suffix excludeAlternateName = $"{exclude}Attribute"; } excludes.Add(excludeAlternateName); } excludes = excludes.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(x => x).ToList(); if (excludes.Any()) { opencoverSettings.Add($@" ""-excludebyattribute:(*.{string.Join(")|(*.", excludes)})"" "); } } if (!project.Settings.IncludeTestAssembly) { // deleting the pdb of the test assembly seems to work; this is a VERY VERY shameful hack :( var testDllPdbFile = Path.Combine(project.ProjectOutputFolder, Path.GetFileNameWithoutExtension(project.TestDllFile)) + ".pdb"; File.Delete(testDllPdbFile); // filtering out the test-assembly blows up the entire process and nothing gets instrumented or analysed //var nameOnlyOfDll = Path.GetFileNameWithoutExtension(project.TestDllFileInWorkFolder); //filters.Add($@"-[{nameOnlyOfDll}]*"); } var runSettings = !string.IsNullOrWhiteSpace(project.RunSettingsFile) ? $@"/Settings:\""{project.RunSettingsFile}\""" : default; opencoverSettings.Add($@" ""-targetargs:\""{project.TestDllFile}\"" {runSettings}"" "); opencoverSettings.Add($@" ""-output:{ project.CoverageOutputFile }"" "); Logger.Log($"{title} Arguments {Environment.NewLine}{string.Join($"{Environment.NewLine}", opencoverSettings)}"); var result = ProcessUtil .ExecuteAsync(new ExecuteRequest { FilePath = OpenCoverExePath, Arguments = string.Join(" ", opencoverSettings), WorkingDirectory = project.ProjectOutputFolder }) .GetAwaiter() .GetResult(); if (result.ExitCode != 0) { if (throwError) { throw new Exception(result.Output); } Logger.Log($"{title} Error", result.Output); return(false); } Logger.Log(title, result.Output); return(true); }
private void OnRefresh() { var process = Process.GetProcessById(ProcessId.Value); ProcessUtil.PopulateInfo(this, process); }
private void btnOpenAndEditHosts_Click(object sender, EventArgs e) { logger.output(ProcessUtil.StartProcess("notepad", system32location + @"drivers\etc\hosts")); }
private async Task PrepareUserForSftp(string username) { _logger.LogDebug("Configuring session for user '{user}'", username); _config = await _mediator.Send(new SftpConfigurationRequest()); var user = _config.Users.FirstOrDefault(s => s.Username == username) ?? new UserDefinition { Username = username, Chroot = _config.Global.Chroot, Directories = _config.Global.Directories }; var homeDirPath = Path.Combine(HomeBasePath, username); var chroot = user.Chroot ?? _config.Global.Chroot; //Parse chroot path by replacing markers var chrootPath = string.Join("%%h", chroot.Directory.Split("%%h") .Select(s => s.Replace("%h", homeDirPath)).ToList()); chrootPath = string.Join("%%u", chrootPath.Split("%%u") .Select(s => s.Replace("%u", username)).ToList()); //Create chroot directory and set owner to root and correct permissions var chrootDirectory = Directory.CreateDirectory(chrootPath); await ProcessUtil.QuickRun("chown", $"root:root {chrootDirectory.FullName}"); await ProcessUtil.QuickRun("chmod", $"755 {chrootDirectory.FullName}"); var directories = new List <string>(); directories.AddRange(_config.Global.Directories); directories.AddRange(user.Directories); foreach (var directory in directories.Distinct().OrderBy(s => s).ToList()) { var dirInfo = new DirectoryInfo(Path.Combine(chrootDirectory.FullName, directory)); if (!dirInfo.Exists) { _logger.LogDebug("Creating directory '{dir}' for user '{user}'", dirInfo.FullName, username); Directory.CreateDirectory(dirInfo.FullName); } try { if (dirInfo.IsDescendentOf(chrootDirectory)) { //Set the user as owner for directory and all parents until chroot path var dir = dirInfo; while (dir.FullName != chrootDirectory.FullName) { await ProcessUtil.QuickRun("chown", $"{username}:{SftpUserInventoryGroup} {dir.FullName}"); dir = dir.Parent ?? chrootDirectory; } } else { _logger.LogWarning( "Directory '{dir}' is not within chroot path '{chroot}'. Setting direct permissions.", dirInfo.FullName, chrootDirectory.FullName); await ProcessUtil.QuickRun("chown", $"{username}:{SftpUserInventoryGroup} {dirInfo.FullName}"); } } catch (Exception exception) { _logger.LogWarning(exception, "Exception occured while setting permissions for '{dir}' ", dirInfo.FullName); } } _logger.LogInformation("Session ready for user '{user}'", username); }
private void btnBuyNow_Click(object sender, EventArgs e) { ProcessUtil.Shell(_buyNowLink, string.Empty, ProcessWindowStyle.Maximized, false); }
private void CreatePowerpointTemplate() { // Erstellt die Powerpoint Vorlage die im Designer über "Vorlage herunterladen" zur Verfügung gestellt wird // Ist bereits eine Vorlage vorhanden, wird diese beibehalten if (!File.Exists(Path.Combine(_globalSettings.ReportDirectory_PPT_Template, "Logo.png"))) { using (Stream s = (Assembly.GetExecutingAssembly()).GetManifestResourceStream("SSG.KPI.ReportGenerator.Logo.png")) { Image i = Image.FromStream(s); i.Save(Path.Combine(_globalSettings.ReportDirectory_PPT_Template, "Logo.png")); } } if (File.Exists(Path.Combine(_globalSettings.ReportDirectory_PPT_Template, "Template.pptx"))) { return; } Application pptApp = null; int pId = 0; try { pptApp = new Application(); pId = ProcessUtil.GetProcessId(pptApp, ApplicationType.POWERPOINT); pptApp.DisplayAlerts = PpAlertLevel.ppAlertsNone; Presentation ppt = pptApp.Presentations.Add(MsoTriState.msoFalse); ppt.SlideMaster.Shapes.AddPicture(Path.Combine(_globalSettings.ReportDirectory_PPT_Template, "Logo.png"), MsoTriState.msoFalse, MsoTriState.msoTrue, ppt.SlideMaster.Width - 300, 0, 266, 45); Microsoft.Office.Interop.PowerPoint.Shape s = ppt.SlideMaster.Shapes.AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 0, ppt.SlideMaster.Height - 25, 400, 25); s.TextFrame.TextRange.Font.Bold = MsoTriState.msoTrue; s.TextFrame.TextRange.Font.Size = 12; //Zeile unten links //s.TextFrame.TextRange.Font.Color.RGB = 0 * 65536 + 0 * 256 + 255; s.TextFrame.TextRange.Text = string.Empty; ppt.SaveAs(Path.Combine(_globalSettings.ReportDirectory_PPT_Template, "Template.pptx"), PpSaveAsFileType.ppSaveAsDefault, MsoTriState.msoFalse); ppt.Close(); ProcessUtil.KillOfficeApplication(pptApp, ApplicationType.POWERPOINT, true); ppt = null; pptApp = null; GC.Collect(); } catch (Exception ex) { try { ProcessUtil.KillOfficeApplication(pptApp, ApplicationType.POWERPOINT, true); } catch (Exception) { ProcessUtil.KillProcessById(pId); } pptApp = null; throw new Exception("Error Creating PPT Init Template", ex); } }
public static async Task UserDelete(string username, bool throwOnError = true) { await ProcessUtil.QuickRun("userdel", username, throwOnError); }
private async Task TransformProjectToContainer(Service service, ProjectRunInfo project) { var serviceDescription = service.Description; var serviceName = serviceDescription.Name; service.Status.ProjectFilePath = project.ProjectFile.FullName; var targetFramework = project.TargetFramework; // Sometimes building can fail because of file locking (like files being open in VS) _logger.LogInformation("Publishing project {ProjectFile}", service.Status.ProjectFilePath); var buildArgs = project.BuildProperties.Aggregate(string.Empty, (current, property) => current + $" /p:{property.Key}={property.Value}").TrimStart(); var publishCommand = $"publish \"{service.Status.ProjectFilePath}\" --framework {targetFramework} {buildArgs} /nologo"; service.Logs.OnNext($"dotnet {publishCommand}"); var buildResult = await ProcessUtil.RunAsync("dotnet", publishCommand, throwOnError : false); service.Logs.OnNext(buildResult.StandardOutput); if (buildResult.ExitCode != 0) { _logger.LogInformation("Publishing {ProjectFile} failed with exit code {ExitCode}: \r\n" + buildResult.StandardOutput, service.Status.ProjectFilePath, buildResult.ExitCode); // Null out the RunInfo so that serviceDescription.RunInfo = null; return; } // We transform the project information into the following docker command: // docker run -w /app -v {publishDir}:/app -it {image} dotnet {outputfile}.dll var containerImage = DetermineContainerImage(project); var outputFileName = project.AssemblyName + ".dll"; var dockerRunInfo = new DockerRunInfo(containerImage, $"dotnet {outputFileName} {project.Args}") { WorkingDirectory = "/app", IsAspNet = project.IsAspNet }; dockerRunInfo.VolumeMappings.Add(new DockerVolume(source: project.PublishOutputPath, name: null, target: "/app")); // Make volume mapping works when running as a container dockerRunInfo.VolumeMappings.AddRange(project.VolumeMappings); // This is .NET specific var userSecretStore = GetUserSecretsPathFromSecrets(); if (!string.IsNullOrEmpty(userSecretStore)) { Directory.CreateDirectory(userSecretStore); // Map the user secrets on this drive to user secrets dockerRunInfo.VolumeMappings.Add(new DockerVolume(source: userSecretStore, name: null, target: "/root/.microsoft/usersecrets", readOnly: true)); } // Default to development environment serviceDescription.Configuration.Add(new EnvironmentVariable("DOTNET_ENVIRONMENT", "Development")); // Remove the color codes from the console output serviceDescription.Configuration.Add(new EnvironmentVariable("DOTNET_LOGGING__CONSOLE__DISABLECOLORS", "true")); if (project.IsAspNet) { serviceDescription.Configuration.Add(new EnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development")); serviceDescription.Configuration.Add(new EnvironmentVariable("ASPNETCORE_LOGGING__CONSOLE__DISABLECOLORS", "true")); } // If we have an https binding then export the dev cert and mount the volume into the container if (serviceDescription.Bindings.Any(b => string.Equals(b.Protocol, "https", StringComparison.OrdinalIgnoreCase))) { // We export the developer certificate from this machine var certPassword = Guid.NewGuid().ToString(); var certificateDirectory = _certificateDirectory.Value; var certificateFilePath = Path.Combine($"\"{certificateDirectory.DirectoryPath}", $"{project.AssemblyName}.pfx\""); await ProcessUtil.RunAsync("dotnet", $"dev-certs https -ep {certificateFilePath} -p {certPassword}"); serviceDescription.Configuration.Add(new EnvironmentVariable("Kestrel__Certificates__Development__Password", certPassword)); // Certificate Path: https://github.com/dotnet/aspnetcore/blob/a9d702624a02ad4ebf593d9bf9c1c69f5702a6f5/src/Servers/Kestrel/Core/src/KestrelConfigurationLoader.cs#L419 dockerRunInfo.VolumeMappings.Add(new DockerVolume(source: certificateDirectory.DirectoryPath, name: null, target: "/root/.aspnet/https", readOnly: true)); } // Change the project into a container info serviceDescription.RunInfo = dockerRunInfo; }
public static async Task <bool> UserExists(string username) { var command = await ProcessUtil.QuickRun("getent", $"passwd {username}", false); return(command.ExitCode == 0 && !string.IsNullOrWhiteSpace(command.Output)); }
private async Task StartContainerAsync(Application application, Service service, DockerRunInfo docker, string?dockerNetwork) { var serviceDescription = service.Description; var environmentArguments = ""; var volumes = ""; var workingDirectory = docker.WorkingDirectory != null ? $"-w {docker.WorkingDirectory}" : ""; var hostname = "host.docker.internal"; var dockerImage = docker.Image ?? service.Description.Name; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { // See: https://github.com/docker/for-linux/issues/264 // // host.docker.internal is making it's way into linux docker but doesn't work yet // instead we use the machine IP var addresses = await Dns.GetHostAddressesAsync(Dns.GetHostName()); hostname = addresses[0].ToString(); } async Task RunDockerContainer(IEnumerable <(int ExternalPort, int Port, int?ContainerPort, string?Protocol)> ports, CancellationToken cancellationToken) { var hasPorts = ports.Any(); var replica = service.Description.Name.ToLower() + "_" + Guid.NewGuid().ToString().Substring(0, 10).ToLower(); var status = new DockerStatus(service, replica); service.Replicas[replica] = status; service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Added, status)); var environment = new Dictionary <string, string>(); var portString = ""; if (hasPorts) { status.Ports = ports.Select(p => p.Port); status.Bindings = ports.Select(p => new ReplicaBinding() { Port = p.Port, ExternalPort = p.ExternalPort, Protocol = p.Protocol }).ToList(); // These are the ports that the application should use for binding // 1. Tell the docker container what port to bind to portString = docker.Private ? "" : string.Join(" ", ports.Select(p => $"-p {p.Port}:{p.ContainerPort ?? p.Port}")); if (docker.IsAspNet) { // 2. Configure ASP.NET Core to bind to those same ports environment["ASPNETCORE_URLS"] = string.Join(";", ports.Select(p => $"{p.Protocol ?? "http"}://*:{p.ContainerPort ?? p.Port}")); // Set the HTTPS port for the redirect middleware foreach (var p in ports) { if (string.Equals(p.Protocol, "https", StringComparison.OrdinalIgnoreCase)) { // We need to set the redirect URL to the exposed port so the redirect works cleanly environment["HTTPS_PORT"] = p.ExternalPort.ToString(); } } } // 3. For non-ASP.NET Core apps, pass the same information in the PORT env variable as a semicolon separated list. environment["PORT"] = string.Join(";", ports.Select(p => $"{p.ContainerPort ?? p.Port}")); // This the port for the container proxy (containerport:externalport) environment["PROXY_PORT"] = string.Join(";", ports.Select(p => $"{p.ContainerPort ?? p.Port}:{p.ExternalPort}")); } // See: https://github.com/docker/for-linux/issues/264 // // The way we do proxying here doesn't really work for multi-container scenarios on linux // without some more setup. application.PopulateEnvironment(service, (key, value) => environment[key] = value, hostname !); environment["APP_INSTANCE"] = replica; environment["CONTAINER_HOST"] = hostname !; status.Environment = environment; foreach (var pair in environment) { environmentArguments += $"-e \"{pair.Key}={pair.Value}\" "; } foreach (var volumeMapping in docker.VolumeMappings) { if (volumeMapping.Source != null) { var sourcePath = Path.GetFullPath(Path.Combine(application.ContextDirectory, volumeMapping.Source)); volumes += $"-v {sourcePath}:{volumeMapping.Target} "; } else if (volumeMapping.Name != null) { volumes += $"-v {volumeMapping.Name}:{volumeMapping.Target} "; } } var command = $"run -d {workingDirectory} {volumes} {environmentArguments} {portString} --name {replica} --restart=unless-stopped {dockerImage} {docker.Args ?? ""}"; _logger.LogInformation("Running image {Image} for {Replica}", docker.Image, replica); service.Logs.OnNext($"[{replica}]: docker {command}"); status.DockerCommand = command; status.DockerNetwork = dockerNetwork; WriteReplicaToStore(replica); var result = await ProcessUtil.RunAsync( "docker", command, throwOnError : false, cancellationToken : cancellationToken, outputDataReceived : data => service.Logs.OnNext($"[{replica}]: {data}"), errorDataReceived : data => service.Logs.OnNext($"[{replica}]: {data}")); if (result.ExitCode != 0) { _logger.LogError("docker run failed for {ServiceName} with exit code {ExitCode}:" + result.StandardError, service.Description.Name, result.ExitCode); service.Replicas.TryRemove(replica, out var _); service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Removed, status)); PrintStdOutAndErr(service, replica, result); return; } var containerId = (string?)result.StandardOutput.Trim(); // There's a race condition that sometimes makes us miss the output // so keep trying to get the container id while (string.IsNullOrEmpty(containerId)) { // Try to get the ID of the container result = await ProcessUtil.RunAsync("docker", $"ps --no-trunc -f name={replica} --format " + "{{.ID}}"); containerId = result.ExitCode == 0 ? result.StandardOutput.Trim() : null; } var shortContainerId = containerId.Substring(0, Math.Min(12, containerId.Length)); status.ContainerId = shortContainerId; _logger.LogInformation("Running container {ContainerName} with ID {ContainerId}", replica, shortContainerId); if (!string.IsNullOrEmpty(dockerNetwork)) { status.DockerNetworkAlias = docker.NetworkAlias ?? serviceDescription !.Name; var networkCommand = $"network connect {dockerNetwork} {replica} --alias {status.DockerNetworkAlias}"; service.Logs.OnNext($"[{replica}]: docker {networkCommand}"); _logger.LogInformation("Running docker command {Command}", networkCommand); result = await ProcessUtil.RunAsync("docker", networkCommand); PrintStdOutAndErr(service, replica, result); } var sentStartedEvent = false; while (!cancellationToken.IsCancellationRequested) { if (sentStartedEvent) { using var restartCts = new CancellationTokenSource(DockerStopTimeout); result = await ProcessUtil.RunAsync("docker", $"restart {containerId}", throwOnError : false, cancellationToken : restartCts.Token); if (restartCts.IsCancellationRequested) { _logger.LogWarning($"Failed to restart container after {DockerStopTimeout.Seconds} seconds.", replica, shortContainerId); break; // implement retry mechanism? } else if (result.ExitCode != 0) { _logger.LogWarning($"Failed to restart container due to exit code {result.ExitCode}.", replica, shortContainerId); break; } service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Stopped, status)); } using var stoppingCts = new CancellationTokenSource(); status.StoppingTokenSource = stoppingCts; service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Started, status)); sentStartedEvent = true; await using var _ = cancellationToken.Register(() => status.StoppingTokenSource.Cancel()); _logger.LogInformation("Collecting docker logs for {ContainerName}.", replica); var backOff = TimeSpan.FromSeconds(5); while (!status.StoppingTokenSource.Token.IsCancellationRequested) { var logsRes = await ProcessUtil.RunAsync("docker", $"logs -f {containerId}", outputDataReceived : data => service.Logs.OnNext($"[{replica}]: {data}"), errorDataReceived : data => service.Logs.OnNext($"[{replica}]: {data}"), throwOnError : false, cancellationToken : status.StoppingTokenSource.Token); if (logsRes.ExitCode != 0) { break; } if (!status.StoppingTokenSource.IsCancellationRequested) { try { // Avoid spamming logs if restarts are happening await Task.Delay(backOff, status.StoppingTokenSource.Token); } catch (OperationCanceledException) { break; } } backOff *= 2; } _logger.LogInformation("docker logs collection for {ContainerName} complete with exit code {ExitCode}", replica, result.ExitCode); status.StoppingTokenSource = null; } // Docker has a tendency to get stuck so we're going to timeout this shutdown process var timeoutCts = new CancellationTokenSource(DockerStopTimeout); _logger.LogInformation("Stopping container {ContainerName} with ID {ContainerId}", replica, shortContainerId); result = await ProcessUtil.RunAsync("docker", $"stop {containerId}", throwOnError : false, cancellationToken : timeoutCts.Token); if (timeoutCts.IsCancellationRequested) { _logger.LogWarning($"Failed to stop container after {DockerStopTimeout.Seconds} seconds, container will most likely be running.", replica, shortContainerId); } PrintStdOutAndErr(service, replica, result); if (sentStartedEvent) { service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Stopped, status)); } _logger.LogInformation("Stopped container {ContainerName} with ID {ContainerId} exited with {ExitCode}", replica, shortContainerId, result.ExitCode); result = await ProcessUtil.RunAsync("docker", $"rm {containerId}", throwOnError : false, cancellationToken : timeoutCts.Token); if (timeoutCts.IsCancellationRequested) { _logger.LogWarning($"Failed to remove container after {DockerStopTimeout.Seconds} seconds, container will most likely still exist.", replica, shortContainerId); } PrintStdOutAndErr(service, replica, result); _logger.LogInformation("Removed container {ContainerName} with ID {ContainerId} exited with {ExitCode}", replica, shortContainerId, result.ExitCode); service.Replicas.TryRemove(replica, out var _); service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Removed, status)); }; async Task DockerBuildAsync(CancellationToken cancellationToken) { if (docker.DockerFile != null) { _logger.LogInformation("Building docker image {Image} from docker file", dockerImage); void Log(string data) { _logger.LogInformation("[" + serviceDescription !.Name + "]:" + data); service.Logs.OnNext(data); } var dockerBuildResult = await ProcessUtil.RunAsync( $"docker", $"build \"{docker.DockerFileContext?.FullName}\" -t {dockerImage} -f \"{docker.DockerFile}\"", outputDataReceived : Log, errorDataReceived : Log, workingDirectory : docker.WorkingDirectory, cancellationToken : cancellationToken, throwOnError : false); if (dockerBuildResult.ExitCode != 0) { throw new CommandException("'docker build' failed."); } } } Task DockerRunAsync(CancellationToken cancellationToken) { var tasks = new Task[serviceDescription !.Replicas]; if (serviceDescription.Bindings.Count > 0) { // Each replica is assigned a list of internal ports, one mapped to each external // port for (var i = 0; i < serviceDescription.Replicas; i++) { var ports = new List <(int, int, int?, string?)>(); foreach (var binding in serviceDescription.Bindings) { if (binding.Port == null) { continue; } ports.Add((binding.Port.Value, binding.ReplicaPorts[i], binding.ContainerPort, binding.Protocol)); } tasks[i] = RunDockerContainer(ports, cancellationToken); } } else { for (var i = 0; i < service.Description.Replicas; i++) { tasks[i] = RunDockerContainer(Enumerable.Empty <(int, int, int?, string?)>(), cancellationToken); } } return(Task.WhenAll(tasks)); }
/// <summary> /// Configures the print preferences of the print queue /// </summary> /// <param name="pqmTask">contains the info about print queue</param> private void ConfigureQueueForm(PrintQueueManagementTask pqmTask) { string queueName = _defaultPrintQueue.FullName; var action = new Action(() => { PrintPreferences preferences = new PrintPreferences(TopCat.TestApi.GUIAutomation.Enums.UIAFramework.ManagedUIA) { DriverModel = _localPrintQueueInfo.PrintDriver.DriverName }; ProcessUtil.Execute("cmd.exe", $"/c rundll32 printui.dll,PrintUIEntry /p /n \"{queueName}\"", TimeSpan.FromSeconds(shortTimeout)); preferences.PrintPreferencesWindow.WaitForAvailable(shortTimeout); preferences.DeviceSettingsTabItem.Select(shortTimeout); preferences.InstallableOptionTreeItem.Select(shortTimeout); if (preferences.DuplexUnitfor2STreeItem.IsAvailable()) { preferences.DuplexUnitfor2STreeItem.Select(shortTimeout); } else { preferences.DuplexUnitfor2SNTreeItem.Select(shortTimeout); } preferences.SelectListItem(pqmTask.Preference.Duplexer); preferences.OKButton1Button.Click(shortTimeout); ProcessUtil.Execute("cmd.exe", $"/c rundll32 printui.dll,PrintUIEntry /e /n \"{queueName}\"", TimeSpan.FromSeconds(shortTimeout)); preferences.PrintPreferencesWindow.WaitForAvailable(shortTimeout); preferences.PrintingShortcutTabItem.Select(shortTimeout); preferences.SelectListItem(pqmTask.Preference.PaperSize); Thread.Sleep(_humanTimespan); preferences.SelectListItem(pqmTask.Preference.InputTray); Thread.Sleep(_humanTimespan); preferences.SelectListItem(pqmTask.Preference.PaperType); Thread.Sleep(_humanTimespan); preferences.SelectListItem(pqmTask.Preference.Orientation); Thread.Sleep(_humanTimespan); preferences.SelectListItem(pqmTask.Preference.DuplexValue); preferences.AdvancedTabItem.Select(shortTimeout); preferences.CopyCountmsctlsSpinner.SetValue(pqmTask.Preference.Copies); preferences.OKButton1Button.Click(shortTimeout); pqmTask.Status = Status.Passed; }); //var tempScriptDirectory = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "TopCatScript")); //File.WriteAllBytes(Path.Combine(tempScriptDirectory.FullName, "CustomPrintSettings.tcx"), // ScriptResource.CustomPrintSettings); //File.WriteAllBytes(Path.Combine(tempScriptDirectory.FullName, "printPreferences.tcc"), // ScriptResource.printPreferences); //_configureScript = new TopCatScript //( // Path.Combine(tempScriptDirectory.FullName, "CustomPrintSettings.tcx"), // "CustomPrintSettings" //); //_configureScript.Properties.Add //( // "QueueName", // _defaultPrintQueue.FullName //); //_configureScript.Properties.Add //( // "Copies", // pqmTask.Preference.Copies.ToString(System.Globalization.CultureInfo.InvariantCulture) //); //_configureScript.Properties.Add //( // "PaperSize", // pqmTask.Preference.PaperSize //); //_configureScript.Properties.Add //( // "PaperSource", // pqmTask.Preference.InputTray //); //_configureScript.Properties.Add //( // "Orientation", // pqmTask.Preference.Orientation //); //_configureScript.Properties.Add //( // "DuplexValue", // pqmTask.Preference.DuplexValue //); //_configureScript.Properties.Add //( // "Duplexer", // pqmTask.Preference.Duplexer //); //_configureScript.Properties.Add //( // "DriverModel", // _localPrintQueueInfo.PrintDriver.DriverName //); //TopCatExecutionController tcExecutionController = new TopCatExecutionController(_configureScript); //tcExecutionController.InstallPrerequisites(GlobalSettings.Items["TopCatSetup"]); //tcExecutionController.ExecuteTopCatTest(); //string resultFile = tcExecutionController.GetResultFilePath(GlobalSettings.Items["DomainAdminUserName"]); //if (!string.IsNullOrEmpty(resultFile)) //{ // XDocument resultDoc = XDocument.Load(resultFile); // var successTests = resultDoc.Descendants("SuccessfulTests").First().Descendants("test"); // pqmTask.Status = successTests.Any() ? Status.Passed : Status.Failed; //} //else //{ // pqmTask.Status = Status.Failed; //} var token = new LocalLockToken(_defaultPrintQueue.FullName, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5)); ExecutionServices.CriticalSection.Run(token, action); }
public async Task StartAsync(Application application) { await PurgeFromPreviousRun(); var containers = new List <Service>(); foreach (var s in application.Services) { if (s.Value.Description.RunInfo is DockerRunInfo) { containers.Add(s.Value); } } if (containers.Count == 0) { return; } var proxies = new List <Service>(); foreach (var service in application.Services.Values) { if (service.Description.RunInfo is DockerRunInfo || service.Description.Bindings.Count == 0) { continue; } // Inject a proxy per non-container service. This allows the container to use normal host names within the // container network to talk to services on the host var proxyContanier = new DockerRunInfo($"mcr.microsoft.com/dotnet/core/sdk:3.1", "dotnet Microsoft.Tye.Proxy.dll") { WorkingDirectory = "/app", NetworkAlias = service.Description.Name, Private = true }; var proxyLocation = Path.GetDirectoryName(typeof(Microsoft.Tye.Proxy.Program).Assembly.Location); proxyContanier.VolumeMappings.Add(new DockerVolume(proxyLocation, name: null, target: "/app")); var proxyDescription = new ServiceDescription($"{service.Description.Name}-proxy", proxyContanier); foreach (var binding in service.Description.Bindings) { if (binding.Port == null) { continue; } var b = new ServiceBinding() { ConnectionString = binding.ConnectionString, Host = binding.Host, ContainerPort = binding.ContainerPort, Name = binding.Name, Port = binding.Port, Protocol = binding.Protocol }; b.ReplicaPorts.Add(b.Port.Value); proxyDescription.Bindings.Add(b); } var proxyContanierService = new Service(proxyDescription); containers.Add(proxyContanierService); proxies.Add(proxyContanierService); } string?dockerNetwork = null; if (!string.IsNullOrEmpty(application.Network)) { var dockerNetworkResult = await ProcessUtil.RunAsync("docker", $"network ls --filter \"name={application.Network}\" --format \"{{{{.ID}}}}\"", throwOnError : false); if (dockerNetworkResult.ExitCode != 0) { _logger.LogError("{Network}: Run docker network ls command failed", application.Network); throw new CommandException("Run docker network ls command failed"); } if (!string.IsNullOrWhiteSpace(dockerNetworkResult.StandardOutput)) { _logger.LogInformation("The specified network {Network} exists", application.Network); dockerNetwork = application.Network; } else { _logger.LogWarning("The specified network {Network} doesn't exist.", application.Network); application.Network = null; } } // We're going to be making containers, only make a network if we have more than one (we assume they'll need to talk) if (string.IsNullOrEmpty(dockerNetwork) && containers.Count > 1) { dockerNetwork = "tye_network_" + Guid.NewGuid().ToString().Substring(0, 10); application.Items["dockerNetwork"] = dockerNetwork; _logger.LogInformation("Creating docker network {Network}", dockerNetwork); var command = $"network create --driver bridge {dockerNetwork}"; _logger.LogInformation("Running docker command {Command}", command); var dockerNetworkResult = await ProcessUtil.RunAsync("docker", command, throwOnError : false); if (dockerNetworkResult.ExitCode != 0) { _logger.LogInformation("Running docker command with exception info {ExceptionStdOut} {ExceptionStdErr}", dockerNetworkResult.StandardOutput, dockerNetworkResult.StandardError); throw new CommandException("Run docker network create command failed"); } } // Stash information outside of the application services application.Items[typeof(DockerApplicationInformation)] = new DockerApplicationInformation(dockerNetwork, proxies); var tasks = new Task[containers.Count]; var index = 0; foreach (var s in containers) { var docker = (DockerRunInfo)s.Description.RunInfo !; tasks[index++] = StartContainerAsync(application, s, docker, dockerNetwork); } await Task.WhenAll(tasks); }
//static void Main(string[] args) //{ // Console.OutputEncoding = Encoding.Unicode; // Process process = Process.GetProcessesByName("Game")[0]; // IntPtr processHandle = OpenProcess(PROCESS_WM_READ, false, process.Id); // int processPtr = (int)processHandle; // //byte[] query = Encoding.Unicode.GetBytes("ねぇねぇ。なにブツブツ言ってるのー?"); // ////Encoding.GetEncoding(932).GetBytes("ねぇねぇ"); // //byte[] query2 = Encoding.GetEncoding(932).GetBytes("ふふん"); // //byte[] contentKey = new byte[query.Length]; // //byte[] content = new byte[256]; // //byte[] nearby = new byte[1024]; // //var memoryPtr = MemoryUtil.Search(processPtr, query); // //MemoryUtil.DumpSection("found.txt", processPtr, memoryPtr - 0x1000, 0x2000); // //Console.WriteLine(memoryPtr); // //var memoryPtr2 = MemoryUtil.Search(processPtr, query2); // //Console.WriteLine(memoryPtr2); // var binDecoder = new BinaryDecoder(); // var testBuffer = new byte[] { 0x11, 0x12, 0x13, 0x23, 0x24, 0x12, 0x13, 0x23, 0x24, 0x11 }; // Console.WriteLine(testBuffer.ToByteString()); // Console.WriteLine(binDecoder.IsPossible("ねぇねぇ", testBuffer, 0)); // Console.WriteLine(binDecoder.IsPossible("ねぇねぇ", testBuffer, 1)); // binDecoder.CheckPossible(processPtr, "右耳に当てているケータイ電話。通話口からはなにも聞こえてこない。"); // //binDecoder.CheckPossible(processPtr, "ねぇねぇ。なにブツブツ言ってるのー?"); // Console.ReadLine(); // //return; //} static void Main(string[] args) { int processPtr = ProcessUtil.OpenProcess("Game"); SteinsMonitor.Run(processPtr); }
private void SpawnMiner(string sComponent) { #region Check for cust pool if (!txtCustomPool.Text.Equals("")) { m_MiningURL = txtCustomPool.Text; PushStatusMessage("custom pool selected[" + txtCustomPool.Text + "], make sure to add your port if needed!", m_bDoLog); } else { pool_SelectedIndexChanged_1(cboPool, EventArgs.Empty); } #endregion #region UPDATE CONFIG #region House Keeping string sConfig_Template_File_Name = "config_templates/config-etncraft.txt"; string sConfig_File_Name = "app_assets/config.txt"; #endregion #region Delete and recreate config.txt if (File.Exists(sConfig_File_Name)) { File.Delete(sConfig_File_Name); } else { File.Create(sConfig_File_Name).Dispose(); } #endregion #region push msg PushStatusMessage("config created for " + sComponent, m_bDoLog); #endregion #region copy template to new config.txt File.Copy(sConfig_Template_File_Name, sConfig_File_Name, true); #endregion #region replace vars in new config.txt with GUI info var CONFIG_CONTENTS = File.ReadAllText(sConfig_File_Name); CONFIG_CONTENTS = CONFIG_CONTENTS.Replace("address_replace", m_MiningURL + ":" + port.Text); CONFIG_CONTENTS = CONFIG_CONTENTS.Replace("wallet_replace", wallet_address.Text.Replace(" ", "")); File.SetAttributes(Application.StartupPath + "\\" + sConfig_File_Name, FileAttributes.Normal); File.WriteAllText(Application.StartupPath + "\\" + sConfig_File_Name, CONFIG_CONTENTS); #endregion #endregion #region Spawn miner PushStatusMessage("Spawning ETNCRAFT miner for " + sComponent, m_bDoLog); string sArgs = ""; if (sComponent.Equals("CPU")) { sArgs = "--noAMD --noNVIDIA"; } else if (sComponent.Equals("GPU")) { sArgs = "--noCPU"; } Process process = ProcessUtil.SpawnMinerProcess(sArgs, m_bDebugging); process.OutputDataReceived += (object SenderOut, DataReceivedEventArgs eOut) => PushWorkStatusMessage(eOut.Data); process.BeginOutputReadLine(); process.ErrorDataReceived += (object SenderErr, DataReceivedEventArgs eErr) => PushWorkStatusMessage(eErr.Data); process.BeginErrorReadLine(); #endregion StartMining.Enabled = false; StartMining.BackColor = Color.LightGray; //BtnStopMining.Enabled = true; }
public void InitializeProcessAttribute(ProcessSearchResultModel selectedProcess, List <string> resources, ProcessUtil processUtil) { StartProcessWindowVm.SetProcessAttribute(selectedProcess, resources, processUtil); }
private void btnDisableWindowsUpdate_Click(object sender, EventArgs e) { ProcessUtil.RunCmd("/c net stop wuauserv"); ProcessUtil.RunPowerShell("-command \"Set-Service -Name wuauserv -StartupType Disabled\""); logger.output("Windows Update disabled"); }
/// <summary> /// 执行一个任务 /// </summary> /// <param name="taskInfo"></param> /// <returns></returns> public Task <TaskExecResult> RunTask(ExecTaskInfo taskInfo) { Task <TaskExecResult> taskRun = Task.Run <TaskExecResult>(() => { taskInfo.LastExecTime = DateTime.Now; int execLogId = 0; if (OnTaskExecBefore != null) { execLogId = OnTaskExecBefore(taskInfo); } TaskExecLog taskExecLog = new TaskExecLog() { ExecGuid = taskInfo.Guid, ExecLogId = execLogId, IsErrorAlert = taskInfo.IsErrorAlert, Title = taskInfo.Title, ReceiveEmail = taskInfo.ReceiveEmail, ExecStatrtTime = taskInfo.LastExecTime }; TaskExecResult execResult = new TaskExecResult(); string rsp = null; if (taskInfo.ExecType == (int)ExecTypeEnum.HTTP) { rsp = Net.HttpRequest(taskInfo.ExecUrl, taskInfo.Params, taskInfo.ExecMethod, taskInfo.Timeout, taskInfo.Encoding, taskInfo.IsResponseNorm || taskInfo.IsLogResult); taskExecLog.ExecEndTime = DateTime.Now; if (rsp.StartsWith(":(")) { execResult.Code = -999; execResult.Msg = string.Format("任务:{0}, 调用异常 url:{1} ", taskInfo.Title, taskInfo.ExecUrl); execResult.Data = rsp; if (OnTaskExecAfter != null) { OnTaskExecAfter(taskExecLog, execResult); } return(execResult); } if (taskInfo.IsResponseNorm) { try { execResult = rsp.FromJson <TaskExecResult>(); } catch (Exception ex) { execResult.Code = -900; execResult.Msg = string.Format("任务:{0},调用 url:{1} , 转换返回结果失败 结果:{1} ", taskInfo.Title, taskInfo.ExecUrl, rsp); execResult.Data = ex; if (OnTaskExecAfter != null) { OnTaskExecAfter(taskExecLog, execResult); } return(execResult); } } else { if (taskInfo.IsLogResult) { execResult.Data = rsp; } execResult.Code = 0; execResult.Msg = string.Format("任务:{0},调用 url:{1} , 处理成功 ", taskInfo.Title, taskInfo.ExecUrl); } } else if (taskInfo.ExecType == (int)ExecTypeEnum.EXE) { if (ProcessUtil.StartProcess(taskInfo.ExecUrl, taskInfo.Params, taskInfo.Timeout, ref rsp, taskInfo.IsLogResult)) { taskExecLog.ExecEndTime = DateTime.Now; execResult.Code = 0; if (taskInfo.IsLogResult) { execResult.Data = rsp; } execResult.Msg = string.Format("任务:{0},调用 url:{1} , 处理成功 ", taskInfo.Title, taskInfo.ExecUrl); } else { taskExecLog.ExecEndTime = DateTime.Now; execResult.Code = -800; execResult.Msg = string.Format("任务:{0},调用 url:{1} , 转换返回结果失败 结果:{1} ", taskInfo.Title, taskInfo.ExecUrl, rsp); } } else { execResult.Code = -1; execResult.Msg = "执行类型不存在"; } if (OnTaskExecAfter != null) { OnTaskExecAfter(taskExecLog, execResult); } return(execResult); }); return(taskRun); }
public static async Task <bool> RunCoverletAsync(CoverageProject project, bool throwError = false) { var title = $"Coverlet Run ({project.ProjectName})"; var coverletSettings = new List <string>(); coverletSettings.Add($@"""{project.TestDllFile}"""); coverletSettings.Add($@"--format ""cobertura"""); foreach (var value in (project.Settings.Exclude ?? new string[0]).Where(x => !string.IsNullOrWhiteSpace(x))) { coverletSettings.Add($@"--exclude ""{value.Replace("\"", "\\\"").Trim(' ', '\'')}"""); } foreach (var referenceProjectWithExcludeAttribute in project.ReferencedProjects.Where(x => x.ExcludeFromCodeCoverage)) { coverletSettings.Add($@"--exclude ""[{referenceProjectWithExcludeAttribute.AssemblyName}]*"""); } foreach (var value in (project.Settings.Include ?? new string[0]).Where(x => !string.IsNullOrWhiteSpace(x))) { coverletSettings.Add($@"--include ""{value.Replace("\"", "\\\"").Trim(' ', '\'')}"""); } foreach (var value in (project.Settings.ExcludeByFile ?? new string[0]).Where(x => !string.IsNullOrWhiteSpace(x))) { coverletSettings.Add($@"--exclude-by-file ""{value.Replace("\"", "\\\"").Trim(' ', '\'')}"""); } foreach (var value in (project.Settings.ExcludeByAttribute ?? new string[0]).Where(x => !string.IsNullOrWhiteSpace(x))) { coverletSettings.Add($@"--exclude-by-attribute ""{value.Replace("\"", "\\\"").Trim(' ', '\'', '[', ']')}"""); } if (project.Settings.IncludeTestAssembly) { coverletSettings.Add("--include-test-assembly"); } coverletSettings.Add($@"--target ""dotnet"""); coverletSettings.Add($@"--threshold-type line"); coverletSettings.Add($@"--threshold-stat total"); coverletSettings.Add($@"--threshold 0"); coverletSettings.Add($@"--output ""{ project.CoverageOutputFile }"""); var runSettings = !string.IsNullOrWhiteSpace(project.RunSettingsFile) ? $@"--settings """"{project.RunSettingsFile}""""" : default; coverletSettings.Add($@"--targetargs ""test """"{project.TestDllFile}"""" --nologo --blame {runSettings} --results-directory """"{project.CoverageOutputFolder}"""" --diag """"{project.CoverageOutputFolder}/diagnostics.log"""" """); Logger.Log($"{title} Arguments {Environment.NewLine}{string.Join($"{Environment.NewLine}", coverletSettings)}"); var result = await ProcessUtil .ExecuteAsync(new ExecuteRequest { FilePath = CoverletExePath, Arguments = string.Join(" ", coverletSettings), WorkingDirectory = project.ProjectOutputFolder }); if (result != null) { /* * 0 - Success. * 1 - If any test fails. * 2 - Coverage percentage is below threshold. * 3 - Test fails and also coverage percentage is below threshold. */ if (result.ExitCode > 3) { if (throwError) { throw new Exception(result.Output); } Logger.Log($"{title} Error", result.Output); return(false); } Logger.Log(title, result.Output); return(true); } return(false); }