Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add System.Net.NameResolution metrics #88773

Merged
merged 5 commits into from
Jul 15, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<Compile Include="System\Net\Dns.cs" />
<Compile Include="System\Net\IPHostEntry.cs" />
<Compile Include="System\Net\NetEventSource.NameResolution.cs" />
<Compile Include="System\Net\NameResolutionMetrics.cs" />
<Compile Include="System\Net\NameResolutionTelemetry.cs" />
<!-- Logging -->
<Compile Include="$(CommonPath)System\Net\Logging\NetEventSource.Common.cs"
Expand Down Expand Up @@ -102,6 +103,7 @@
<ItemGroup>
<Reference Include="Microsoft.Win32.Primitives" />
<Reference Include="System.Collections" />
<Reference Include="System.Diagnostics.DiagnosticSource" />
<Reference Include="System.Diagnostics.Tracing" />
<Reference Include="System.Memory" />
<Reference Include="System.Net.Primitives" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -535,12 +535,11 @@ private static Task GetHostEntryOrAddressesCoreAsync(string hostName, bool justR
ValidateHostName(hostName);

Task? t;
if (NameResolutionTelemetry.Log.IsEnabled())
if (NameResolutionTelemetry.Log.IsEnabled() || NameResolutionMetrics.IsEnabled())
{
t = justAddresses
? GetAddrInfoWithTelemetryAsync<IPAddress[]>(hostName, justAddresses, family, cancellationToken)
: GetAddrInfoWithTelemetryAsync<IPHostEntry>(hostName, justAddresses, family, cancellationToken);

}
else
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Net.Sockets;

namespace System.Net
{
internal static class NameResolutionMetrics
{
private static readonly Meter s_meter = new("System.Net.NameResolution");

private static readonly Counter<long> s_lookupsRequestedCounter = s_meter.CreateCounter<long>(
name: "dns-lookups-requested",
Copy link
Member

@antonfirsov antonfirsov Jul 12, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/cc @noahfalk to figure out the naming, since this is establishing a precedent. Should it be dns.lookups.requested?

(The instruments in my pr are to be renamed.)

description: "Number of DNS lookups requested.");

public static bool IsEnabled() => s_lookupsRequestedCounter.Enabled;

public static void BeforeResolution(object hostNameOrAddress, out string? host)
{
if (s_lookupsRequestedCounter.Enabled)
{
host = GetHostnameFromStateObject(hostNameOrAddress);

s_lookupsRequestedCounter.Add(1, KeyValuePair.Create("hostname", (object?)host));
}
else
{
host = null;
}
}

public static string GetHostnameFromStateObject(object hostNameOrAddress)
{
Debug.Assert(hostNameOrAddress is not null);

string host = hostNameOrAddress switch
{
string h => h,
KeyValuePair<string, AddressFamily> t => t.Key,
IPAddress a => a.ToString(),
KeyValuePair<IPAddress, AddressFamily> t => t.Key.ToString(),
_ => null!
};

Debug.Assert(host is not null, $"Unknown hostNameOrAddress type: {hostNameOrAddress.GetType().Name}");

return host;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Net.Sockets;
using System.Threading;

namespace System.Net
Expand Down Expand Up @@ -62,29 +60,19 @@ protected override void OnEventCommand(EventCommandEventArgs command)
[NonEvent]
public long BeforeResolution(object hostNameOrAddress)
{
Debug.Assert(hostNameOrAddress != null);
Debug.Assert(
hostNameOrAddress is string ||
hostNameOrAddress is IPAddress ||
hostNameOrAddress is KeyValuePair<string, AddressFamily> ||
hostNameOrAddress is KeyValuePair<IPAddress, AddressFamily>,
$"Unknown hostNameOrAddress type: {hostNameOrAddress.GetType().Name}");
// System.Diagnostics.Metrics part
NameResolutionMetrics.BeforeResolution(hostNameOrAddress, out string? host);

// System.Diagnostics.Tracing part
if (IsEnabled())
{
Interlocked.Increment(ref _lookupsRequested);
Interlocked.Increment(ref _currentLookups);

if (IsEnabled(EventLevel.Informational, EventKeywords.None))
{
string host = hostNameOrAddress switch
{
string h => h,
KeyValuePair<string, AddressFamily> t => t.Key,
IPAddress a => a.ToString(),
KeyValuePair<IPAddress, AddressFamily> t => t.Key.ToString(),
_ => null!
};
host ??= NameResolutionMetrics.GetHostnameFromStateObject(hostNameOrAddress);

ResolutionStart(host);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Generic;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Net.Sockets;
using System.Threading.Tasks;
using Xunit;

namespace System.Net.NameResolution.Tests
{
public class MetricsTest
{
private const string DnsLookupsRequested = "dns-lookups-requested";

[Fact]
public static async Task ResolveValidHostName_MetricsRecorded()
{
const string ValidHostName = "localhost";

using var recorder = new InstrumentRecorder<long>(DnsLookupsRequested);

await Dns.GetHostEntryAsync(ValidHostName);
await Dns.GetHostAddressesAsync(ValidHostName);

Dns.GetHostEntry(ValidHostName);
Dns.GetHostAddresses(ValidHostName);

Dns.EndGetHostEntry(Dns.BeginGetHostEntry(ValidHostName, null, null));
Dns.EndGetHostAddresses(Dns.BeginGetHostAddresses(ValidHostName, null, null));

long[] measurements = GetMeasurementsForHostname(recorder, ValidHostName);

// >= 6 because other tests running in parallel may have also resolved the same host.
MihaZupan marked this conversation as resolved.
Show resolved Hide resolved
Assert.True(measurements.Length >= 6, $"Was {measurements.Length}");
Assert.All(measurements, m => Assert.Equal(1, m));
}

[Fact]
public static async Task ResolveInvalidHostName_MetricsRecorded()
{
const string InvalidHostName = $"invalid...example.com...{nameof(ResolveInvalidHostName_MetricsRecorded)}";

using var recorder = new InstrumentRecorder<long>(DnsLookupsRequested);

await Assert.ThrowsAnyAsync<SocketException>(async () => await Dns.GetHostEntryAsync(InvalidHostName));
await Assert.ThrowsAnyAsync<SocketException>(async () => await Dns.GetHostAddressesAsync(InvalidHostName));

Assert.ThrowsAny<SocketException>(() => Dns.GetHostEntry(InvalidHostName));
Assert.ThrowsAny<SocketException>(() => Dns.GetHostAddresses(InvalidHostName));

Assert.ThrowsAny<SocketException>(() => Dns.EndGetHostEntry(Dns.BeginGetHostEntry(InvalidHostName, null, null)));
Assert.ThrowsAny<SocketException>(() => Dns.EndGetHostAddresses(Dns.BeginGetHostAddresses(InvalidHostName, null, null)));

long[] measurements = GetMeasurementsForHostname(recorder, InvalidHostName);

Assert.Equal(6, measurements.Length);
Assert.All(measurements, m => Assert.Equal(1, m));
}

private static long[] GetMeasurementsForHostname(InstrumentRecorder<long> recorder, string hostname)
{
return recorder
.GetMeasurements()
.Where(m => m.Tags.ToArray().Any(t => t.Key == "hostname" && t.Value is string hostnameTag && hostnameTag == hostname))
.Select(m => m.Value)
.ToArray();
}

private sealed class InstrumentRecorder<T> : IDisposable where T : struct
{
private readonly MeterListener _meterListener = new();
private readonly List<Measurement<T>> _values = new();

public InstrumentRecorder(string instrumentName)
{
_meterListener.InstrumentPublished = (instrument, listener) =>
{
if (instrument.Meter.Name == "System.Net.NameResolution" && instrument.Name == instrumentName)
{
listener.EnableMeasurementEvents(instrument);
}
};
_meterListener.SetMeasurementEventCallback<T>(OnMeasurementRecorded);
_meterListener.Start();
}

private void OnMeasurementRecorded(Instrument instrument, T measurement, ReadOnlySpan<KeyValuePair<string, object?>> tags, object? state) => _values.Add(new Measurement<T>(measurement, tags));
public IReadOnlyList<Measurement<T>> GetMeasurements() => _values.ToArray();
public void Dispose() => _meterListener.Dispose();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<Compile Include="GetHostByAddressTest.cs" />
<Compile Include="GetHostByNameTest.cs" />
<Compile Include="ResolveTest.cs" />
<Compile Include="MetricsTest.cs" />
<Compile Include="GetHostNameTest.cs" />
<Compile Include="GetHostEntryTest.cs" />
<Compile Include="GetHostAddressesTest.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
using System.Net.Sockets;
using System.Threading.Tasks;
using Microsoft.DotNet.RemoteExecutor;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
using Xunit.Sdk;

namespace System.Net.NameResolution.Tests
{
Expand Down