|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Diagnostics; |
| 6 | +using System.Runtime.InteropServices; |
| 7 | +using Microsoft.Extensions.Logging; |
| 8 | + |
| 9 | +namespace Microsoft.AspNetCore.Server.IntegrationTesting |
| 10 | +{ |
| 11 | + public class PortHelper |
| 12 | + { |
| 13 | + public static void LogPortStatus(ILogger logger, int port) |
| 14 | + { |
| 15 | + logger.LogInformation("Checking for processes currently using port {0}", port); |
| 16 | + |
| 17 | + var psi = new ProcessStartInfo |
| 18 | + { |
| 19 | + RedirectStandardOutput = true, |
| 20 | + RedirectStandardError = true, |
| 21 | + }; |
| 22 | + |
| 23 | + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| 24 | + { |
| 25 | + psi.FileName = "cmd"; |
| 26 | + psi.Arguments = $"/C netstat -nq | find \"{port}\""; |
| 27 | + } |
| 28 | + else |
| 29 | + { |
| 30 | + psi.FileName = "lsof"; |
| 31 | + psi.Arguments = $"-i :{port}"; |
| 32 | + } |
| 33 | + |
| 34 | + var process = new Process |
| 35 | + { |
| 36 | + StartInfo = psi, |
| 37 | + EnableRaisingEvents = true |
| 38 | + }; |
| 39 | + |
| 40 | + var linesLogged = false; |
| 41 | + |
| 42 | + process.OutputDataReceived += (sender, data) => |
| 43 | + { |
| 44 | + if (!string.IsNullOrWhiteSpace(data.Data)) |
| 45 | + { |
| 46 | + linesLogged = true; |
| 47 | + logger.LogInformation("portstatus: {0}", data.Data); |
| 48 | + } |
| 49 | + }; |
| 50 | + process.ErrorDataReceived += (sender, data) => |
| 51 | + { |
| 52 | + if (!string.IsNullOrWhiteSpace(data.Data)) |
| 53 | + { |
| 54 | + logger.LogWarning("portstatus: {0}", data.Data); |
| 55 | + } |
| 56 | + }; |
| 57 | + |
| 58 | + try |
| 59 | + { |
| 60 | + process.Start(); |
| 61 | + process.BeginErrorReadLine(); |
| 62 | + process.BeginOutputReadLine(); |
| 63 | + process.WaitForExit(); |
| 64 | + |
| 65 | + if (!linesLogged) |
| 66 | + { |
| 67 | + logger.LogInformation("portstatus: it appears the port {0} is not in use.", port); |
| 68 | + } |
| 69 | + } |
| 70 | + catch (Exception ex) |
| 71 | + { |
| 72 | + logger.LogWarning("Failed to check port status. Executed: {0} {1}\nError: {2}", psi.FileName, psi.Arguments, ex.ToString()); |
| 73 | + } |
| 74 | + return; |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments