diff --git a/AGENTS.md b/AGENTS.md index 6427f89851..5da20fd6a8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -367,6 +367,9 @@ The website is deployed to GitHub Pages at: https://borntoberoot.net/NETworkMana - **`Source/NETworkManager.sln`**: Main Visual Studio solution - **`Source/GlobalAssemblyInfo.cs`**: Shared assembly version info - **`Source/global.json`**: .NET SDK version specification (also used by AppVeyor) +- **`Source/Directory.Build.props`**: Properties for all projects (CS0108 / CS0114 - a member hiding an inherited one - are + errors: WPF binds by name, a hiding property of a view model silently replaces e.g. `ProfileSearch` of + `ProfileHostViewModelBase`) - **`Source/.editorconfig`**: C# code style configuration - **`appveyor.yml`**: AppVeyor CI/CD configuration - **`.github/workflows/codeql.yml`**: CodeQL security analysis workflow diff --git a/Source/Directory.Build.props b/Source/Directory.Build.props new file mode 100644 index 0000000000..f334a67c35 --- /dev/null +++ b/Source/Directory.Build.props @@ -0,0 +1,10 @@ + + + + + $(WarningsAsErrors);CS0108;CS0114 + + diff --git a/Source/NETworkManager.Converters/PingMonitorGroupSummaryConverter.cs b/Source/NETworkManager.Converters/PingMonitorGroupSummaryConverter.cs index 0fdc6387e9..b2cb5d9c7d 100644 --- a/Source/NETworkManager.Converters/PingMonitorGroupSummaryConverter.cs +++ b/Source/NETworkManager.Converters/PingMonitorGroupSummaryConverter.cs @@ -1,22 +1,22 @@ using System; +using System.Collections; using System.Globalization; using System.Linq; -using System.Windows; using System.Windows.Data; using NETworkManager.Models.Network; namespace NETworkManager.Converters; /// -/// Formats the count of hosts up (reachable), down (unreachable) or paused (not running) within -/// a Ping Monitor group, selected via ConverterParameter ("Up", "Down", "Paused" - formats the +/// Formats the count of all hosts, the hosts up (reachable), down (unreachable) or paused (not running) within +/// a Ping Monitor group, selected via ConverterParameter ("Hosts", "Up", "Down", "Paused" - formats the /// count with the format string bound as the third value, e.g. Strings.XUp = "{0} Up", so the -/// word order can be translated - or "PausedVisibility", which instead returns a -/// so the paused count can be hidden while zero). +/// word order can be translated). Pending hosts (status not established yet) are only counted in "Hosts". /// /// /// Bound as a with the as the first -/// value and a per-group change-notification trigger as the second. The second value isn't used +/// value, a per-group change-notification trigger as the second, the format as the third and optionally all hosts +/// as the fourth (the summary counts all hosts of the group, also the ones hidden by the search / status filter). The second value isn't used /// directly, it only forces re-evaluation whenever a host's /// changes, since itself only raises change notifications for /// item add/remove, not for property changes on its items. @@ -26,16 +26,27 @@ public sealed class PingMonitorGroupSummaryConverter : IMultiValueConverter public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { if (values.Length == 0 || values[0] is not CollectionViewGroup group) - return parameter as string == "PausedVisibility" ? Visibility.Collapsed : string.Empty; + return string.Empty; + var total = 0; var up = 0; var down = 0; var paused = 0; - foreach (var host in group.Items.OfType()) + // All hosts of the group (fourth value: all hosts), not only the hosts shown by the filter + var groupName = group.Name?.ToString(); + var hosts = values.Length > 3 && values[3] is IEnumerable allHosts + ? allHosts.OfType().Where(x => x.Group == groupName) + : group.Items.OfType(); + + foreach (var host in hosts) { + total++; + if (!host.IsRunning) paused++; + else if (host.IsPending) + continue; // Neither up nor down until its status is established else if (host.IsReachable) up++; else @@ -46,10 +57,10 @@ public object Convert(object[] values, Type targetType, object parameter, Cultur return parameter as string switch { + "Hosts" => string.Format(culture, format, total), "Up" => string.Format(culture, format, up), "Down" => string.Format(culture, format, down), "Paused" => string.Format(culture, format, paused), - "PausedVisibility" => paused > 0 ? Visibility.Visible : Visibility.Collapsed, _ => string.Empty }; } diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index 3476a91987..2a5a02ac87 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -429,6 +429,15 @@ public static string Action { } } + /// + /// Looks up a localized string similar to Actions. + /// + public static string Actions { + get { + return ResourceManager.GetString("Actions", resourceCulture); + } + } + /// /// Looks up a localized string similar to Active connections. /// @@ -2296,6 +2305,17 @@ public static string CloseAll { } } + /// + /// Looks up a localized string similar to {0} hosts will be stopped and removed. + /// + ///Do you want to close all hosts?. + /// + public static string CloseAllHostsMessage { + get { + return ResourceManager.GetString("CloseAllHostsMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to Closed. /// @@ -6586,7 +6606,7 @@ public static string HelpMessage_MaxLogonFailures { } /// - /// Looks up a localized string similar to Number of consecutive failed pings (timeouts) required before a "Host is down" notification is shown. Higher values reduce noise from flapping hosts.. + /// Looks up a localized string similar to Number of consecutive failed pings (timeouts) required before a host is shown as down (status icon, group counters) and a "Host is down" notification is shown. Higher values reduce noise from flapping hosts.. /// public static string HelpMessage_NotificationFailureThreshold { get { @@ -6595,7 +6615,7 @@ public static string HelpMessage_NotificationFailureThreshold { } /// - /// Looks up a localized string similar to Number of consecutive successful pings required before a "Host is up" notification is shown. Higher values reduce noise from flapping hosts.. + /// Looks up a localized string similar to Number of consecutive successful pings required before a host is shown as up (status icon, group counters) and a "Host is up" notification is shown. Higher values reduce noise from flapping hosts.. /// public static string HelpMessage_NotificationSuccessThreshold { get { @@ -6657,6 +6677,15 @@ public static string HelpMessage_PingHostsBeforeScan { } } + /// + /// Looks up a localized string similar to Pings older than this are removed from the history of a host (export, chart when returning to live mode). The counters (received, lost, packet loss) include all pings since the host was started.. + /// + public static string HelpMessage_PingMonitorHistoryHours { + get { + return ResourceManager.GetString("HelpMessage_PingMonitorHistoryHours", resourceCulture); + } + } + /// /// Looks up a localized string similar to Pings a public IP address with every check of the network connection (dashboard and status window) to see if the internet is reachable. The target receives a ping (ICMP echo request). /// @@ -7003,6 +7032,15 @@ public static string History { } } + /// + /// Looks up a localized string similar to History (hours). + /// + public static string HistoryInHours { + get { + return ResourceManager.GetString("HistoryInHours", resourceCulture); + } + } + /// /// Looks up a localized string similar to Hop. /// @@ -9174,6 +9212,15 @@ public static string Model { } } + /// + /// Looks up a localized string similar to Monitored hosts. + /// + public static string MonitoredHosts { + get { + return ResourceManager.GetString("MonitoredHosts", resourceCulture); + } + } + /// /// Looks up a localized string similar to Move. /// @@ -10507,6 +10554,15 @@ public static string Pause { } } + /// + /// Looks up a localized string similar to Pause all. + /// + public static string PauseAll { + get { + return ResourceManager.GetString("PauseAll", resourceCulture); + } + } + /// /// Looks up a localized string similar to Paused. /// @@ -10651,6 +10707,17 @@ public static string PingMonitor { } } + /// + /// Looks up a localized string similar to {0} hosts will be added. Each host is pinged continuously and has its own chart, this needs a lot of resources. + /// + ///Do you want to add the hosts?. + /// + public static string PingMonitorManyHostsMessage { + get { + return ResourceManager.GetString("PingMonitorManyHostsMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to Notification. /// @@ -10660,6 +10727,15 @@ public static string PingMonitorNotification { } } + /// + /// Looks up a localized string similar to {0} hosts cannot be monitored at once (maximum {1}). Split the input into smaller ranges.. + /// + public static string PingMonitorTooManyHostsMessage { + get { + return ResourceManager.GetString("PingMonitorTooManyHostsMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to Ping public IP address. /// @@ -13339,6 +13415,15 @@ public static string Resume { } } + /// + /// Looks up a localized string similar to Resume all. + /// + public static string ResumeAll { + get { + return ResourceManager.GetString("ResumeAll", resourceCulture); + } + } + /// /// Looks up a localized string similar to Retries. /// @@ -15571,6 +15656,15 @@ public static string TheFollowingHostnamesCouldNotBeResolved { } } + /// + /// Looks up a localized string similar to The following hosts are already monitored in this group:. + /// + public static string TheFollowingHostsAreAlreadyMonitoredInThisGroup { + get { + return ResourceManager.GetString("TheFollowingHostsAreAlreadyMonitoredInThisGroup", resourceCulture); + } + } + /// /// Looks up a localized string similar to The following parameters are available:. /// @@ -17010,6 +17104,15 @@ public static string XGone { } } + /// + /// Looks up a localized string similar to {0} Hosts. + /// + public static string XHosts { + get { + return ResourceManager.GetString("XHosts", resourceCulture); + } + } + /// /// Looks up a localized string similar to {0} host(s) did not answer the ping and were not scanned.. /// diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index ff1ae46fe0..e0cd7f8828 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -2518,13 +2518,13 @@ is disabled! Success threshold - Number of consecutive successful pings required before a "Host is up" notification is shown. Higher values reduce noise from flapping hosts. + Number of consecutive successful pings required before a host is shown as up (status icon, group counters) and a "Host is up" notification is shown. Higher values reduce noise from flapping hosts. Failure threshold - Number of consecutive failed pings (timeouts) required before a "Host is down" notification is shown. Higher values reduce noise from flapping hosts. + Number of consecutive failed pings (timeouts) required before a host is shown as down (status icon, group counters) and a "Host is down" notification is shown. Higher values reduce noise from flapping hosts. Display duration (seconds) @@ -5917,4 +5917,41 @@ Own row: above the speed test. Open Windows Settings > Privacy & security > Location and enable access for Desktop Apps / NETworkManager. The widget shows the connection a few seconds later, a restart is not needed. - \ No newline at end of file + + {0} hosts will be added. Each host is pinged continuously and has its own chart, this needs a lot of resources. + +Do you want to add the hosts? + + + {0} hosts cannot be monitored at once (maximum {1}). Split the input into smaller ranges. + + + History (hours) + + + Pings older than this are removed from the history of a host (export, chart when returning to live mode). The counters (received, lost, packet loss) include all pings since the host was started. + + + The following hosts are already monitored in this group: + + + Pause all + + + Resume all + + + {0} Hosts + + + {0} hosts will be stopped and removed. + +Do you want to close all hosts? + + + Monitored hosts + + + Actions + + diff --git a/Source/NETworkManager.Models/Network/HostMonitor.cs b/Source/NETworkManager.Models/Network/HostMonitor.cs new file mode 100644 index 0000000000..0a8201c0ec --- /dev/null +++ b/Source/NETworkManager.Models/Network/HostMonitor.cs @@ -0,0 +1,179 @@ +using System; +using System.Net; +using System.Net.NetworkInformation; +using System.Threading; +using System.Threading.Tasks; +using log4net; +using NETworkManager.Utilities; + +namespace NETworkManager.Models.Network; + +/// +/// Checks a host continuously (Ping Monitor): one check of the , then +/// , until it is canceled. Fully asynchronous - no thread is blocked while waiting for a +/// reply or between the checks, and a cancellation stops it right away. +/// +/// +/// The events are raised on a thread pool thread. +/// +public sealed class HostMonitor +{ + private static readonly ILog Log = LogManager.GetLogger(typeof(HostMonitor)); + + private readonly IHostMonitorProbe _probe; + + /// + /// Creates a new monitor for a host. + /// + /// IP address of the host. + /// Known hostname (e.g. typed by the user), null or empty to resolve the PTR record. + /// Check of the host (e.g. ). + public HostMonitor(IPAddress ipAddress, string hostname, IHostMonitorProbe probe) + { + IPAddress = ipAddress; + Hostname = hostname; + _probe = probe; + } + + /// + /// IP address of the host. + /// + public IPAddress IPAddress { get; } + + /// + /// Hostname of the host (the known one, otherwise the PTR record once it is resolved). + /// + public string Hostname { get; private set; } + + /// + /// Time in milliseconds to wait between the checks. Default is 1000 ms. + /// + public int WaitTime { get; init; } = 1000; + + #region Events + + /// + /// Occurs after each check. A check that failed with an exception is reported with + /// and the message (). + /// + public event EventHandler PingReceived; + + /// + /// Occurs when the PTR record of the host was resolved (only if no hostname was known). + /// + public event EventHandler HostnameResolved; + + /// + /// Occurs when the monitor has stopped (canceled, or an unexpected error). Always the last event. + /// + public event EventHandler Stopped; + + /// + /// Message of the unexpected error that stopped the monitor, null if it was canceled (paused / closed). Set before + /// is raised. + /// + public string StopErrorMessage { get; private set; } + + #endregion + + /// + /// Starts the monitor in the background. It runs until the token is canceled. + /// + /// Token to stop the monitor. + public void Start(CancellationToken cancellationToken) + { + // On the thread pool, not on the caller's (UI) thread. The token is deliberately not passed to Task.Run: a + // token canceled before the task starts would skip RunAsync - and Stopped would never be raised. + _ = Task.Run(() => RunAsync(cancellationToken), CancellationToken.None); + } + + /// + /// Runs the monitor until the token is canceled. Never throws; is raised on every exit. + /// + /// Token to stop the monitor. + /// Task that completes when the monitor has stopped. + public async Task RunAsync(CancellationToken cancellationToken) + { + try + { + if (string.IsNullOrEmpty(Hostname)) + await ResolveHostnameAsync().ConfigureAwait(false); + + while (!cancellationToken.IsCancellationRequested) + { + var timestamp = DateTime.Now; + + PingInfo pingInfo; + string errorMessage = null; + + try + { + pingInfo = await _probe.ProbeAsync(cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) + { + // E.g. a PingException while the network adapter / VPN is gone: counted as lost, keep checking + pingInfo = new PingInfo(timestamp, IPAddress, IPStatus.Unknown); + errorMessage = GetErrorMessage(ex); + } + + // One IP address instance for the whole history, with the hostname of the host + pingInfo.IPAddress = IPAddress; + pingInfo.Hostname = Hostname; + + PingReceived?.Invoke(this, new PingReceivedArgs(pingInfo, errorMessage)); + + await Task.Delay(WaitTime, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + // Canceled while waiting + } + catch (Exception ex) + { + Log.Error($"Host monitor of {IPAddress} stopped because of an unexpected error", ex); + + StopErrorMessage = ex.Message; + } + finally + { + Stopped?.Invoke(this, EventArgs.Empty); + } + } + + /// + /// Resolves the PTR record of the host. A failed lookup is ignored (the host is shown without hostname). + /// + private async Task ResolveHostnameAsync() + { + try + { + var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress).ConfigureAwait(false); + + if (dnsResult.HasError) + return; + + Hostname = dnsResult.Value; + + HostnameResolved?.Invoke(this, new HostnameArgs(Hostname)); + } + catch (Exception ex) + { + Log.Warn($"Could not resolve the PTR record of {IPAddress}", ex); + } + } + + /// + /// Message of a failed check. The message of a is generic ("An exception occurred + /// during a Ping request."), the inner exception has the reason. + /// + private static string GetErrorMessage(Exception ex) + { + return ex is PingException { InnerException: not null } ? ex.InnerException.Message : ex.Message; + } +} diff --git a/Source/NETworkManager.Models/Network/ICMPHostMonitorProbe.cs b/Source/NETworkManager.Models/Network/ICMPHostMonitorProbe.cs new file mode 100644 index 0000000000..06fd725e5b --- /dev/null +++ b/Source/NETworkManager.Models/Network/ICMPHostMonitorProbe.cs @@ -0,0 +1,52 @@ +using System; +using System.Net; +using System.Net.NetworkInformation; +using System.Threading; +using System.Threading.Tasks; + +namespace NETworkManager.Models.Network; + +/// +/// Checks a host with one ICMP echo request (ping) per call. +/// +public sealed class ICMPHostMonitorProbe : IHostMonitorProbe +{ + private readonly IPAddress _ipAddress; + private readonly TimeSpan _timeout; + private readonly byte[] _buffer; + private readonly PingOptions _options; + + /// + /// Creates a new ICMP probe. + /// + /// IP address of the host. + /// Time in milliseconds to wait for a reply. + /// Size of the data sent with the echo request in bytes. + /// Time to live of the echo request. + /// Don't fragment the echo request. + public ICMPHostMonitorProbe(IPAddress ipAddress, int timeout, int bufferSize, int ttl, bool dontFragment) + { + _ipAddress = ipAddress; + _timeout = TimeSpan.FromMilliseconds(timeout); + _buffer = new byte[bufferSize]; + _options = new PingOptions { Ttl = ttl, DontFragment = dontFragment }; + } + + /// + public string Name => "ICMP"; + + /// + public async Task ProbeAsync(CancellationToken cancellationToken) + { + using var ping = new System.Net.NetworkInformation.Ping(); + + var timestamp = DateTime.Now; + + var pingReply = await ping.SendPingAsync(_ipAddress, _timeout, _buffer, _options, cancellationToken) + .ConfigureAwait(false); + + return pingReply.Status == IPStatus.Success + ? PingInfo.FromSuccessfulReply(timestamp, pingReply) + : new PingInfo(timestamp, _ipAddress, pingReply.Status); + } +} diff --git a/Source/NETworkManager.Models/Network/IHostMonitorProbe.cs b/Source/NETworkManager.Models/Network/IHostMonitorProbe.cs new file mode 100644 index 0000000000..daec5343ad --- /dev/null +++ b/Source/NETworkManager.Models/Network/IHostMonitorProbe.cs @@ -0,0 +1,33 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace NETworkManager.Models.Network; + +/// +/// One check of a host monitored by (e.g. an ICMP echo request). The monitor calls it +/// once per interval, so a probe only has to check the host once. +/// +/// +/// Only ICMP () exists so far. Further methods (e.g. TCP connect, HTTP) are +/// planned; they return the same result type, its status is the +/// that matches the outcome (e.g. Success, TimedOut). +/// +public interface IHostMonitorProbe +{ + /// + /// Short name of the method, shown as tag next to the host (e.g. ICMP). + /// + string Name { get; } + + /// + /// Checks the host once. + /// + /// Token to stop the check (the monitor was paused or closed). + /// Result of the check (timestamp, status and round-trip time). + /// The check was canceled. + /// + /// Other exceptions (e.g. while the network adapter is + /// gone) are counted as failed check by the monitor, which keeps checking. + /// + Task ProbeAsync(CancellationToken cancellationToken); +} diff --git a/Source/NETworkManager.Models/Network/IPingMonitorHostStatus.cs b/Source/NETworkManager.Models/Network/IPingMonitorHostStatus.cs index 0ec902e2f0..99d44546c2 100644 --- a/Source/NETworkManager.Models/Network/IPingMonitorHostStatus.cs +++ b/Source/NETworkManager.Models/Network/IPingMonitorHostStatus.cs @@ -7,6 +7,11 @@ namespace NETworkManager.Models.Network; /// public interface IPingMonitorHostStatus { + /// + /// Gets the group of the host. + /// + string Group { get; } + /// /// Gets a value indicating whether the host is reachable (responds to ping). /// @@ -16,4 +21,10 @@ public interface IPingMonitorHostStatus /// Gets a value indicating whether the ping monitoring is currently running. /// bool IsRunning { get; } + + /// + /// Gets a value indicating whether the status of the host is not established yet (after the start, until the + /// success / failure threshold is reached): neither up nor down. + /// + bool IsPending { get; } } diff --git a/Source/NETworkManager.Models/Network/LatencyAccumulator.cs b/Source/NETworkManager.Models/Network/LatencyAccumulator.cs new file mode 100644 index 0000000000..055fd9fa77 --- /dev/null +++ b/Source/NETworkManager.Models/Network/LatencyAccumulator.cs @@ -0,0 +1,71 @@ +using System; + +namespace NETworkManager.Models.Network; + +/// +/// Running statistics of the round-trip times of a host (Ping Monitor): minimum, average, maximum and jitter of all +/// replies since the start, without keeping the replies (the history is limited by age). +/// +public sealed class LatencyAccumulator +{ + private long _sum; + private long _jitterSum; + private long? _previous; + + /// + /// Number of replies. + /// + public int Count { get; private set; } + + /// + /// Lowest round-trip time in milliseconds, null without a reply. + /// + public long? Minimum { get; private set; } + + /// + /// Highest round-trip time in milliseconds, null without a reply. + /// + public long? Maximum { get; private set; } + + /// + /// Average round-trip time in milliseconds, null without a reply. + /// + public double? Average => Count == 0 ? null : (double)_sum / Count; + + /// + /// Jitter in milliseconds: the average difference between the round-trip times of consecutive replies, null with + /// less than two replies. + /// + public double? Jitter => Count < 2 ? null : (double)_jitterSum / (Count - 1); + + /// + /// Adds the round-trip time of a reply. + /// + /// Round-trip time in milliseconds. + public void Add(long time) + { + Count++; + _sum += time; + + Minimum = Minimum.HasValue ? Math.Min(Minimum.Value, time) : time; + Maximum = Maximum.HasValue ? Math.Max(Maximum.Value, time) : time; + + if (_previous.HasValue) + _jitterSum += Math.Abs(time - _previous.Value); + + _previous = time; + } + + /// + /// Removes all replies (the host is started again). + /// + public void Reset() + { + Count = 0; + _sum = 0; + _jitterSum = 0; + _previous = null; + Minimum = null; + Maximum = null; + } +} diff --git a/Source/NETworkManager.Models/Network/Ping.cs b/Source/NETworkManager.Models/Network/Ping.cs index b6844513d8..67a8b7d6ce 100644 --- a/Source/NETworkManager.Models/Network/Ping.cs +++ b/Source/NETworkManager.Models/Network/Ping.cs @@ -1,193 +1,12 @@ -using System; -using System.Net; -using System.Net.NetworkInformation; -using System.Threading; -using System.Threading.Tasks; -using NETworkManager.Utilities; +using System.Net.NetworkInformation; namespace NETworkManager.Models.Network; /// -/// Provides functionality to ping a network host. +/// Helpers for pings. The continuous ping of the Ping Monitor is . /// -public sealed class Ping +public static class Ping { - #region Variables - - /// - /// The time in milliseconds to wait between ping requests. Default is 1000ms. - /// - public int WaitTime = 1000; - - /// - /// The time in milliseconds to wait for a reply. Default is 4000ms. - /// - public int Timeout = 4000; - - /// - /// The size in bytes of the buffer to send with the ping request. Default is 32 bytes. - /// - public int BufferSize = 32; - - /// - /// The Time to Live (TTL) value for the ping request. Default is 64. - /// - public int TTL = 64; - - /// - /// Indicates whether to prevent fragmentation of the data packets. Default is true. - /// - public bool DontFragment = true; - - private const int ExceptionCancelCount = 3; - - #endregion - - #region Events - - /// - /// Occurs when a ping reply is received. - /// - public event EventHandler PingReceived; - - private void OnPingReceived(PingReceivedArgs e) - { - PingReceived?.Invoke(this, e); - } - - /// - /// Occurs when the ping operation is completed. - /// - public event EventHandler PingCompleted; - - private void OnPingCompleted() - { - PingCompleted?.Invoke(this, EventArgs.Empty); - } - - /// - /// Occurs when a ping exception is thrown. - /// - public event EventHandler PingException; - - private void OnPingException(PingExceptionArgs e) - { - PingException?.Invoke(this, e); - } - - /// - /// Occurs when the hostname is resolved. - /// - public event EventHandler HostnameResolved; - - private void OnHostnameResolved(HostnameArgs e) - { - HostnameResolved?.Invoke(this, e); - } - - /// - /// Occurs when the user has canceled the operation. - /// - public event EventHandler UserHasCanceled; - - private void OnUserHasCanceled() - { - UserHasCanceled?.Invoke(this, EventArgs.Empty); - } - - #endregion - - #region Methods - - /// - /// Sends ping requests to the specified IP address asynchronously. - /// - /// The IP address to ping. - /// The token to monitor for cancellation requests. - public void SendAsync(IPAddress ipAddress, CancellationToken cancellationToken) - { - Task.Run(async () => - { - var hostname = string.Empty; - - // Try to resolve PTR - var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(ipAddress); - - if (!dnsResult.HasError) - { - hostname = dnsResult.Value; - - OnHostnameResolved(new HostnameArgs(hostname)); - } - - var errorCount = 0; - - var buffer = new byte[BufferSize]; - - var options = new PingOptions - { - Ttl = TTL, - DontFragment = DontFragment - }; - - using (var ping = new System.Net.NetworkInformation.Ping()) - { - do - { - try - { - // Get timestamp - var timestamp = DateTime.Now; - - // Send ping - var pingReply = ping.Send(ipAddress, Timeout, buffer, options); - - // Reset the error count (if no exception was thrown) - errorCount = 0; - - if (pingReply is not { Status: IPStatus.Success }) - { - if (pingReply != null) - OnPingReceived(new PingReceivedArgs( - new PingInfo(timestamp, pingReply.Address, hostname, pingReply.Status))); - } - else - { - OnPingReceived(new PingReceivedArgs( - PingInfo.FromSuccessfulReply(timestamp, pingReply, hostname))); - } - } - catch (PingException ex) - { - errorCount++; - - if (errorCount == ExceptionCancelCount) - { - OnPingException(new PingExceptionArgs(ex.Message, ex.InnerException)); - - break; - } - } - - // If ping is canceled... dont wait for example 5 seconds - for (var i = 0; i < WaitTime; i += 100) - { - Thread.Sleep(100); - - if (cancellationToken.IsCancellationRequested) - break; - } - } while (!cancellationToken.IsCancellationRequested); - } - - if (cancellationToken.IsCancellationRequested) - OnUserHasCanceled(); - // Currently not used (ping will run until the user cancels it) - else - OnPingCompleted(); - }, cancellationToken); - } - /// /// Converts the ping time to a string representation (e.g. <1 ms, 4 ms), -/- without a /// reply. @@ -202,6 +21,4 @@ public static string TimeToString(IPStatus status, long time) return time == 0 ? "<1 ms" : $"{time} ms"; } - - #endregion -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Models/Network/PingExceptionArgs.cs b/Source/NETworkManager.Models/Network/PingExceptionArgs.cs deleted file mode 100644 index 3783a1560a..0000000000 --- a/Source/NETworkManager.Models/Network/PingExceptionArgs.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -namespace NETworkManager.Models.Network; - -public class PingExceptionArgs : EventArgs -{ - public PingExceptionArgs(string message, Exception innerException) - { - Message = message; - InnerException = innerException; - } - - public string Message { get; set; } - public Exception InnerException { get; set; } -} \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/PingMonitorHistory.cs b/Source/NETworkManager.Models/Network/PingMonitorHistory.cs new file mode 100644 index 0000000000..c3f263d880 --- /dev/null +++ b/Source/NETworkManager.Models/Network/PingMonitorHistory.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; + +namespace NETworkManager.Models.Network; + +/// +/// History of the pings of a host in the Ping Monitor (export, chart after "Live"), limited by age. +/// +public static class PingMonitorHistory +{ + /// + /// Removes the pings older than . To avoid copying the list on every ping, the pings are + /// only removed once the oldest one is 1 % of too old (e.g. about every 15 minutes for + /// 24 hours), then all outdated pings at once. + /// + /// Pings, the oldest first. + /// Current time. + /// Maximum age of a ping. + /// Number of removed pings. + public static int Trim(List history, DateTime now, TimeSpan maxAge) + { + if (history.Count == 0) + return 0; + + var cutoff = now - maxAge; + + if (history[0].Timestamp >= cutoff - maxAge / 100) + return 0; + + var count = 0; + + while (count < history.Count && history[count].Timestamp < cutoff) + count++; + + history.RemoveRange(0, count); + + return count; + } +} diff --git a/Source/NETworkManager.Models/Network/PingMonitorHostFilter.cs b/Source/NETworkManager.Models/Network/PingMonitorHostFilter.cs new file mode 100644 index 0000000000..3e5d66cc9f --- /dev/null +++ b/Source/NETworkManager.Models/Network/PingMonitorHostFilter.cs @@ -0,0 +1,48 @@ +using System; +using System.Linq; + +namespace NETworkManager.Models.Network; + +/// +/// Filter of the hosts shown in the Ping Monitor (status check boxes and search). Only the display is filtered: +/// hidden hosts keep being pinged and notified. +/// +public static class PingMonitorHostFilter +{ + /// + /// Checks whether a host is shown. + /// + /// Status of the host. + /// Show the running hosts that are up. + /// Show the running hosts that are down. + /// Show the paused hosts. + /// Search text, null or empty for all hosts. + /// Searched values of the host (e.g. title, IP address, hostname, group), null values are + /// skipped. + /// True if the host is shown. + /// + /// A pending host (running, status not established yet) is shown with up or down, so a host that was just + /// added doesn't disappear until its status is known. + /// + public static bool Matches(IPingMonitorHostStatus host, bool showUp, bool showDown, bool showPaused, + string search, params string[] values) + { + var statusMatches = !host.IsRunning + ? showPaused + : host.IsPending + ? showUp || showDown + : host.IsReachable + ? showUp + : showDown; + + if (!statusMatches) + return false; + + if (string.IsNullOrWhiteSpace(search)) + return true; + + var text = search.Trim(); + + return values.Any(x => x?.Contains(text, StringComparison.OrdinalIgnoreCase) == true); + } +} diff --git a/Source/NETworkManager.Models/Network/PingMonitorHostHelper.cs b/Source/NETworkManager.Models/Network/PingMonitorHostHelper.cs new file mode 100644 index 0000000000..f3d81ea8a4 --- /dev/null +++ b/Source/NETworkManager.Models/Network/PingMonitorHostHelper.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.Linq; +using System.Net; + +namespace NETworkManager.Models.Network; + +/// +/// Helpers for the hosts of the Ping Monitor. +/// +public static class PingMonitorHostHelper +{ + /// + /// Splits the hosts to add into the new hosts and the hosts that are already monitored (same IP address, in the + /// group they are added to). Several entries of the input for the same IP address (e.g. different hostnames, see + /// ) are kept. + /// + /// + /// With further check methods (e.g. TCP, HTTP), the method and its port / URL become part of the key. + /// + /// Hosts to add. + /// IP addresses already monitored in the group. + /// Hosts to add and hosts that are already monitored, in the order of . + public static (List<(IPAddress ipAddress, string hostname)> hostsToAdd, + List<(IPAddress ipAddress, string hostname)> alreadyMonitored) SplitAlreadyMonitored( + IEnumerable<(IPAddress ipAddress, string hostname)> hosts, IEnumerable monitoredIPAddresses) + { + var monitored = monitoredIPAddresses.ToHashSet(); + + var hostsToAdd = new List<(IPAddress ipAddress, string hostname)>(); + var alreadyMonitored = new List<(IPAddress ipAddress, string hostname)>(); + + foreach (var host in hosts) + (monitored.Contains(host.ipAddress) ? alreadyMonitored : hostsToAdd).Add(host); + + return (hostsToAdd, alreadyMonitored); + } +} diff --git a/Source/NETworkManager.Models/Network/PingMonitorStatusTracker.cs b/Source/NETworkManager.Models/Network/PingMonitorStatusTracker.cs new file mode 100644 index 0000000000..3a2336b511 --- /dev/null +++ b/Source/NETworkManager.Models/Network/PingMonitorStatusTracker.cs @@ -0,0 +1,96 @@ +namespace NETworkManager.Models.Network; + +/// +/// Change of the status of a host in the Ping Monitor, see . +/// +public enum PingMonitorStatusChange +{ + /// + /// The status didn't change. + /// + None, + + /// + /// The first status after the start was established (no notification). + /// + Initial, + + /// + /// The host is up again (notification). + /// + Up, + + /// + /// The host is down (notification). + /// + Down +} + +/// +/// Status of a host in the Ping Monitor: the status only changes after a number of consecutive successful / failed +/// pings (thresholds), to avoid noise from flapping hosts. The first status after the start is established the +/// same way, without a notification; until then the host is pending (neither up nor down). +/// +public sealed class PingMonitorStatusTracker +{ + private int _consecutiveSuccesses; + private int _consecutiveFailures; + + /// + /// No status yet (after the start, until a threshold is reached). + /// + public bool IsPending { get; private set; } = true; + + /// + /// The host is up (only meaningful if not ). + /// + public bool IsReachable { get; private set; } + + /// + /// Adds the result of a ping. + /// + /// The host replied. + /// Consecutive successful pings until the host is up. + /// Consecutive failed pings until the host is down. + /// Change of the status. + public PingMonitorStatusChange Add(bool success, int successThreshold, int failureThreshold) + { + if (success) + { + _consecutiveSuccesses++; + _consecutiveFailures = 0; + + if (_consecutiveSuccesses < successThreshold || (!IsPending && IsReachable)) + return PingMonitorStatusChange.None; + } + else + { + _consecutiveFailures++; + _consecutiveSuccesses = 0; + + if (_consecutiveFailures < failureThreshold || (!IsPending && !IsReachable)) + return PingMonitorStatusChange.None; + } + + var wasPending = IsPending; + + IsPending = false; + IsReachable = success; + + if (wasPending) + return PingMonitorStatusChange.Initial; + + return success ? PingMonitorStatusChange.Up : PingMonitorStatusChange.Down; + } + + /// + /// Resets the status (the host is started again): pending until a threshold is reached. + /// + public void Reset() + { + _consecutiveSuccesses = 0; + _consecutiveFailures = 0; + IsPending = true; + IsReachable = false; + } +} diff --git a/Source/NETworkManager.Models/Network/PingReceivedArgs.cs b/Source/NETworkManager.Models/Network/PingReceivedArgs.cs index 1506cb2c68..c40d7d5315 100644 --- a/Source/NETworkManager.Models/Network/PingReceivedArgs.cs +++ b/Source/NETworkManager.Models/Network/PingReceivedArgs.cs @@ -3,21 +3,29 @@ namespace NETworkManager.Models.Network; /// -/// Contains the information of a received ping in a . +/// Contains the result of a check of a . /// public class PingReceivedArgs : EventArgs { /// /// Creates a new instance of with the given . /// - /// - public PingReceivedArgs(PingInfo args) + /// Result of the check. + /// Message if the check failed with an error (e.g. no network), otherwise null. + public PingReceivedArgs(PingInfo args, string errorMessage = null) { Args = args; + ErrorMessage = errorMessage; } /// /// Ping information. /// public PingInfo Args { get; } -} \ No newline at end of file + + /// + /// Message if the check failed with an error (status ), + /// otherwise null. + /// + public string ErrorMessage { get; } +} diff --git a/Source/NETworkManager.Profiles/IProfileHostViewModel.cs b/Source/NETworkManager.Profiles/IProfileHostViewModel.cs index dd79ff52ff..83959f6f05 100644 --- a/Source/NETworkManager.Profiles/IProfileHostViewModel.cs +++ b/Source/NETworkManager.Profiles/IProfileHostViewModel.cs @@ -17,14 +17,14 @@ public interface IProfileHostViewModel : IProfileManager ProfileInfo SelectedProfile { get; set; } /// - /// Gets or sets the search text. + /// Gets or sets the search text of the profiles. /// - string Search { get; set; } + string ProfileSearch { get; set; } /// - /// Gets or sets a value indicating whether a search is in progress. + /// Gets or sets a value indicating whether a search of the profiles is in progress. /// - bool IsSearching { get; set; } + bool IsProfileSearching { get; set; } /// /// Gets or sets a value indicating whether the profile filter popup is open. diff --git a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs index ab0de0ef02..d4f583d229 100644 --- a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs +++ b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs @@ -313,9 +313,28 @@ public static class GlobalStaticConfiguration public static int PingMonitor_WaitTime => 1000; // ms public static bool PingMonitor_ExpandHostView => false; public static int PingMonitor_ChartTime => 120; // s + public static int PingMonitor_HistoryHours => 12; // h (a workday) public static ExportFileType PingMonitor_ExportFileType => ExportFileType.Csv; + /// + /// Every host is pinged continuously and has its own chart: ask before adding many hosts at once and refuse + /// even more (e.g. a /16 subnet). + /// + public static long PingMonitor_ConfirmHostCount => 256; + public static long PingMonitor_MaxHostCount => 4096; + + /// + /// Inputs with more hosts (before the exclusions, e.g. 10.0.0.0/8) are refused before they are resolved; up to + /// this size (a /16) the exclusions can bring the input below . + /// + public static long PingMonitor_MaxInputHostCount => 65536; + // Ping Monitor (notifications) + /// + /// Status changes of the hosts within this time are shown as one notification (e.g. an uplink outage). + /// + public static TimeSpan PingMonitor_NotificationDelay => TimeSpan.FromSeconds(1); + public static bool PingMonitor_ShowNotificationPopup => true; public static bool PingMonitor_NotificationSound => false; public static int PingMonitor_NotificationSuccessThreshold => 1; diff --git a/Source/NETworkManager.Settings/SettingsInfo.cs b/Source/NETworkManager.Settings/SettingsInfo.cs index 53b8196a49..02803bb418 100644 --- a/Source/NETworkManager.Settings/SettingsInfo.cs +++ b/Source/NETworkManager.Settings/SettingsInfo.cs @@ -2363,6 +2363,22 @@ public int PingMonitor_ChartTime } } = GlobalStaticConfiguration.PingMonitor_ChartTime; + /// + /// Hours the pings of a host are kept in the history (export, chart after "Live"). + /// + public int PingMonitor_HistoryHours + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.PingMonitor_HistoryHours; + public bool PingMonitor_ShowNotificationPopup { get; diff --git a/Source/NETworkManager.Tests/Converters/PingMonitorGroupSummaryConverterTests.cs b/Source/NETworkManager.Tests/Converters/PingMonitorGroupSummaryConverterTests.cs new file mode 100644 index 0000000000..ffb89a40f2 --- /dev/null +++ b/Source/NETworkManager.Tests/Converters/PingMonitorGroupSummaryConverterTests.cs @@ -0,0 +1,68 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using NETworkManager.Converters; +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Converters; + +/// +/// Tests of . The group needs WPF (collection view): the tests only run +/// on Windows. The WPF code is in separate methods, so the test methods can be loaded without WPF. +/// +public class PingMonitorGroupSummaryConverterTests +{ + private sealed record Host(string Group, bool IsRunning, bool IsPending, bool IsReachable) : IPingMonitorHostStatus; + + private static readonly Host[] Hosts = + [ + new("a", true, false, true), // up + new("a", true, false, true), // up + new("a", true, false, false), // down + new("a", true, true, false), // pending: neither up nor down + new("a", false, false, true), // paused + new("b", true, false, false) // other group + ]; + + private static void SkipUnlessWindows() + { + Assert.SkipUnless(OperatingSystem.IsWindows(), "Needs WPF (Windows)"); + } + + [Theory] + [InlineData("Hosts", "5")] + [InlineData("Up", "2")] + [InlineData("Down", "1")] + [InlineData("Paused", "1")] + public void CountsTheHostsOfTheGroup(string parameter, string expected) + { + SkipUnlessWindows(); + + Assert.Equal(expected, Convert(parameter)); + } + + + [Fact] + public void CountsAllHostsOfTheGroupAlsoIfFiltered() + { + SkipUnlessWindows(); + + // Only the paused host is shown, the summary counts all hosts of the group + Assert.Equal("2", Convert("Up", filterPaused: true)); + } + + private static object Convert(string parameter, bool filterPaused = false) + { + var view = new ListCollectionView(Hosts); + view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(Host.Group))); + + if (filterPaused) + view.Filter = x => !((Host)x).IsRunning; + + var group = (CollectionViewGroup)view.Groups[0]; + + return new PingMonitorGroupSummaryConverter().Convert([group, 0, "{0}", Hosts], typeof(object), parameter, + CultureInfo.InvariantCulture); + } +} diff --git a/Source/NETworkManager.Tests/NETworkManager.Tests.csproj b/Source/NETworkManager.Tests/NETworkManager.Tests.csproj index 2c922ce08d..4bce1abc65 100644 --- a/Source/NETworkManager.Tests/NETworkManager.Tests.csproj +++ b/Source/NETworkManager.Tests/NETworkManager.Tests.csproj @@ -19,6 +19,7 @@ + diff --git a/Source/NETworkManager.Tests/Network/LatencyAccumulatorTests.cs b/Source/NETworkManager.Tests/Network/LatencyAccumulatorTests.cs new file mode 100644 index 0000000000..ffebe441a8 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/LatencyAccumulatorTests.cs @@ -0,0 +1,61 @@ +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class LatencyAccumulatorTests +{ + [Fact] + public void EmptyHasNoValues() + { + var accumulator = new LatencyAccumulator(); + + Assert.Equal(0, accumulator.Count); + Assert.Null(accumulator.Minimum); + Assert.Null(accumulator.Average); + Assert.Null(accumulator.Maximum); + Assert.Null(accumulator.Jitter); + } + + [Fact] + public void OneReplyHasNoJitter() + { + var accumulator = new LatencyAccumulator(); + accumulator.Add(7); + + Assert.Equal(7, accumulator.Minimum); + Assert.Equal(7, accumulator.Average); + Assert.Equal(7, accumulator.Maximum); + Assert.Null(accumulator.Jitter); + } + + [Fact] + public void CalculatesTheStatistics() + { + var accumulator = new LatencyAccumulator(); + + foreach (var time in new long[] { 10, 20, 15, 35 }) + accumulator.Add(time); + + Assert.Equal(4, accumulator.Count); + Assert.Equal(10, accumulator.Minimum); + Assert.Equal(20, accumulator.Average); + Assert.Equal(35, accumulator.Maximum); + // |20-10| + |15-20| + |35-15| = 35 over 3 differences + Assert.Equal(35 / 3.0, accumulator.Jitter!.Value, 6); + } + + [Fact] + public void ResetRemovesAll() + { + var accumulator = new LatencyAccumulator(); + accumulator.Add(10); + accumulator.Add(20); + accumulator.Reset(); + accumulator.Add(5); + + Assert.Equal(1, accumulator.Count); + Assert.Equal(5, accumulator.Minimum); + Assert.Null(accumulator.Jitter); + } +} diff --git a/Source/NETworkManager.Tests/Network/PingMonitorHistoryTests.cs b/Source/NETworkManager.Tests/Network/PingMonitorHistoryTests.cs new file mode 100644 index 0000000000..62b0d6c2a7 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/PingMonitorHistoryTests.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.NetworkInformation; +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class PingMonitorHistoryTests +{ + private static readonly DateTime Now = new(2026, 11, 29, 12, 0, 0); + + private static List History(params int[] minutesAgo) => + minutesAgo.Select(x => new PingInfo(Now.AddMinutes(-x), IPAddress.Loopback, IPStatus.Success)).ToList(); + + [Fact] + public void EmptyHistoryIsKept() + { + var history = new List(); + + Assert.Equal(0, PingMonitorHistory.Trim(history, Now, TimeSpan.FromHours(1))); + } + + [Fact] + public void PingsWithinTheLimitAreKept() + { + var history = History(59, 30, 0); + + Assert.Equal(0, PingMonitorHistory.Trim(history, Now, TimeSpan.FromHours(1))); + Assert.Equal(3, history.Count); + } + + [Fact] + public void SlightlyOutdatedPingsAreRemovedLater() + { + // 1 % of an hour = 36 seconds - the list isn't copied for every ping + var history = History(60, 30, 0); + history[0].Timestamp = Now.AddHours(-1).AddSeconds(-20); + + Assert.Equal(0, PingMonitorHistory.Trim(history, Now, TimeSpan.FromHours(1))); + Assert.Equal(3, history.Count); + } + + [Fact] + public void AllOutdatedPingsAreRemovedInOrder() + { + var history = History(120, 90, 61, 59, 0); + + Assert.Equal(3, PingMonitorHistory.Trim(history, Now, TimeSpan.FromHours(1))); + Assert.Equal([Now.AddMinutes(-59), Now], history.Select(x => x.Timestamp)); + } + + [Fact] + public void AllPingsCanBeRemoved() + { + var history = History(180, 120); + + Assert.Equal(2, PingMonitorHistory.Trim(history, Now, TimeSpan.FromHours(1))); + Assert.Empty(history); + } +} diff --git a/Source/NETworkManager.Tests/Network/PingMonitorHostFilterTests.cs b/Source/NETworkManager.Tests/Network/PingMonitorHostFilterTests.cs new file mode 100644 index 0000000000..3ba5da1d55 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/PingMonitorHostFilterTests.cs @@ -0,0 +1,50 @@ +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class PingMonitorHostFilterTests +{ + private sealed record Host(string Group, bool IsRunning, bool IsPending, bool IsReachable) : IPingMonitorHostStatus; + + private static readonly Host Up = new("a", true, false, true); + private static readonly Host Down = new("a", true, false, false); + private static readonly Host Pending = new("a", true, true, false); + private static readonly Host Paused = new("a", false, false, true); + + [Theory] + // showUp, showDown, showPaused -> up, down, pending, paused shown + [InlineData(true, true, true, true, true, true, true)] + [InlineData(true, false, false, true, false, true, false)] + [InlineData(false, true, false, false, true, true, false)] + [InlineData(false, false, true, false, false, false, true)] + [InlineData(false, true, true, false, true, true, true)] + [InlineData(false, false, false, false, false, false, false)] + public void StatusFilter(bool showUp, bool showDown, bool showPaused, bool up, bool down, bool pending, + bool paused) + { + Assert.Equal(up, PingMonitorHostFilter.Matches(Up, showUp, showDown, showPaused, null)); + Assert.Equal(down, PingMonitorHostFilter.Matches(Down, showUp, showDown, showPaused, null)); + Assert.Equal(pending, PingMonitorHostFilter.Matches(Pending, showUp, showDown, showPaused, null)); + Assert.Equal(paused, PingMonitorHostFilter.Matches(Paused, showUp, showDown, showPaused, null)); + } + + [Theory] + [InlineData("", true)] + [InlineData(" ", true)] + [InlineData("SERVER", true)] + [InlineData(" 10.0.0 ", true)] + [InlineData("office", true)] + [InlineData("router", false)] + public void SearchIsCaseInsensitive(string search, bool expected) + { + Assert.Equal(expected, + PingMonitorHostFilter.Matches(Up, true, true, true, search, "server-01", "10.0.0.1", null, "Office")); + } + + [Fact] + public void SearchAndStatusMustBothMatch() + { + Assert.False(PingMonitorHostFilter.Matches(Up, false, true, true, "server", "server-01")); + } +} diff --git a/Source/NETworkManager.Tests/Network/PingMonitorHostHelperTests.cs b/Source/NETworkManager.Tests/Network/PingMonitorHostHelperTests.cs new file mode 100644 index 0000000000..06b1eb3462 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/PingMonitorHostHelperTests.cs @@ -0,0 +1,50 @@ +using System.Linq; +using System.Net; +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class PingMonitorHostHelperTests +{ + private static readonly IPAddress A = IPAddress.Parse("10.0.0.1"); + private static readonly IPAddress B = IPAddress.Parse("10.0.0.2"); + private static readonly IPAddress V6 = IPAddress.Parse("2001:db8::1"); + + [Fact] + public void NothingMonitoredAddsAll() + { + var (hostsToAdd, alreadyMonitored) = PingMonitorHostHelper.SplitAlreadyMonitored([(A, null), (B, "b")], []); + + Assert.Equal([A, B], hostsToAdd.Select(x => x.ipAddress)); + Assert.Empty(alreadyMonitored); + } + + [Fact] + public void MonitoredIPAddressIsSkipped() + { + var (hostsToAdd, alreadyMonitored) = + PingMonitorHostHelper.SplitAlreadyMonitored([(A, "server"), (B, null)], [IPAddress.Parse("10.0.0.1")]); + + Assert.Equal([B], hostsToAdd.Select(x => x.ipAddress)); + Assert.Equal([(A, "server")], alreadyMonitored); + } + + [Fact] + public void IPv6IsComparedByValue() + { + var (hostsToAdd, alreadyMonitored) = + PingMonitorHostHelper.SplitAlreadyMonitored([(V6, null)], [IPAddress.Parse("2001:0db8:0:0::1")]); + + Assert.Empty(hostsToAdd); + Assert.Single(alreadyMonitored); + } + + [Fact] + public void EntriesOfTheInputForTheSameIPAddressAreKept() + { + var (hostsToAdd, _) = PingMonitorHostHelper.SplitAlreadyMonitored([(A, "a"), (A, "alias")], [B]); + + Assert.Equal(2, hostsToAdd.Count); + } +} diff --git a/Source/NETworkManager.Tests/Network/PingMonitorStatusTrackerTests.cs b/Source/NETworkManager.Tests/Network/PingMonitorStatusTrackerTests.cs new file mode 100644 index 0000000000..71acf2a945 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/PingMonitorStatusTrackerTests.cs @@ -0,0 +1,108 @@ +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class PingMonitorStatusTrackerTests +{ + private static PingMonitorStatusChange[] Add(PingMonitorStatusTracker tracker, int successThreshold, + int failureThreshold, params bool[] results) + { + var changes = new PingMonitorStatusChange[results.Length]; + + for (var i = 0; i < results.Length; i++) + changes[i] = tracker.Add(results[i], successThreshold, failureThreshold); + + return changes; + } + + [Fact] + public void NewTrackerIsPending() + { + var tracker = new PingMonitorStatusTracker(); + + Assert.True(tracker.IsPending); + Assert.False(tracker.IsReachable); + } + + [Fact] + public void InitialStateIsEstablishedSilently() + { + var tracker = new PingMonitorStatusTracker(); + + Assert.Equal([PingMonitorStatusChange.Initial, PingMonitorStatusChange.None], + Add(tracker, 1, 3, true, true)); + Assert.False(tracker.IsPending); + Assert.True(tracker.IsReachable); + } + + [Fact] + public void InitialDownNeedsTheFailureThreshold() + { + var tracker = new PingMonitorStatusTracker(); + + Assert.Equal( + [PingMonitorStatusChange.None, PingMonitorStatusChange.None, PingMonitorStatusChange.Initial], + Add(tracker, 1, 3, false, false, false)); + Assert.False(tracker.IsReachable); + } + + [Fact] + public void StaysPendingUntilAThresholdIsReached() + { + var tracker = new PingMonitorStatusTracker(); + + Add(tracker, 3, 3, true, true, false, false, true); + + Assert.True(tracker.IsPending); + } + + [Fact] + public void DownAndUpAfterTheThresholds() + { + var tracker = new PingMonitorStatusTracker(); + + Assert.Equal( + [ + PingMonitorStatusChange.None, PingMonitorStatusChange.Initial, PingMonitorStatusChange.None, + PingMonitorStatusChange.None, PingMonitorStatusChange.Down, PingMonitorStatusChange.None, + PingMonitorStatusChange.None, PingMonitorStatusChange.Up + ], Add(tracker, 2, 3, true, true, false, false, false, false, true, true)); + } + + [Fact] + public void FlappingBelowTheThresholdDoesNotChange() + { + var tracker = new PingMonitorStatusTracker(); + + Add(tracker, 1, 3, true); + + Assert.All(Add(tracker, 1, 3, false, false, true, false, false, true), + x => Assert.Equal(PingMonitorStatusChange.None, x)); + Assert.True(tracker.IsReachable); + } + + [Fact] + public void ThresholdOneChangesOnEveryPing() + { + var tracker = new PingMonitorStatusTracker(); + + Assert.Equal( + [ + PingMonitorStatusChange.Initial, PingMonitorStatusChange.Down, PingMonitorStatusChange.Up + ], Add(tracker, 1, 1, true, false, true)); + } + + [Fact] + public void ResetIsPendingAgain() + { + var tracker = new PingMonitorStatusTracker(); + + Add(tracker, 1, 1, true); + tracker.Reset(); + + Assert.True(tracker.IsPending); + Assert.False(tracker.IsReachable); + Assert.Equal([PingMonitorStatusChange.Initial], Add(tracker, 1, 1, false)); + } +} diff --git a/Source/NETworkManager.Tests/Network/PingTests.cs b/Source/NETworkManager.Tests/Network/PingTests.cs new file mode 100644 index 0000000000..d3eb285c23 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/PingTests.cs @@ -0,0 +1,21 @@ +using System.Net.NetworkInformation; +using NETworkManager.Models.Network; +using Xunit; +using Ping = NETworkManager.Models.Network.Ping; + +namespace NETworkManager.Tests.Network; + +public class PingTests +{ + [Theory] + [InlineData(IPStatus.Success, 0, "<1 ms")] + [InlineData(IPStatus.Success, 12, "12 ms")] + [InlineData(IPStatus.TtlExpired, 5, "5 ms")] + [InlineData(IPStatus.TimedOut, 0, "-/-")] + [InlineData(IPStatus.Unknown, 0, "-/-")] + [InlineData(IPStatus.DestinationHostUnreachable, 3, "-/-")] + public void TimeToString(IPStatus status, long time, string expected) + { + Assert.Equal(expected, Ping.TimeToString(status, time)); + } +} diff --git a/Source/NETworkManager.Tests/Utilities/DateTimeHelperTests.cs b/Source/NETworkManager.Tests/Utilities/DateTimeHelperTests.cs index d88ef6eefb..3ad312474e 100644 --- a/Source/NETworkManager.Tests/Utilities/DateTimeHelperTests.cs +++ b/Source/NETworkManager.Tests/Utilities/DateTimeHelperTests.cs @@ -6,6 +6,17 @@ namespace NETworkManager.Tests.Utilities; public class DateTimeHelperTests { + [Fact] + public void TimeOnlyIfToday() + { + var now = new DateTime(2026, 11, 29, 18, 0, 0); + + Assert.Equal("14:32:05", + DateTimeHelper.DateTimeToTimeOrDateTimeString(new DateTime(2026, 11, 29, 14, 32, 5), now)); + Assert.Equal("2026-11-28 23:59:59", + DateTimeHelper.DateTimeToTimeOrDateTimeString(new DateTime(2026, 11, 28, 23, 59, 59), now)); + } + [Theory] [InlineData(0, "00:00")] [InlineData(5, "00:05")] diff --git a/Source/NETworkManager.Utilities/DateTimeHelper.cs b/Source/NETworkManager.Utilities/DateTimeHelper.cs index 42eed2cbf9..773317eee3 100644 --- a/Source/NETworkManager.Utilities/DateTimeHelper.cs +++ b/Source/NETworkManager.Utilities/DateTimeHelper.cs @@ -27,6 +27,18 @@ public static string DateTimeToTimeString(DateTime dateTime) return dateTime.ToString("HH:mm:ss"); } + /// + /// Convert a DateTime to a string with the time only if it is today ("HH:mm:ss"), otherwise with the date + /// ("yyyy-MM-dd HH:mm:ss"), e.g. for the time of a status change of a long running monitor. + /// + /// DateTime to convert. + /// Current time (decides whether it is today). + /// Time, or date and time if it is not today. + public static string DateTimeToTimeOrDateTimeString(DateTime dateTime, DateTime now) + { + return dateTime.Date == now.Date ? dateTime.ToString("HH:mm:ss") : dateTime.ToString("yyyy-MM-dd HH:mm:ss"); + } + /// /// Convert the time until an event (e.g. the next refresh) to a countdown: "mm:ss", "h:mm:ss" from one hour /// (fixed width while counting down). Negative times are shown as "00:00". diff --git a/Source/NETworkManager/NotificationManager.cs b/Source/NETworkManager/NotificationManager.cs index 25172f3092..5cab685c9c 100644 --- a/Source/NETworkManager/NotificationManager.cs +++ b/Source/NETworkManager/NotificationManager.cs @@ -1,3 +1,4 @@ +using NETworkManager.Localization.Resources; using NETworkManager.Models; using NETworkManager.Settings; using System; @@ -76,6 +77,40 @@ public static IReadOnlyList FormatChanges(IReadOnlyList + /// Gets the lines of a notification with at most lines: the first changes one per + /// line, the remaining changes as one line per status, e.g. "(+47 more) · Down". Unlike + /// , the first changes are always shown (e.g. which hosts are down). + /// + /// One line per change, the most important first (e.g. the hosts that are down). + /// Maximum number of lines (at least one line per status of the remaining changes). + /// Lines of the notification. + public static IReadOnlyList LimitLines(IReadOnlyList lines, int maxLines = 6) + { + if (lines.Count <= maxLines) + return lines; + + // Statuses of the changes that don't fit: as many changes as possible, one line per status for the rest + var shown = maxLines; + + while (shown > 0) + { + var moreLines = lines.Skip(shown).Select(x => (x.Status, x.StatusKind)).Distinct().Count(); + + if (shown + moreLines <= maxLines) + break; + + shown--; + } + + var more = lines.Skip(shown) + .GroupBy(x => (x.Status, x.StatusKind)) + .Select(x => new NotificationLine(string.Format(Strings.PlusXMore, x.Count()), x.Key.Status, + x.Key.StatusKind)); + + return [.. lines.Take(shown), .. more]; + } + /// /// Returns the combined height (including margins) of all windows stacked below the given /// window, i.e. the vertical offset from the bottom edge at which it should be placed. diff --git a/Source/NETworkManager/ViewModels/DNSLookupHostViewModel.cs b/Source/NETworkManager/ViewModels/DNSLookupHostViewModel.cs index 5ca5fe8f9a..7248e71d8e 100644 --- a/Source/NETworkManager/ViewModels/DNSLookupHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/DNSLookupHostViewModel.cs @@ -117,7 +117,7 @@ private void AddTabAction() /// private bool LookupProfile_CanExecute(object obj) { - return !IsSearching && SelectedProfile != null; + return !IsProfileSearching && SelectedProfile != null; } /// diff --git a/Source/NETworkManager/ViewModels/IPGeolocationHostViewModel.cs b/Source/NETworkManager/ViewModels/IPGeolocationHostViewModel.cs index cae5201d56..71dd88f668 100644 --- a/Source/NETworkManager/ViewModels/IPGeolocationHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/IPGeolocationHostViewModel.cs @@ -115,7 +115,7 @@ private void AddTabAction() /// private bool QueryProfile_CanExecute(object obj) { - return !IsSearching && SelectedProfile != null; + return !IsProfileSearching && SelectedProfile != null; } /// diff --git a/Source/NETworkManager/ViewModels/IPScannerHostViewModel.cs b/Source/NETworkManager/ViewModels/IPScannerHostViewModel.cs index 3edf32e87e..081b457a57 100644 --- a/Source/NETworkManager/ViewModels/IPScannerHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/IPScannerHostViewModel.cs @@ -119,7 +119,7 @@ private void AddTabAction() /// private bool ScanProfile_CanExecute(object obj) { - return !IsSearching && SelectedProfile != null; + return !IsProfileSearching && SelectedProfile != null; } /// diff --git a/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs index 8409ed640a..30459c0677 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs @@ -1,3 +1,4 @@ +using log4net; using NETworkManager.Controls; using NETworkManager.Converters; using NETworkManager.Localization.Resources; @@ -6,6 +7,7 @@ using NETworkManager.Profiles; using NETworkManager.Settings; using NETworkManager.Utilities; +using NETworkManager.Utilities.WPF; using NETworkManager.Views; using System; using System.Collections.Generic; @@ -30,9 +32,214 @@ public class PingMonitorHostViewModel : ProfileHostViewModelBase { #region Variables + private static readonly ILog Log = LogManager.GetLogger(typeof(PingMonitorHostViewModel)); + private CancellationTokenSource _cancellationTokenSource; - private string _group = Strings.Hosts; // Default group name + // Group of the host set by SetHost (e.g. the group of a profile) and the input it belongs to: only used while the + // input wasn't changed, a host typed afterwards is added to the default group (Strings.Hosts) + private string _group; + private string _groupHost; + + /// + /// Status changes (up / down) of the hosts that are not notified yet: collected for + /// and shown as one notification (e.g. an + /// uplink outage with many hosts). A host that changes back within this time is removed. + /// + private readonly List<(PingMonitorViewModel Host, bool IsUp)> _pendingStatusChanges = []; + + private readonly DispatcherTimer _notificationTimer; + + /// + /// Delays filtering the hosts while the user is typing (see ). + /// + private readonly SearchDelay _hostsSearchDelay; + + /// + /// Interval of the summary / filter updates after status changes, see . + /// + private static readonly TimeSpan StatusUpdateInterval = TimeSpan.FromMilliseconds(250); + + /// + /// Updates the summaries (and the status filter) after status changes, see . + /// + private readonly DispatcherTimer _statusUpdateTimer; + + /// + /// Filters the hosts again after a hostname was resolved while a search is set - not on every change (a refresh + /// rebuilds the whole list with the charts). + /// + private readonly DispatcherTimer _refilterTimer; + + /// + /// Groups collapsed by the user. The group containers are created again when the hosts are filtered, so the + /// state is kept here. + /// + private readonly HashSet _collapsedGroups = []; + + /// + /// Result of the filter per host (last refresh) and the hosts whose status changed since the last update: the + /// list is only filtered again if a status change shows or hides a host. + /// + private readonly Dictionary _shownHosts = []; + + private readonly HashSet _statusChangedHosts = []; + + /// + /// Gets or sets the search text (title, IP address, hostname, group). The hosts are filtered after a short delay. + /// + public string HostsSearch + { + get; + set + { + if (value == field) + return; + + field = value; + + _hostsSearchDelay.Restart(); + + OnPropertyChanged(); + } + } + + /// + /// Gets or sets a value indicating whether the hosts that are up (and pending hosts) are shown (status filter). Only the display is filtered, + /// hidden hosts keep being pinged. + /// + public bool ShowUp + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + + ApplyFilter(); + } + } = true; + + /// + /// Gets or sets a value indicating whether the hosts that are down (and pending hosts) are shown (status filter). Only the display is filtered, + /// hidden hosts keep being pinged. + /// + public bool ShowDown + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + + ApplyFilter(); + } + } = true; + + /// + /// Gets or sets a value indicating whether the paused hosts are shown (status filter). Only the display is filtered, + /// hidden hosts keep being pinged. + /// + public bool ShowPaused + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + + ApplyFilter(); + } + } = true; + + /// + /// Gets a value indicating whether hosts are monitored but none matches the search / status filter. + /// + public bool IsNothingFound + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the number of monitored hosts (all hosts, also the ones hidden by the filter). + /// + public int HostsTotal + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the number of hosts that are up (all hosts, also the ones hidden by the filter). + /// + public int HostsUp + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the number of hosts that are down (all hosts, also the ones hidden by the filter). + /// + public int HostsDown + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the number of paused hosts (all hosts, also the ones hidden by the filter). + /// + public int HostsPaused + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } /// /// Gets or sets the host to ping. @@ -190,8 +397,37 @@ public PingMonitorHostViewModel() HostsView = CollectionViewSource.GetDefaultView(Hosts); HostsView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(PingMonitorView.Group))); HostsView.SortDescriptions.Add(new SortDescription(nameof(PingMonitorView.Group), ListSortDirection.Ascending)); + HostsView.Filter = o => + { + if (o is not PingMonitorView host) + return false; + + var shown = MatchesFilter(host.ViewModel); + + // Remembered to filter again only if a status change changes it (see StatusUpdateTimer_Tick) + _shownHosts[host.ViewModel] = shown; + + return shown; + }; Hosts.CollectionChanged += Hosts_CollectionChanged; + _hostsSearchDelay = new SearchDelay(GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan, ApplyFilter); + + _statusUpdateTimer = new DispatcherTimer { Interval = StatusUpdateInterval }; + _statusUpdateTimer.Tick += StatusUpdateTimer_Tick; + + _refilterTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) }; + _refilterTimer.Tick += (_, _) => + { + _refilterTimer.Stop(); + ApplyFilter(); + }; + + UpdateSummary(); + + _notificationTimer = new DispatcherTimer { Interval = GlobalStaticConfiguration.PingMonitor_NotificationDelay }; + _notificationTimer.Tick += NotificationTimer_Tick; + InitializeProfileHost(); } @@ -230,7 +466,7 @@ private void PingAction() private bool PingProfile_CanExecute(object obj) { - return !IsSearching && SelectedProfile != null; + return !IsProfileSearching && SelectedProfile != null; } private void PingProfileAction() @@ -270,10 +506,192 @@ private void PauseGroupAction(object group) host.Stop(); } + /// + /// Gets the command to filter right away (Enter in the search box). + /// + public ICommand ApplyHostsSearchCommand => _hostsSearchDelay.ApplyCommand; + + /// + /// Gets the command to clear the search and the status filter (all hosts are shown again). + /// + public ICommand ClearHostsFilterCommand => new RelayCommand(_ => ClearHostsFilterAction()); + + private void ClearHostsFilterAction() + { + // Filtered once at the end, not by every setter + _isClearingFilter = true; + + HostsSearch = string.Empty; + ShowUp = true; + ShowDown = true; + ShowPaused = true; + + _isClearingFilter = false; + + // Also stops the delay of the search + _hostsSearchDelay.Apply(); + } + + /// + /// Set while the filter is cleared (see ): the setters don't filter. + /// + private bool _isClearingFilter; + + /// + /// Gets the command to resume all paused hosts. + /// + public ICommand ResumeAllCommand => new RelayCommand(_ => ResumeAllAction(), _ => Hosts.Any(x => !x.IsRunning)); + + private void ResumeAllAction() + { + foreach (var host in Hosts.Where(x => !x.IsRunning)) + host.Start(); + } + + /// + /// Gets the command to pause all running hosts. + /// + public ICommand PauseAllCommand => new RelayCommand(_ => PauseAllAction(), _ => Hosts.Any(x => x.IsRunning)); + + private void PauseAllAction() + { + foreach (var host in Hosts.Where(x => x.IsRunning)) + host.Stop(); + } + + /// + /// Gets the command to close all hosts (with a confirmation for more than one host). + /// + public ICommand CloseAllCommand => new RelayCommand(_ => { _ = CloseAllAction(); }, + _ => Hosts.Count > 0 && !DialogHelper.IsAnyDialogOpen()); + + private async Task CloseAllAction() + { + if (Hosts.Count > 1 && !await DialogHelper.ShowConfirmationMessageAsync(Application.Current.MainWindow, + Strings.CloseAll, string.Format(Strings.CloseAllHostsMessage, Hosts.Count.ToString("N0")), + ChildWindowIcon.Question, Strings.CloseAll)) + return; + + foreach (var host in Hosts.ToList()) + RemoveHost(host); + } + + /// + /// Gets the command to expand the charts of all shown hosts. + /// + public ICommand ExpandAllCommand => new RelayCommand(_ => SetHostViewsExpanded(null, true), _ => Hosts.Count > 0); + + /// + /// Gets the command to collapse the charts of all shown hosts. + /// + public ICommand CollapseAllCommand => new RelayCommand(_ => SetHostViewsExpanded(null, false), _ => Hosts.Count > 0); + + /// + /// Gets the command to expand the charts of the shown hosts of a group. + /// + public ICommand ExpandGroupCommand => new RelayCommand(group => SetHostViewsExpanded(group?.ToString(), true)); + + /// + /// Gets the command to collapse the charts of the shown hosts of a group. + /// + public ICommand CollapseGroupCommand => new RelayCommand(group => SetHostViewsExpanded(group?.ToString(), false)); + + /// + /// Expands / collapses the charts of the shown hosts (the setting "Expand host view" is not changed, it is the + /// default for new hosts). + /// + /// Group of the hosts, null for all groups. + /// Expand or collapse. + private void SetHostViewsExpanded(string group, bool expanded) + { + foreach (var host in HostsView.Cast().Where(x => group == null || x.Group == group)) + host.ViewModel.ExpandHostView = expanded; + } + #endregion #region Methods + /// + /// Checks whether a host is shown with the search and the status filter. + /// + private bool MatchesFilter(PingMonitorViewModel host) + { + return PingMonitorHostFilter.Matches(host, ShowUp, ShowDown, ShowPaused, HostsSearch, host.Title, + host.IPAddress.ToString(), host.Hostname, host.Group); + } + + /// + /// Filters the hosts with the search and the status filter. + /// + private void ApplyFilter() + { + if (_isClearingFilter) + return; + + _refilterTimer.Stop(); + + HostsView.Refresh(); + + UpdateIsNothingFound(); + } + + private void UpdateIsNothingFound() + { + IsNothingFound = Hosts.Count > 0 && HostsView.IsEmpty; + } + + /// + /// Updates the counters of all hosts (not only the shown ones). Pending hosts are counted in the total only. + /// + private void UpdateSummary() + { + var up = 0; + var down = 0; + var paused = 0; + + foreach (var host in Hosts) + { + if (!host.IsRunning) + paused++; + else if (host.IsPending) + continue; + else if (host.IsReachable) + up++; + else + down++; + } + + HostsTotal = Hosts.Count; + HostsUp = up; + HostsDown = down; + HostsPaused = paused; + } + + /// + /// Gets whether a group is expanded (shown with its hosts), see . + /// + /// Name of the group. + /// False if the user collapsed the group. + public bool IsGroupExpanded(string group) + { + return !_collapsedGroups.Contains(group); + } + + /// + /// Keeps the state of a group expanded / collapsed by the user (the group is shown again with this state after + /// the hosts were filtered). + /// + /// Name of the group. + /// Expanded or collapsed. + public void SetGroupExpanded(string group, bool expanded) + { + if (expanded) + _collapsedGroups.Remove(group); + else + _collapsedGroups.Add(group); + } + /// /// Adds the host(s) and starts the ping monitor. /// @@ -313,8 +731,8 @@ public bool SetHost(string host, string group = null) return false; } - if (group != null) - _group = group; + _group = group; + _groupHost = host; Host = host; @@ -339,6 +757,40 @@ private void AddStatusMessage(string message, StatusLevel level) /// public async Task Start() { + // The input and its group when the start was requested (the input can be changed while the dialog is open or + // the hostnames are resolved) + var input = Host; + var group = _group != null && input == _groupHost ? _group : Strings.Hosts; + + // Refuse inputs that can't get below the limit (e.g. 10.0.0.0/8) before they are resolved (memory, time). The + // limits of the Ping Monitor are checked after the exclusions and the already monitored hosts were removed + // (see below), so e.g. a /16 with exclusions is still possible. + long hostCount; + + try + { + hostCount = HostRangeHelper.GetHostCount(HostRangeHelper.CreateListFromInput(input)); + } + catch (Exception ex) + { + Log.Error("Error while counting the hosts", ex); + + StatusMessage = Strings.EnterValidHosts; + StatusMessageLevel = StatusLevel.Error; + IsStatusMessageDisplayed = true; + + return; + } + + if (hostCount > GlobalStaticConfiguration.PingMonitor_MaxInputHostCount) + { + // Replaces the messages of the previous start + IsStatusMessageDisplayed = false; + ShowTooManyHostsMessage(hostCount); + + return; + } + IsStatusMessageDisplayed = false; IsRunning = true; @@ -350,7 +802,7 @@ public async Task Start() try { - hosts = await HostRangeHelper.ResolveAsync(HostRangeHelper.CreateListFromInput(Host), + hosts = await HostRangeHelper.ResolveAsync(HostRangeHelper.CreateListFromInput(input), SettingsManager.Current.Network_ResolveHostnamePreferIPv4, keepAllHostnames: true, _cancellationTokenSource.Token); } @@ -382,13 +834,47 @@ public async Task Start() return; } + // Hosts already monitored in the group are skipped (the same IP address in another group is added) + var (hostsToAdd, alreadyMonitored) = PingMonitorHostHelper.SplitAlreadyMonitored(hosts.hosts, + Hosts.Where(x => x.Group == group).Select(x => x.ViewModel.IPAddress)); + + // Every host is pinged continuously and has its own chart: refuse too many hosts (e.g. a /16) instead of + // freezing the application and ask before adding many - counted without the exclusions and the already + // monitored hosts. The input is kept to correct it. + if (hostsToAdd.Count > GlobalStaticConfiguration.PingMonitor_MaxHostCount) + { + ShowTooManyHostsMessage(hostsToAdd.Count); + + IsCanceling = false; + IsRunning = false; + + return; + } + + // The ping command can't be executed while the dialog is open (Ping_CanExecute) + if (hostsToAdd.Count > GlobalStaticConfiguration.PingMonitor_ConfirmHostCount && + !await DialogHelper.ShowConfirmationMessageAsync(Application.Current.MainWindow, Strings.PingMonitor, + string.Format(Strings.PingMonitorManyHostsMessage, hostsToAdd.Count.ToString("N0")), + ChildWindowIcon.Warn, Strings.Add)) + { + IsCanceling = false; + IsRunning = false; + + return; + } + // Add host(s) to history - ListHelper.Modify(SettingsManager.Current.PingMonitor_HostHistory, Host, + ListHelper.Modify(SettingsManager.Current.PingMonitor_HostHistory, input, SettingsManager.Current.General_HistoryListEntries); + if (alreadyMonitored.Count > 0) + AddStatusMessage( + $"{Strings.TheFollowingHostsAreAlreadyMonitoredInThisGroup} {string.Join(", ", alreadyMonitored.Select(x => NotificationLine.FormatHost(x.ipAddress, x.hostname)))}", + StatusLevel.None); + // Add host(s) to list and start the ping - foreach (var hostView in hosts.hosts.Select(currentHost => - new PingMonitorView(Guid.NewGuid(), RemoveHostByGuid, currentHost, _group))) + foreach (var hostView in hostsToAdd.Select(currentHost => + new PingMonitorView(Guid.NewGuid(), RemoveHostByGuid, currentHost, group))) { // Check if the user has canceled the operation if (_cancellationTokenSource.IsCancellationRequested) @@ -407,13 +893,25 @@ public async Task Start() await Task.Delay(25); } + // Also if every host was already monitored (nothing to correct) Host = string.Empty; - _group = Strings.Hosts; // Reset the group + _group = null; + _groupHost = null; IsCanceling = false; IsRunning = false; } + /// + /// Shows that too many hosts were entered (maximum ). + /// + /// Number of hosts of the input. + private void ShowTooManyHostsMessage(long hostCount) + { + AddStatusMessage(string.Format(Strings.PingMonitorTooManyHostsMessage, hostCount.ToString("N0"), + GlobalStaticConfiguration.PingMonitor_MaxHostCount.ToString("N0")), StatusLevel.Error); + } + private void Stop() { IsCanceling = true; @@ -422,31 +920,27 @@ private void Stop() private void RemoveGroup(string group) { - for (var i = Hosts.Count - 1; i >= 0; i--) - { - if (!Hosts[i].Group.Equals(group)) - continue; - - Hosts[i].Stop(); - Hosts[i].Cleanup(); - Hosts.RemoveAt(i); - } + foreach (var host in Hosts.Where(x => x.Group == group).ToList()) + RemoveHost(host); } private void RemoveHostByGuid(Guid hostId) { - var i = -1; - - foreach (var host in Hosts) - if (host.HostId.Equals(hostId)) - i = Hosts.IndexOf(host); + var host = Hosts.FirstOrDefault(x => x.HostId == hostId); - if (i == -1) - return; + if (host != null) + RemoveHost(host); + } - Hosts[i].Stop(); - Hosts[i].Cleanup(); - Hosts.RemoveAt(i); + /// + /// Stops the host, releases its subscriptions and removes it from the list. + /// + /// Host to remove. + private void RemoveHost(PingMonitorView host) + { + host.Stop(); + host.Cleanup(); + Hosts.Remove(host); } #endregion @@ -465,39 +959,194 @@ private void UserHasCanceled() /// /// Keeps each host's subscription in - /// sync with , and bumps so the - /// per-group up/down summary () re-evaluates. + /// sync with , and schedules the update of so the + /// per-group summary () re-evaluates. /// private void Hosts_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.NewItems != null) foreach (PingMonitorView host in e.NewItems) + { host.ViewModel.PropertyChanged += HostViewModel_PropertyChanged; + host.ViewModel.StatusChanged += HostViewModel_StatusChanged; + } if (e.OldItems != null) foreach (PingMonitorView host in e.OldItems) + { host.ViewModel.PropertyChanged -= HostViewModel_PropertyChanged; + host.ViewModel.StatusChanged -= HostViewModel_StatusChanged; - HostsChangeVersion++; + // A closed host is not notified anymore + _pendingStatusChanges.RemoveAll(x => x.Host == host.ViewModel); + _shownHosts.Remove(host.ViewModel); + _statusChangedHosts.Remove(host.ViewModel); + + // The last host of a group was closed: a group with this name added later is expanded again + if (!Hosts.Any(x => x.Group == host.Group)) + _collapsedGroups.Remove(host.Group); + } + + // Many hosts are added one after the other (a range) - updated at most every StatusUpdateInterval + ScheduleStatusUpdate(); } /// - /// Bumps whenever a host's reachability or running state - /// changes, so the per-group up/down summary re-evaluates. + /// Schedules the update of the summaries when a host's reachability, pending or running state changes (and + /// drops a pending notification of a host that was paused / started again); filters again when a hostname + /// was resolved while a search is set. /// /// - /// / - /// are updated directly from each host's background ping loop (not marshaled to the UI - /// thread), so this handler can be invoked concurrently for multiple hosts. The increment - /// is marshaled to the UI thread so it's never lost - and never silently suppressed by the - /// property setter's equality check - to a concurrent write from another host. + /// The state of a host is only changed on the UI thread (see + /// ), so this handler is never called concurrently. /// private void HostViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) { - if (e.PropertyName is not (nameof(PingMonitorViewModel.IsReachable) or nameof(PingMonitorViewModel.IsRunning))) + switch (e.PropertyName) + { + case nameof(PingMonitorViewModel.IsReachable) or nameof(PingMonitorViewModel.IsPending): + if (sender is PingMonitorViewModel changedHost) + _statusChangedHosts.Add(changedHost); + + ScheduleStatusUpdate(); + break; + case nameof(PingMonitorViewModel.IsRunning): + if (sender is PingMonitorViewModel host) + { + // Paused or started again: a pending notification of the old status is dropped + _pendingStatusChanges.RemoveAll(x => x.Host == host); + _statusChangedHosts.Add(host); + } + + ScheduleStatusUpdate(); + break; + // The PTR record was resolved after the host was added: the search may match it now + case nameof(PingMonitorViewModel.Title) or nameof(PingMonitorViewModel.Hostname): + if (!string.IsNullOrWhiteSpace(HostsSearch) && !_refilterTimer.IsEnabled) + _refilterTimer.Start(); + break; + } + } + + /// + /// Updates the group summaries, the counters and (with a status filter) the filter at most every + /// - not for every status change: thousands of hosts change their status + /// at once after they were added or an uplink outage, and every group summary counts all hosts. + /// + private void ScheduleStatusUpdate() + { + if (!_statusUpdateTimer.IsEnabled) + _statusUpdateTimer.Start(); + } + + private void StatusUpdateTimer_Tick(object sender, EventArgs e) + { + _statusUpdateTimer.Stop(); + + HostsChangeVersion++; + + UpdateSummary(); + + // Filter again (a rebuild of the list with the charts) only if a status change shows or hides a host + var refilter = _statusChangedHosts.Any(x => + _shownHosts.TryGetValue(x, out var shown) && shown != MatchesFilter(x)); + + _statusChangedHosts.Clear(); + + if (refilter) + ApplyFilter(); + else + UpdateIsNothingFound(); + } + + /// + /// Collects the status change of a host for the combined notification. A host that changes back before the + /// notification is shown (e.g. down and up again) is removed - its status is the same as before. + /// + private void HostViewModel_StatusChanged(object sender, EventArgs e) + { + if (sender is not PingMonitorViewModel host) return; - Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Normal, () => HostsChangeVersion++); + // The status at the time of the change (the host may be paused / restarted before the notification is shown) + if (_pendingStatusChanges.RemoveAll(x => x.Host == host) == 0) + _pendingStatusChanges.Add((host, host.IsReachable)); + + // Not restarted by further changes, so a notification is shown at the latest after the delay + if (!_notificationTimer.IsEnabled) + _notificationTimer.Start(); + } + + private void NotificationTimer_Tick(object sender, EventArgs e) + { + _notificationTimer.Stop(); + + var changes = _pendingStatusChanges.ToList(); + _pendingStatusChanges.Clear(); + + ShowStatusNotification(changes); + } + + /// + /// Shows one notification for the status changes of the hosts (see settings): one host as before (title = host, + /// line = IP address and status), several hosts one per line, the hosts that are down first; hosts that don't + /// fit (more than six lines) as "(+47 more) · Down". Only up = up, only down = down, both = up and down. + /// + /// Hosts whose status changed, with the status at the time of the change. + private static void ShowStatusNotification(List<(PingMonitorViewModel Host, bool IsUp)> changes) + { + var showPopup = SettingsManager.Current.PingMonitor_ShowNotificationPopup; + var playSound = SettingsManager.Current.PingMonitor_NotificationSound; + + if (changes.Count == 0 || (!showPopup && !playSound)) + return; + + var up = changes.Count(x => x.IsUp); + var down = changes.Count - up; + + var status = NotificationStatusHelper.FromChanges(up, down, 0); + + NotificationInfo notification; + + if (changes.Count == 1) + { + var (host, isUp) = changes[0]; + + notification = new NotificationInfo(ApplicationName.PingMonitor, status, host.NotificationHostDisplay, + [GetNotificationLine(host.NotificationIPAddress, isUp)], + SettingsManager.Current.PingMonitor_NotificationCloseTime); + } + else + { + // The hosts that are down first (what needs attention), then by IP address + changes.Sort((x, y) => x.IsUp != y.IsUp + ? x.IsUp.CompareTo(y.IsUp) + : IPAddressHelper.CompareIPAddresses(x.Host.IPAddress, y.Host.IPAddress)); + + // "10.0.0.5 (server) · Down", the hosts that don't fit as "(+47 more) · Down" + var lines = changes.Select(x => GetNotificationLine( + NotificationLine.FormatHost(x.Host.IPAddress, DNSClientHelper.SanitizeHostname(x.Host.Hostname)), + x.IsUp)).ToList(); + + // The group if all hosts are in the same group, otherwise the tool + var groups = changes.Select(x => x.Host.Group).Distinct().ToList(); + + notification = new NotificationInfo(ApplicationName.PingMonitor, status, + groups.Count == 1 ? groups[0] : Strings.PingMonitor, NotificationManager.LimitLines(lines), + SettingsManager.Current.PingMonitor_NotificationCloseTime); + } + + NotificationManager.Show(notification, showPopup, playSound); + } + + /// + /// Line of a notification with the status of the change (up / down). + /// + private static NotificationLine GetNotificationLine(string text, bool isUp) + { + return isUp + ? new NotificationLine(text, Strings.Up, NotificationStatus.Up) + : new NotificationLine(text, Strings.Down, NotificationStatus.Down); } #endregion diff --git a/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs index f3692fbaa7..f862d0f26b 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs @@ -144,6 +144,25 @@ public int ChartTime } } + /// + /// Gets or sets the hours the pings of a host are kept in the history. + /// + public int HistoryHours + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.PingMonitor_HistoryHours = value; + + field = value; + OnPropertyChanged(); + } + } + /// /// Gets or sets a value indicating whether a notification popup is shown on status change. /// @@ -264,6 +283,7 @@ private void LoadSettings() WaitTime = SettingsManager.Current.PingMonitor_WaitTime; ExpandHostView = SettingsManager.Current.PingMonitor_ExpandHostView; ChartTime = SettingsManager.Current.PingMonitor_ChartTime; + HistoryHours = SettingsManager.Current.PingMonitor_HistoryHours; ShowNotificationPopup = SettingsManager.Current.PingMonitor_ShowNotificationPopup; NotificationSound = SettingsManager.Current.PingMonitor_NotificationSound; NotificationSuccessThreshold = SettingsManager.Current.PingMonitor_NotificationSuccessThreshold; diff --git a/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs index 5ea49d17c2..b464335f4a 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs @@ -66,8 +66,8 @@ public PingMonitorViewModel(Guid hostId, Action removeHostByGuid, private static readonly ILog Log = LogManager.GetLogger(typeof(PingMonitorViewModel)); private CancellationTokenSource _cancellationTokenSource; + private HostMonitor _hostMonitor; private int _maxPingValues; - private int _sessionId; private bool _updatingAxisFromCode; public readonly Guid HostId; @@ -75,12 +75,17 @@ public PingMonitorViewModel(Guid hostId, Action removeHostByGuid, private List _pingInfoList = []; - // Notification threshold tracking. The status transition (and notification) only fires once - // the configured number of consecutive successes/failures is reached, to avoid noise from - // flapping hosts. The initial state is established silently (no notification). - private int _consecutiveSuccesses; - private int _consecutiveFailures; - private bool _initialStateEstablished; + // Status (up / down) with the notification thresholds, see PingMonitorStatusTracker + private readonly PingMonitorStatusTracker _statusTracker = new(); + + // Minimum / average / maximum / jitter of all replies since the start + private readonly LatencyAccumulator _latency = new(); + + // Day on which StatusTimeText was last updated: after midnight it gets the date (long running monitor) + private DateTime _statusTimeTextDate; + + // Wait time of the running pings (settings apply when the host is started) + private int _waitTime = SettingsManager.Current.PingMonitor_WaitTime; /// /// Gets the title of the monitor, typically "Hostname # IP". @@ -103,13 +108,13 @@ private set /// otherwise the IP address as a fallback. Without a trailing dot (single-label name from DNS like /// "gateway." or a hostname entered with a dot). /// - private string NotificationHostDisplay => + public string NotificationHostDisplay => DNSClientHelper.SanitizeHostname(Hostname) is { Length: > 0 } hostname ? hostname : IPAddress.ToString(); /// /// IP address in the line of a notification ("10.0.0.1 · Up"), null if the title already is the IP address. /// - private string NotificationIPAddress => + public string NotificationIPAddress => NotificationHostDisplay == IPAddress.ToString() ? null : IPAddress.ToString(); /// @@ -192,6 +197,23 @@ public bool IsReachable } } + /// + /// Gets a value indicating whether the status of the host is not established yet (after the start, until the + /// success / failure threshold is reached): shown neither as up nor as down. + /// + public bool IsPending + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = true; + /// /// Gets the time of the last status update. /// @@ -204,15 +226,22 @@ private set return; field = value; + _statusTimeTextDate = DateTime.Today; OnPropertyChanged(); + OnPropertyChanged(nameof(StatusTimeText)); OnPropertyChanged(nameof(StatusTimeToolTip)); } } /// - /// Gets the tooltip text for the connectivity icon, e.g. "Last status change: 14:32:05". + /// Gets the time of the last status change, with the date if it is not today (long running monitor). /// - public string StatusTimeToolTip => $"{Strings.StatusChange}: {StatusTime:HH:mm:ss}"; + public string StatusTimeText => DateTimeHelper.DateTimeToTimeOrDateTimeString(StatusTime, DateTime.Now); + + /// + /// Gets the tooltip text for the connectivity icon, e.g. "Status change: 14:32:05". + /// + public string StatusTimeToolTip => $"{Strings.StatusChange}: {StatusTimeText}"; /// /// Gets or sets the total number of ping packets transmitted. @@ -279,12 +308,12 @@ public double PacketLoss } /// - /// Gets or sets the round-trip time in milliseconds of the last ping. + /// Gets the round-trip time of the last ping, e.g. "4 ms", "<1 ms", or "-/-" without a reply. /// - public long TimeMs + public string TimeText { get; - set + private set { if (value == field) return; @@ -292,8 +321,53 @@ public long TimeMs field = value; OnPropertyChanged(); } + } = "-/-"; + + /// + /// Gets the lowest round-trip time since the start, e.g. "4 ms", "-/-" without a reply. + /// + public string MinimumTimeText => LatencyStatistics.FormatTime(_latency.Minimum); + + /// + /// Gets the average round-trip time since the start, e.g. "12 ms", "-/-" without a reply. + /// + public string AverageTimeText => LatencyStatistics.FormatTime(_latency.Average); + + /// + /// Gets the highest round-trip time since the start, e.g. "40 ms", "-/-" without a reply. + /// + public string MaximumTimeText => LatencyStatistics.FormatTime(_latency.Maximum); + + /// + /// Gets the jitter (average difference of consecutive round-trip times) since the start, "-/-" with less than two + /// replies. + /// + public string JitterText => LatencyStatistics.FormatTime(_latency.Jitter); + + /// + /// Gets the tooltip of the counters: minimum, average, maximum and jitter since the start. + /// + public string StatisticsToolTip => + $"{Strings.Minimum}: {MinimumTimeText}{Environment.NewLine}{Strings.AverageTime}: {AverageTimeText}{Environment.NewLine}{Strings.Maximum}: {MaximumTimeText}{Environment.NewLine}{Strings.Jitter}: {JitterText}"; + + /// + /// Raises the change notifications of the statistics (after a reply or a reset). + /// + private void OnStatisticsChanged() + { + OnPropertyChanged(nameof(MinimumTimeText)); + OnPropertyChanged(nameof(AverageTimeText)); + OnPropertyChanged(nameof(MaximumTimeText)); + OnPropertyChanged(nameof(JitterText)); + OnPropertyChanged(nameof(StatisticsToolTip)); } + /// + /// Occurs when the host went up or down (after the thresholds; not for the initial status). The Ping Monitor shows + /// one notification for the changes of all hosts within a short time. + /// + public event EventHandler StatusChanged; + private ObservableCollection _pingValues; /// @@ -404,7 +478,8 @@ private set } /// - /// Gets the error message if an error occurs. + /// Gets the error message of the last ping, if it failed with an error (e.g. no network). Cleared by the next ping + /// without an error. /// public string ErrorMessage { @@ -420,7 +495,7 @@ private set } /// - /// Gets or sets a value indicating whether the error message is displayed. + /// Gets or sets a value indicating whether the error message is displayed (instead of the status icon). /// public bool IsErrorMessageDisplayed { @@ -481,6 +556,24 @@ private void CloseAction() _removeHostByGuid(HostId); } + /// + /// Gets the command to open the host in another application (e.g. Port Scanner, Remote Desktop). + /// + public ICommand RedirectDataToApplicationCommand => new RelayCommand(RedirectDataToApplicationAction); + + private void RedirectDataToApplicationAction(object name) + { + if (name is not ApplicationName applicationName) + return; + + // The hostname (without a trailing dot from DNS), otherwise the IP address + var host = DNSClientHelper.SanitizeHostname(Hostname) is { Length: > 0 } hostname + ? hostname + : IPAddress.ToString(); + + NavigationManager.Open(new ApplicationRequest(applicationName) { Target = host }); + } + /// /// Gets the command to export the ping monitoring results of this host. /// @@ -523,12 +616,15 @@ private void GoLiveAction() /// public void Start() { + // The previous run must have ended (Stopped) - otherwise two loops would update this host + if (IsRunning) + return; + IsErrorMessageDisplayed = false; + ErrorMessage = null; IsRunning = true; IsLiveMode = true; - _sessionId++; - // Reset history _pingInfoList = []; @@ -538,15 +634,19 @@ public void Start() Received = 0; Lost = 0; PacketLoss = 0; - - // Reset notification threshold tracking so the initial state is re-established silently. - // IsReachable is cleared too, so a prior run's state can't linger and show a stale (e.g. - // green "up") icon during the first few pings before the new initial state is established. - _consecutiveSuccesses = 0; - _consecutiveFailures = 0; - _initialStateEstablished = false; + TimeText = "-/-"; + _latency.Reset(); + OnStatisticsChanged(); + + // The status is established again (silently, pending until then). IsReachable is cleared too, so the state of + // the previous run can't linger. + _statusTracker.Reset(); + IsPending = true; IsReachable = false; + // Settings of the ping apply when the host is (re)started + _waitTime = SettingsManager.Current.PingMonitor_WaitTime; + // Reset chart _sessionStartTime = DateTime.Now; ResetTimeChart(); @@ -556,21 +656,21 @@ public void Start() UpdateMaxPingValues(); - var ping = new Ping + var probe = new ICMPHostMonitorProbe(IPAddress, SettingsManager.Current.PingMonitor_Timeout, + GlobalStaticConfiguration.LimitICMPBuffer(SettingsManager.Current.PingMonitor_Buffer), + SettingsManager.Current.PingMonitor_TTL, SettingsManager.Current.PingMonitor_DontFragment); + + // The known hostname (typed, from DNS or resolved before) is kept, the PTR record is only resolved without one + _hostMonitor = new HostMonitor(IPAddress, Hostname, probe) { - Timeout = SettingsManager.Current.PingMonitor_Timeout, - BufferSize = GlobalStaticConfiguration.LimitICMPBuffer(SettingsManager.Current.PingMonitor_Buffer), - TTL = SettingsManager.Current.PingMonitor_TTL, - DontFragment = SettingsManager.Current.PingMonitor_DontFragment, - WaitTime = SettingsManager.Current.PingMonitor_WaitTime + WaitTime = _waitTime }; - ping.PingReceived += Ping_PingReceived; - ping.PingException += Ping_PingException; - ping.HostnameResolved += Ping_HostnameResolved; - ping.UserHasCanceled += Ping_UserHasCanceled; + _hostMonitor.PingReceived += HostMonitor_PingReceived; + _hostMonitor.HostnameResolved += HostMonitor_HostnameResolved; + _hostMonitor.Stopped += HostMonitor_Stopped; - ping.SendAsync(IPAddress, _cancellationTokenSource.Token); + _hostMonitor.Start(_cancellationTokenSource.Token); } /// @@ -582,6 +682,11 @@ public void Stop() return; _cancellationTokenSource?.Cancel(); + + // Paused right away (the button switches, Resume works at once); the last events of the stopping monitor are + // ignored (sender is no longer _hostMonitor) + _hostMonitor = null; + IsRunning = false; } private DateTime _sessionStartTime; @@ -662,147 +767,146 @@ await DialogHelper.ShowMessageAsync(Application.Current.MainWindow, Strings.Erro #region Events /// - /// Handles the PingReceived event. Updates statistics and the chart. + /// Handles the PingReceived event (thread pool thread): the ping is processed on the UI thread, where every state of + /// this host is changed (statistics, status, history, chart), so nothing is changed concurrently. /// - /// The source of the event. + /// The host monitor that sent the ping. /// The instance containing the event data. - private void Ping_PingReceived(object sender, PingReceivedArgs e) + private void HostMonitor_PingReceived(object sender, PingReceivedArgs e) { - // Calculate statistics - Transmitted++; + // Null exception may occur when the application is closing + Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Normal, () => + { + // A late ping of a previous run (or of a closed host) + if (!ReferenceEquals(sender, _hostMonitor)) + return; - LvlChartsDefaultInfo timeInfo; + OnPingReceived(e); + }); + } - var successThreshold = SettingsManager.Current.PingMonitor_NotificationSuccessThreshold; - var failureThreshold = SettingsManager.Current.PingMonitor_NotificationFailureThreshold; + /// + /// Shows the time of the last status change with the date once a day passed (long running monitor). Called for + /// every ping and by the view when the tooltip / context menu opens (a paused host gets no pings). + /// + public void RefreshStatusTimeText() + { + if (_statusTimeTextDate == DateTime.Today) + return; - if (e.Args.Status == IPStatus.Success) - { - _consecutiveSuccesses++; - _consecutiveFailures = 0; + _statusTimeTextDate = DateTime.Today; + OnPropertyChanged(nameof(StatusTimeText)); + OnPropertyChanged(nameof(StatusTimeToolTip)); + } - if (!_initialStateEstablished) - { - if (_consecutiveSuccesses >= successThreshold) - { - _initialStateEstablished = true; - StatusTime = DateTime.Now; - IsReachable = true; - // No notification — this is the initial state being established. - } - } - else if (!IsReachable && _consecutiveSuccesses >= successThreshold) - { - StatusTime = DateTime.Now; - IsReachable = true; - - NotificationManager.Show(new NotificationInfo(ApplicationName.PingMonitor, NotificationStatus.Up, - NotificationHostDisplay, [new NotificationLine(NotificationIPAddress, Strings.Up, NotificationStatus.Up)], - SettingsManager.Current.PingMonitor_NotificationCloseTime), - SettingsManager.Current.PingMonitor_ShowNotificationPopup, - SettingsManager.Current.PingMonitor_NotificationSound); - } + /// + /// Updates statistics, status, history and the chart with a ping. Runs on the UI thread. + /// + /// The instance containing the event data. + private void OnPingReceived(PingReceivedArgs e) + { + RefreshStatusTimeText(); + + // Calculate statistics + Transmitted++; + + var success = e.Args.Status == IPStatus.Success; + if (success) + { Received++; - timeInfo = new LvlChartsDefaultInfo(e.Args.Timestamp, e.Args.Time); + _latency.Add(e.Args.Time); + OnStatisticsChanged(); } else { - _consecutiveFailures++; - _consecutiveSuccesses = 0; - - if (!_initialStateEstablished) - { - if (_consecutiveFailures >= failureThreshold) - { - _initialStateEstablished = true; - StatusTime = DateTime.Now; - IsReachable = false; - // No notification or sound — initial state. - } - } - else if (IsReachable && _consecutiveFailures >= failureThreshold) - { - StatusTime = DateTime.Now; - IsReachable = false; - - NotificationManager.Show(new NotificationInfo(ApplicationName.PingMonitor, NotificationStatus.Down, - NotificationHostDisplay, [new NotificationLine(NotificationIPAddress, Strings.Down, NotificationStatus.Down)], - SettingsManager.Current.PingMonitor_NotificationCloseTime), - SettingsManager.Current.PingMonitor_ShowNotificationPopup, - SettingsManager.Current.PingMonitor_NotificationSound); - } - Lost++; - - timeInfo = new LvlChartsDefaultInfo(e.Args.Timestamp, double.NaN); } - PacketLoss = Math.Round((double)Lost / Transmitted * 100, 2); - TimeMs = e.Args.Time; + var change = _statusTracker.Add(success, SettingsManager.Current.PingMonitor_NotificationSuccessThreshold, + SettingsManager.Current.PingMonitor_NotificationFailureThreshold); - // Null exception may occur when the application is closing - var capturedSession = _sessionId; - Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Normal, () => + if (change != PingMonitorStatusChange.None) { - if (_sessionId != capturedSession) - return; + StatusTime = DateTime.Now; + IsReachable = _statusTracker.IsReachable; + IsPending = false; + } - // Add to history - on the UI thread, like every other access to it (export, GoLiveAction) - _pingInfoList.Add(e.Args); + // The initial status is established silently, only later changes are notified (combined by the Ping Monitor) + if (change is PingMonitorStatusChange.Up or PingMonitorStatusChange.Down) + StatusChanged?.Invoke(this, EventArgs.Empty); - // While the user is inspecting the chart (zoomed/panned, i.e. not live), keep - // the chart frozen: ignore new samples here so the view does not move and the - // buffer does not grow. The sample is still recorded in the history above and - // becomes visible again when the user returns to live mode (see GoLiveAction). - if (!IsLiveMode) - return; + var timeInfo = new LvlChartsDefaultInfo(e.Args.Timestamp, success ? e.Args.Time : double.NaN); - _pingValues.Add(timeInfo); - if (_pingValues.Count > _maxPingValues) - _pingValues.RemoveAt(0); + PacketLoss = Math.Round((double)Lost / Transmitted * 100, 2); + TimeText = Ping.TimeToString(e.Args.Status, e.Args.Time); + + // A ping that failed with an error (e.g. no network) is counted as lost, the host keeps being pinged. The error + // is shown (status icon tooltip) until a ping works again. + ErrorMessage = e.ErrorMessage; + IsErrorMessageDisplayed = e.ErrorMessage != null; + + // Add to history, limited by age (PingMonitor_HistoryHours) + _pingInfoList.Add(e.Args); + PingMonitorHistory.Trim(_pingInfoList, DateTime.Now, + TimeSpan.FromHours(SettingsManager.Current.PingMonitor_HistoryHours)); + + // While the user is inspecting the chart (zoomed/panned, i.e. not live), keep + // the chart frozen: ignore new samples here so the view does not move and the + // buffer does not grow. The sample is still recorded in the history above and + // becomes visible again when the user returns to live mode (see GoLiveAction). + if (!IsLiveMode) + return; - UpdateXAxisWindow(timeInfo.DateTime); - UpdateYAxis(); - }); + _pingValues.Add(timeInfo); + if (_pingValues.Count > _maxPingValues) + _pingValues.RemoveAt(0); + + UpdateXAxisWindow(timeInfo.DateTime); + UpdateYAxis(); } /// - /// Handles the UserHasCanceled event. Stops the monitoring. + /// Handles the Stopped event of the host monitor (paused, closed or an unexpected error). /// - /// The source of the event. + /// The host monitor that stopped. /// The instance containing the event data. - private void Ping_UserHasCanceled(object sender, EventArgs e) + private void HostMonitor_Stopped(object sender, EventArgs e) { - IsRunning = false; - } + // After the pings of this run (same priority, processed in order) + Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Normal, () => + { + if (!ReferenceEquals(sender, _hostMonitor)) + return; - /// - /// Handles the HostnameResolved event. Updates the hostname and title if necessary. - /// - /// The source of the event. - /// The instance containing the event data. - private void Ping_HostnameResolved(object sender, HostnameArgs e) - { - // Update title if name was not set in the constructor - if (string.IsNullOrEmpty(Hostname)) - Title = $"{DNSClientHelper.SanitizeHostname(e.Hostname)} # {IPAddress}"; + IsRunning = false; - Hostname = e.Hostname; + // Stopped by an unexpected error (not paused / closed): show why instead of a silent "paused" + if (sender is HostMonitor { StopErrorMessage: { } errorMessage }) + { + ErrorMessage = errorMessage; + IsErrorMessageDisplayed = true; + } + }); } /// - /// Handles the PingException event. Stops the monitoring and displays the error. + /// Handles the HostnameResolved event (only raised without a known hostname). Updates the hostname and title. /// - /// The source of the event. - /// The instance containing the event data. - private void Ping_PingException(object sender, PingExceptionArgs e) + /// The host monitor that resolved the hostname. + /// The instance containing the event data. + private void HostMonitor_HostnameResolved(object sender, HostnameArgs e) { - IsRunning = false; + Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Normal, () => + { + if (!ReferenceEquals(sender, _hostMonitor)) + return; - ErrorMessage = e.Message; - IsErrorMessageDisplayed = true; + Title = $"{DNSClientHelper.SanitizeHostname(e.Hostname)} # {IPAddress}"; + Hostname = e.Hostname; + }); } /// @@ -811,6 +915,9 @@ private void Ping_PingException(object sender, PingExceptionArgs e) /// public void Cleanup() { + // Late events of the (stopped) monitor are ignored + _hostMonitor = null; + SettingsManager.Current.PropertyChanged -= SettingsManager_PropertyChanged; AppearanceManager.ThemeResourcesChanged -= AppearanceManager_ThemeResourcesChanged; } @@ -841,9 +948,6 @@ private void SettingsManager_PropertyChanged(object sender, System.ComponentMode if (IsRunning && IsLiveMode) UpdateXAxisWindow(DateTime.Now); break; - case nameof(SettingsInfo.PingMonitor_WaitTime): - UpdateMaxPingValues(); - break; } } @@ -855,8 +959,8 @@ private void SettingsManager_PropertyChanged(object sender, System.ComponentMode private void UpdateMaxPingValues() { - var visibleValues = (double)SettingsManager.Current.PingMonitor_ChartTime * 1000 / - SettingsManager.Current.PingMonitor_WaitTime; + // With the wait time of the running pings (a changed setting applies when the host is started again) + var visibleValues = (double)SettingsManager.Current.PingMonitor_ChartTime * 1000 / _waitTime; _maxPingValues = (int)Math.Ceiling(visibleValues * PingValuesHeadroom); } diff --git a/Source/NETworkManager/ViewModels/PortScannerHostViewModel.cs b/Source/NETworkManager/ViewModels/PortScannerHostViewModel.cs index c06986aeff..0c31d32b62 100644 --- a/Source/NETworkManager/ViewModels/PortScannerHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/PortScannerHostViewModel.cs @@ -109,7 +109,7 @@ private void AddTabAction() private bool ScanProfile_CanExecute(object obj) { - return !IsSearching && SelectedProfile != null; + return !IsProfileSearching && SelectedProfile != null; } private void ScanProfileAction() diff --git a/Source/NETworkManager/ViewModels/PowerShellHostViewModel.cs b/Source/NETworkManager/ViewModels/PowerShellHostViewModel.cs index 3664e396c5..c841f80e27 100644 --- a/Source/NETworkManager/ViewModels/PowerShellHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/PowerShellHostViewModel.cs @@ -226,7 +226,7 @@ private void ResizeWindowAction(object view) private bool ConnectProfile_CanExecute(object obj) { - return !IsSearching && SelectedProfile != null; + return !IsProfileSearching && SelectedProfile != null; } private void ConnectProfileAction() @@ -255,7 +255,7 @@ public ICommand TextBoxSearchLostFocusCommand private void ClearSearchAction() { - Search = string.Empty; + ProfileSearch = string.Empty; } public ICommand OpenSettingsCommand => new RelayCommand(_ => OpenSettingsAction()); diff --git a/Source/NETworkManager/ViewModels/ProfileHostViewModelBase.cs b/Source/NETworkManager/ViewModels/ProfileHostViewModelBase.cs index a1c2a3e6ad..c2a36ba30a 100644 --- a/Source/NETworkManager/ViewModels/ProfileHostViewModelBase.cs +++ b/Source/NETworkManager/ViewModels/ProfileHostViewModelBase.cs @@ -24,7 +24,7 @@ public abstract class ProfileHostViewModelBase : ViewModelBase, IProfileHostView { #region Variables - private readonly SearchDelay _searchDelay; + private readonly SearchDelay _profileSearchDelay; private bool _searchDisabled; private bool _isViewActive = true; @@ -88,7 +88,7 @@ public virtual ProfileInfo SelectedProfile /// /// Gets or sets the search text. /// - public string Search + public string ProfileSearch { get; set @@ -101,8 +101,8 @@ public string Search // Start searching... if (!_searchDisabled) { - IsSearching = true; - _searchDelay.Restart(); + IsProfileSearching = true; + _profileSearchDelay.Restart(); } OnPropertyChanged(); @@ -112,7 +112,7 @@ public string Search /// /// Gets or sets a value indicating whether a search is in progress. /// - public bool IsSearching + public bool IsProfileSearching { get; set @@ -207,11 +207,11 @@ public bool IsProfileFilterSet /// /// Initializes the search delay, before the constructor of the derived class (which may already set - /// ). + /// ). /// protected ProfileHostViewModelBase() { - _searchDelay = new SearchDelay(GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan, ApplySearch); + _profileSearchDelay = new SearchDelay(GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan, ApplyProfileSearch); } /// @@ -326,7 +326,7 @@ private void ApplyProfileFilterAction() private void ClearProfileFilterAction() { _searchDisabled = true; - Search = string.Empty; + ProfileSearch = string.Empty; _searchDisabled = false; foreach (var tag in ProfileFilterTags) @@ -491,7 +491,7 @@ private void RefreshProfiles() var filter = new ProfileFilterInfo { - Search = Search, + Search = ProfileSearch, Tags = [.. ProfileFilterTags.Where(x => x.IsSelected).Select(x => x.Name)], TagsFilterMatch = ProfileFilterTagsMatchAny ? ProfileFilterTagsMatch.Any : ProfileFilterTagsMatch.All }; @@ -530,13 +530,13 @@ private void GroupExpanderStateStore_GroupExpandedChanged(object sender, GroupEx } /// - /// Filters the profiles with the current . + /// Filters the profiles with the current . /// - private void ApplySearch() + private void ApplyProfileSearch() { RefreshProfiles(); - IsSearching = false; + IsProfileSearching = false; } #endregion diff --git a/Source/NETworkManager/ViewModels/PuTTYHostViewModel.cs b/Source/NETworkManager/ViewModels/PuTTYHostViewModel.cs index 1956057ae7..c16e35884a 100644 --- a/Source/NETworkManager/ViewModels/PuTTYHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/PuTTYHostViewModel.cs @@ -234,7 +234,7 @@ private void RestartSessionAction(object view) private bool ConnectProfile_CanExecute(object obj) { - return !IsSearching && SelectedProfile != null; + return !IsProfileSearching && SelectedProfile != null; } private void ConnectProfileAction() diff --git a/Source/NETworkManager/ViewModels/RDAPHostViewModel.cs b/Source/NETworkManager/ViewModels/RDAPHostViewModel.cs index eadb7b0d7b..1603c98574 100644 --- a/Source/NETworkManager/ViewModels/RDAPHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/RDAPHostViewModel.cs @@ -86,7 +86,7 @@ private void AddTabAction() private bool QueryProfile_CanExecute(object obj) { - return !IsSearching && SelectedProfile != null; + return !IsProfileSearching && SelectedProfile != null; } private void QueryProfileAction() diff --git a/Source/NETworkManager/ViewModels/RemoteDesktopHostViewModel.cs b/Source/NETworkManager/ViewModels/RemoteDesktopHostViewModel.cs index 27b990ecb7..18b79835f9 100644 --- a/Source/NETworkManager/ViewModels/RemoteDesktopHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/RemoteDesktopHostViewModel.cs @@ -204,7 +204,7 @@ await DialogHelper.ShowMessageAsync(Application.Current.MainWindow, Strings.Erro private bool ConnectProfile_CanExecute(object obj) { - return !IsSearching && SelectedProfile != null; + return !IsProfileSearching && SelectedProfile != null; } private void ConnectProfileAction() diff --git a/Source/NETworkManager/ViewModels/SNMPHostViewModel.cs b/Source/NETworkManager/ViewModels/SNMPHostViewModel.cs index 4d215d8002..dc06ab3379 100644 --- a/Source/NETworkManager/ViewModels/SNMPHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/SNMPHostViewModel.cs @@ -83,7 +83,7 @@ private void AddTabAction() private bool AddTabProfile_CanExecute(object obj) { - return !IsSearching && SelectedProfile != null; + return !IsProfileSearching && SelectedProfile != null; } private void AddTabProfileAction() diff --git a/Source/NETworkManager/ViewModels/TigerVNCHostViewModel.cs b/Source/NETworkManager/ViewModels/TigerVNCHostViewModel.cs index 0656b89157..c1e6ce3061 100644 --- a/Source/NETworkManager/ViewModels/TigerVNCHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/TigerVNCHostViewModel.cs @@ -140,7 +140,7 @@ private void ReconnectAction(object view) private bool ConnectProfile_CanExecute(object obj) { - return !IsSearching && SelectedProfile != null; + return !IsProfileSearching && SelectedProfile != null; } private void ConnectProfileAction() diff --git a/Source/NETworkManager/ViewModels/TracerouteHostViewModel.cs b/Source/NETworkManager/ViewModels/TracerouteHostViewModel.cs index c32f43070a..52edb5bab4 100644 --- a/Source/NETworkManager/ViewModels/TracerouteHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/TracerouteHostViewModel.cs @@ -85,7 +85,7 @@ private void AddTabAction() private bool TraceProfile_CanExecute(object obj) { - return !IsSearching && SelectedProfile != null; + return !IsProfileSearching && SelectedProfile != null; } private void TraceProfileAction() diff --git a/Source/NETworkManager/ViewModels/WebConsoleHostViewModel.cs b/Source/NETworkManager/ViewModels/WebConsoleHostViewModel.cs index e359419d6a..de25627679 100644 --- a/Source/NETworkManager/ViewModels/WebConsoleHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/WebConsoleHostViewModel.cs @@ -140,7 +140,7 @@ private void ReloadAction(object view) private bool ConnectProfile_CanExecute(object obj) { - return !IsSearching && SelectedProfile != null; + return !IsProfileSearching && SelectedProfile != null; } private void ConnectProfileAction() diff --git a/Source/NETworkManager/ViewModels/WhoisHostViewModel.cs b/Source/NETworkManager/ViewModels/WhoisHostViewModel.cs index d6356fb6db..82b6ddd8a2 100644 --- a/Source/NETworkManager/ViewModels/WhoisHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/WhoisHostViewModel.cs @@ -85,7 +85,7 @@ private void AddTabAction() private bool QueryProfile_CanExecute(object obj) { - return !IsSearching && SelectedProfile != null; + return !IsProfileSearching && SelectedProfile != null; } private void QueryProfileAction() diff --git a/Source/NETworkManager/Views/Controls/ProfileExpanderPanel.xaml b/Source/NETworkManager/Views/Controls/ProfileExpanderPanel.xaml index 589470a610..e84d6dca5a 100644 --- a/Source/NETworkManager/Views/Controls/ProfileExpanderPanel.xaml +++ b/Source/NETworkManager/Views/Controls/ProfileExpanderPanel.xaml @@ -85,7 +85,7 @@ @@ -252,7 +252,7 @@ - + @@ -77,6 +160,7 @@ + @@ -200,7 +284,153 @@ Visibility="{Binding Path=IsStatusMessageDisplayed, Converter={StaticResource ResourceKey=BooleanToVisibilityCollapsedConverter}}" Margin="0,10,0,0" /> - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + @@ -231,82 +466,94 @@ Style="{StaticResource ResourceKey=DefaultTextBlock}" FontSize="16" FontWeight="SemiBold" VerticalAlignment="Center" /> + - + Orientation="Horizontal" + VerticalAlignment="Center"> + - + - - + + + - + Style="{StaticResource ResourceKey=DefaultTextBlock}" + Foreground="{DynamicResource ResourceKey=MahApps.Brushes.Gray5}" + Margin="6,0,6,0" /> + + - + - - + + + - + Style="{StaticResource ResourceKey=DefaultTextBlock}" + Foreground="{DynamicResource ResourceKey=MahApps.Brushes.Gray5}" + Margin="6,0,6,0" /> + + - + - - + + + - - + + + + + + - + + + - + @@ -393,16 +599,59 @@ - + + + diff --git a/Source/NETworkManager/Views/PingMonitorHostView.xaml.cs b/Source/NETworkManager/Views/PingMonitorHostView.xaml.cs index fcc4350ddd..da1b5347f3 100644 --- a/Source/NETworkManager/Views/PingMonitorHostView.xaml.cs +++ b/Source/NETworkManager/Views/PingMonitorHostView.xaml.cs @@ -33,15 +33,39 @@ public void OnViewVisible() } /// - /// Opens the group actions context menu on a normal click (not just right-click), so it + /// Opens the actions context menu (all hosts / group) on a normal click (not just right-click), so it /// works the same way for mouse, touch and keyboard activation. PlacementTarget is set /// explicitly since it isn't populated automatically when opening the menu this way, and /// the menu items rely on it to reach the group name (see Button.Tag in the XAML). /// - private void GroupActionsButton_Click(object sender, RoutedEventArgs e) + private void ActionsButton_Click(object sender, RoutedEventArgs e) { var button = (Button)sender; button.ContextMenu.PlacementTarget = button; button.ContextMenu.IsOpen = true; } + + /// + /// Restores the state of a group (expanded / collapsed by the user): the group containers are created again when + /// the hosts are filtered. + /// + private void GroupExpander_Loaded(object sender, RoutedEventArgs e) + { + if (sender is Expander { Tag: { } group } expander) + expander.IsExpanded = _viewModel.IsGroupExpanded(group.ToString()); + } + + private void GroupExpander_Expanded(object sender, RoutedEventArgs e) + { + // Only the group itself, not the expander of a host inside it (routed event) + if (ReferenceEquals(e.OriginalSource, sender) && sender is Expander { Tag: { } group }) + _viewModel.SetGroupExpanded(group.ToString(), true); + } + + private void GroupExpander_Collapsed(object sender, RoutedEventArgs e) + { + if (ReferenceEquals(e.OriginalSource, sender) && sender is Expander { Tag: { } group }) + _viewModel.SetGroupExpanded(group.ToString(), false); + } + } diff --git a/Source/NETworkManager/Views/PingMonitorSettingsView.xaml b/Source/NETworkManager/Views/PingMonitorSettingsView.xaml index 8e0a388a1e..4578ea4b25 100644 --- a/Source/NETworkManager/Views/PingMonitorSettingsView.xaml +++ b/Source/NETworkManager/Views/PingMonitorSettingsView.xaml @@ -29,6 +29,19 @@ + + + + + +