Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
85 commits
Select commit Hold shift + click to select a range
44b7d65
POC
jamescrosswell Oct 9, 2024
157a4a9
Configurable level
jamescrosswell Oct 9, 2024
67a1c38
Changed dependency from net5.0 to net6.0
jamescrosswell Oct 9, 2024
4f8f917
Format code
getsentry-bot Oct 9, 2024
0d1aa2d
Update MemoryMonitor.cs
jamescrosswell Oct 9, 2024
5ceff11
Exclude on Android and iOS
jamescrosswell Oct 10, 2024
ae55ae9
Bundle dotnet-gcdump in the Sentry nuget package
jamescrosswell Oct 10, 2024
c5b75ad
Merge branch 'auto-heap-dump' of github.com:getsentry/sentry-dotnet i…
jamescrosswell Oct 10, 2024
60aeda0
Format code
getsentry-bot Oct 11, 2024
cc1a00e
Fixed Bindable tests
jamescrosswell Oct 11, 2024
b02fa28
Update CHANGELOG.md
jamescrosswell Oct 11, 2024
0625662
Merge branch 'auto-heap-dump' of github.com:getsentry/sentry-dotnet i…
jamescrosswell Oct 11, 2024
1d12b7c
Merge branch 'version-5.0.0' into auto-heap-dump
jamescrosswell Oct 11, 2024
ecfbce3
Update CHANGELOG.md
jamescrosswell Oct 11, 2024
1e6d29b
Tweaked the demos
jamescrosswell Oct 11, 2024
5b0f08e
Revert "Bundle dotnet-gcdump in the Sentry nuget package"
jamescrosswell Oct 13, 2024
ba4bcd9
Unbundled GCDump from NuGet package
jamescrosswell Oct 13, 2024
a357e9f
Switched to built in GC.RegisterForFullGCNotification events for garb…
jamescrosswell Oct 14, 2024
b6c3bff
Tweaked settings to expedite full GC in Heap Dump sample
jamescrosswell Oct 14, 2024
e36dfef
Added TryGetDumpLocation tests
jamescrosswell Oct 15, 2024
d35477b
Added CaptureMemoryDump tests
jamescrosswell Oct 15, 2024
4c0ccc8
Refactored MemoryMonitor to use triggers and debouncers
jamescrosswell Oct 15, 2024
ffad135
Format code
getsentry-bot Oct 15, 2024
265e397
Fixed tests
jamescrosswell Oct 15, 2024
7a3b109
Merge branch 'auto-heap-dump' of github.com:getsentry/sentry-dotnet i…
jamescrosswell Oct 15, 2024
da07de2
Format code
getsentry-bot Oct 15, 2024
975b9b1
Added CheckMemoryUsage tests
jamescrosswell Oct 15, 2024
38ad7bc
Fixed remaining BindableOptions tests
jamescrosswell Oct 15, 2024
ef3a33f
Merge branch 'auto-heap-dump' of github.com:getsentry/sentry-dotnet i…
jamescrosswell Oct 15, 2024
4b86619
Bundle dotnet-gcdump in Sentry.nupkg
jamescrosswell Oct 17, 2024
08c9db4
Use bundled version of gcdump if it is present
jamescrosswell Oct 17, 2024
169ef49
Delete buildlog.txt
jamescrosswell Oct 17, 2024
2e6a0f1
Review feedback
jamescrosswell Oct 23, 2024
87b76d8
Refactored error handling on garbage collection monitor to use a Cont…
jamescrosswell Oct 23, 2024
3f15073
Comment in Dispose
jamescrosswell Oct 23, 2024
2dfd4f4
Review feedback
jamescrosswell Oct 23, 2024
99af671
Use _options.FileSystem
jamescrosswell Oct 23, 2024
acf93ab
Type
jamescrosswell Oct 23, 2024
8708377
Merge branch 'version-5.0.0' into auto-heap-dump
jamescrosswell Oct 23, 2024
3b62d53
Merge branch 'auto-heap-dump' of github.com:getsentry/sentry-dotnet i…
jamescrosswell Oct 23, 2024
2a3d8b7
GCDump.props now downloads nuget directly, rather than installing dot…
jamescrosswell Oct 23, 2024
3eb2f73
Created separate demo and tweaked the API
jamescrosswell Oct 23, 2024
60f0b7e
Format code
getsentry-bot Oct 23, 2024
70486da
Typo in transitive build file
jamescrosswell Oct 23, 2024
d2755db
Merge branch 'auto-heap-dump' of github.com:getsentry/sentry-dotnet i…
jamescrosswell Oct 23, 2024
8133a63
Updated solution filters
jamescrosswell Oct 23, 2024
58d9e55
Reverted to Continuation to handle errors in the gc monitor
jamescrosswell Oct 23, 2024
7135767
Review feedback
jamescrosswell Oct 28, 2024
22760c8
Update SentrySdk.cs
jamescrosswell Oct 28, 2024
f371304
Update Directory.Build.props
jamescrosswell Oct 28, 2024
26c85b8
release: 14.12.1-dump1
getsentry-bot Oct 28, 2024
0142d29
Workaround issue in release action
jamescrosswell Oct 28, 2024
8a831fc
Revert "Workaround issue in release action"
jamescrosswell Oct 28, 2024
056ec48
Merge branch 'release/14.12.1-dump1' into auto-heap-dump
Oct 28, 2024
29058f1
Revert "Merge branch 'release/14.12.1-dump1' into auto-heap-dump"
jamescrosswell Oct 29, 2024
5469815
Review feedback
jamescrosswell Nov 4, 2024
f1c9e64
Merge branch 'version-5.0.0' into auto-heap-dump
jamescrosswell Nov 4, 2024
8a49c01
Update ApiApprovalTests.Run.DotNet9_0.verified.txt
jamescrosswell Nov 4, 2024
dbe9f60
Update action.yml
jamescrosswell Nov 4, 2024
be63db4
Revert "Update action.yml"
jamescrosswell Nov 4, 2024
36e4a2b
Update workaround for slow release builds for ios
jamescrosswell Nov 6, 2024
076e9f9
Removed async void unit tests
jamescrosswell Nov 6, 2024
506fba1
Drop net6.0 target from Sentry.Tests
jamescrosswell Nov 6, 2024
298f57c
Add diagnostic logging for Windows tests
jamescrosswell Nov 6, 2024
a234ef2
Update build.yml
jamescrosswell Nov 6, 2024
f4fba3a
Merge branch 'version-5.0.0' into auto-heap-dump
jamescrosswell Nov 7, 2024
4eafc16
Disabled diagnostics output on windows tests
jamescrosswell Nov 7, 2024
a09ffef
Update build.yml
jamescrosswell Nov 7, 2024
b8cffed
Use mock GC implementation for MemoryMonitorTests
jamescrosswell Nov 9, 2024
b216a3c
Update Sentry.Tests.csproj
jamescrosswell Nov 9, 2024
e1ba7c2
Try disabling heapdump tests on Windows in CI
jamescrosswell Nov 10, 2024
2c79a4a
Reverse skip condition
jamescrosswell Nov 10, 2024
72c90b5
Try re-enabling GarbageCollectionMonitorTests on Windows
jamescrosswell Nov 11, 2024
cadd0cf
Try reinstating MemoryMonitorTests (constructor test changed)
jamescrosswell Nov 11, 2024
84c436f
Update MemoryMonitor.cs
jamescrosswell Nov 11, 2024
3a9ba29
Refactored Constructor_NoHeapdumpsConfigured_Throws
jamescrosswell Nov 11, 2024
9fea039
Try re-enabling remaining MemoryMonitorTests
jamescrosswell Nov 11, 2024
845378c
Re-enable remaining MemoryMonitorTests
jamescrosswell Nov 11, 2024
4245a75
Unbundled dotnet-gcdump
jamescrosswell Nov 11, 2024
5865245
Disable CaptureMemoryDump and TryGetDumpLocation tests
jamescrosswell Nov 11, 2024
d9b9306
Re-enable CaptureMemoryDump tests
jamescrosswell Nov 11, 2024
13bfe6f
Disable CaptureMemoryDump and enable TryGetDumpLocation
jamescrosswell Nov 11, 2024
d330c2c
Fixed CaptureMemoryDump_CapturesDump
jamescrosswell Nov 11, 2024
8127bb5
Added remarks about dotnet-gcdump dependency to options
jamescrosswell Nov 11, 2024
e628bb3
Merge branch 'version-5.0.0' into auto-heap-dump
bruno-garcia Nov 16, 2024
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
Prev Previous commit
Next Next commit
Added TryGetDumpLocation tests
  • Loading branch information
jamescrosswell committed Oct 15, 2024
commit e36dfef4dc1d3d1a766d6d92fe4534e0d0ab3dab
10 changes: 5 additions & 5 deletions src/Sentry/Internal/GarbageCollectionMonitor.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
namespace Sentry.Internal;

/// <summary>
/// Simple class to determine when GarbageCollection occurs
/// Simple class to detect when Full Garbage Collection occurs
/// </summary>
internal sealed class GarbageCollectionMonitor(Action onGarbageCollected)
internal sealed class GarbageCollectionMonitor
{
private const int MaxGenerationThreshold = 10;
private const int LargeObjectHeapThreshold = 10;

public void Start(CancellationToken cancellationToken) =>
Task.Run(() => MonitorGarbageCollection(cancellationToken), cancellationToken);
public static void Start(Action onGarbageCollected, CancellationToken cancellationToken) =>
Task.Run(() => MonitorGarbageCollection(onGarbageCollected, cancellationToken), cancellationToken);

private void MonitorGarbageCollection(CancellationToken cancellationToken)
private static void MonitorGarbageCollection(Action onGarbageCollected, CancellationToken cancellationToken)
{
GC.RegisterForFullGCNotification(MaxGenerationThreshold, LargeObjectHeapThreshold);

Expand Down
6 changes: 5 additions & 1 deletion src/Sentry/Internal/Hub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ internal Hub(
#if NET6_0_OR_GREATER && !(IOS || ANDROID)
if (options.AutomaticHeapDumpMemoryThreshold is { } threshold)
{
_memoryMonitor = new MemoryMonitor(threshold, options, CaptureHeapDump);
_memoryMonitor = new MemoryMonitor(options, threshold, CaptureHeapDump);
}
#endif

Expand Down Expand Up @@ -692,6 +692,10 @@ public void Dispose()
return;
}

#if NET6_0_OR_GREATER && !(IOS || ANDROID)
_memoryMonitor?.Dispose();
#endif

try
{
CurrentClient.FlushAsync(_options.ShutdownTimeout).ConfigureAwait(false).GetAwaiter().GetResult();
Expand Down
38 changes: 21 additions & 17 deletions src/Sentry/Internal/MemoryMonitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,17 @@

namespace Sentry.Internal;

internal class MemoryMonitor
internal class MemoryMonitor : IDisposable
{
private readonly SentryOptions _options;
private readonly long _thresholdBytes;
private readonly long _totalMemory;
internal readonly long _thresholdBytes;
private bool _dumpTriggered;
private GarbageCollectionMonitor _gcMonitor;
CancellationTokenSource _cancellationTokenSource = new();
private readonly CancellationTokenSource _cancellationTokenSource = new();

private Action<string> OnDumpCollected { get; }

public MemoryMonitor(short thresholdPercentage, SentryOptions options, Action<string> onDumpCollected)
public MemoryMonitor(SentryOptions options, short thresholdPercentage, Action<string> onDumpCollected)
{
if (thresholdPercentage is < 0 or > 100)
{
Expand All @@ -37,8 +36,7 @@ public MemoryMonitor(short thresholdPercentage, SentryOptions options, Action<st
_thresholdBytes = (long)Math.Ceiling(portion * _totalMemory);
_options.LogInfo("Automatic heap dump enabled if memory usage exceeds {0:N0} bytes ({1}%)", _thresholdBytes, thresholdPercentage);

_gcMonitor = new GarbageCollectionMonitor(CheckMemoryUsage);
_gcMonitor.Start(_cancellationTokenSource.Token);
GarbageCollectionMonitor.Start(CheckMemoryUsage, _cancellationTokenSource.Token);
}

private void CheckMemoryUsage()
Expand All @@ -54,16 +52,22 @@ private void CheckMemoryUsage()
// Trigger the event if the threshold is exceeded
if (usedMemory > _thresholdBytes && !_dumpTriggered)
{
_dumpTriggered = true;
_options.LogDebug("Total Memory: {0:N0} bytes", _totalMemory);
_options.LogDebug("Threshold: {0:N0} bytes", _thresholdBytes);
_options.LogDebug("Memory used: {0:N0} bytes ({1:N2}%)", usedMemory, usedMemoryPercentage);
_dumpTriggered = true;
CaptureMemoryDump();
}
}

internal void CaptureMemoryDump()
{
if (_options.DisableFileWrite)
{
_options.LogDebug("File write has been disabled via the options. Unable to create memory dump.");
return;
}

var dumpFile = TryGetDumpLocation();
if (dumpFile is null)
{
Expand Down Expand Up @@ -102,14 +106,8 @@ internal void CaptureMemoryDump()
OnDumpCollected(dumpFile);
}

private string? TryGetDumpLocation()
internal string? TryGetDumpLocation()
{
if (_options.DisableFileWrite)
{
_options.LogDebug("File write has been disabled via the options. Unable to create memory dump.");
return null;
}

try
{
var rootPath = _options.CacheDirectoryPath ??
Expand All @@ -119,7 +117,7 @@ internal void CaptureMemoryDump()

if (!fileSystem.CreateDirectory(directoryPath))
{
_options.LogDebug("Failed to create a directory for memory dump ({0}).", directoryPath);
_options.LogWarning("Failed to create a directory for memory dump ({0}).", directoryPath);
return null;
}
_options.LogDebug("Created directory for heap dump ({0}).", directoryPath);
Expand All @@ -129,7 +127,8 @@ internal void CaptureMemoryDump()
var filePath = Path.Combine(directoryPath, $"{timestamp}_{processId}.gcdump");
if (fileSystem.FileExists(filePath))
{
fileSystem.DeleteFile(filePath);
_options.LogWarning("Duplicate dump file detected.");
return null;
}

return filePath;
Expand All @@ -141,6 +140,11 @@ internal void CaptureMemoryDump()
return null;
}
}

public void Dispose()
{
_cancellationTokenSource.Cancel();
}
}

#endif
46 changes: 46 additions & 0 deletions test/Sentry.Testing/SentryOptionsExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
namespace Sentry.Testing;

/// <summary>
/// We most frequently call IDiagnosticLogger via extension methods on the SentryOptions class, which obscures what
/// we're expecting to receive via mocks when writing tests. This class provides some test extensions that mirror the
/// extensions provided for SentryOptions to make it easier to write tests that match the code they're testing.
/// </summary>
public static class SentryOptionsExtensions
{
private static SentryOptions ReceivedLog(this SentryOptions substitute, SentryLevel level)
{
substitute.DiagnosticLogger.Received().Log(level, Arg.Any<string>(), null, Arg.Any<object[]>());
return substitute;
}

private static SentryOptions ReceivedLog(this SentryOptions substitute, SentryLevel level, string message, params object[] args)
{
substitute.DiagnosticLogger.Received().Log(level, message, null, args);
return substitute;
}

public static SentryOptions ReceivedLogInfo(this SentryOptions substitute)
=> ReceivedLog(substitute, SentryLevel.Info);

public static SentryOptions ReceivedLogInfo(this SentryOptions substitute, string message, params object[] args)
=> ReceivedLog(substitute, SentryLevel.Info, message, args);

public static SentryOptions ReceivedLogWarning(this SentryOptions substitute)
=> ReceivedLog(substitute, SentryLevel.Warning);

public static SentryOptions ReceivedLogWarning(this SentryOptions substitute, string message, params object[] args)
=> ReceivedLog(substitute, SentryLevel.Warning, message, args);

public static SentryOptions ReceivedLogError(this SentryOptions substitute)
=> ReceivedLogError(substitute, string.Empty);

public static SentryOptions ReceivedLogError(this SentryOptions substitute, string message, params object[] args)
=> ReceivedLog(substitute, SentryLevel.Error, message, args);

public static SentryOptions ReceivedLogError(this SentryOptions substitute, Exception exception, string message,
params object[] args)
{
substitute.DiagnosticLogger.Received().Log(SentryLevel.Error, message, exception, Arg.Any<object[]>());
return substitute;
}
}
93 changes: 93 additions & 0 deletions test/Sentry.Tests/Internals/MemoryMonitorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
#if NET6_0_OR_GREATER && !(IOS || ANDROID)
namespace Sentry.Tests.Internals;

public class MemoryMonitorTests
{
private class Fixture
{
public SentryOptions Options { get; set; } = new()
{
Dsn = ValidDsn,
Debug = true,
DiagnosticLogger = Substitute.For<IDiagnosticLogger>()
};
public Action<string> OnDumpCollected { get; set; } = _ => { };
public short ThresholdPercentage { get; set; } = 5;

public MemoryMonitor GetSut()
{
Options.DiagnosticLogger?.IsEnabled(Arg.Any<SentryLevel>()).Returns(true);
return new(Options, ThresholdPercentage, OnDumpCollected);
}
}

private readonly Fixture _fixture = new();

[Fact]
public void TryGetDumpLocation_DirectoryCreationFails_ReturnsNull()
{
// Arrange
_fixture.Options.FileSystem = Substitute.For<IFileSystem>();
_fixture.Options.FileSystem.CreateDirectory(Arg.Any<string>()).Returns(false);
using var sut = _fixture.GetSut();

// Act
var result = sut.TryGetDumpLocation();

// Assert
result.Should().BeNull();
_fixture.Options.FileSystem.Received().CreateDirectory(Arg.Any<string>());
_fixture.Options.FileSystem.DidNotReceive().FileExists(Arg.Any<string>());
_fixture.Options.ReceivedLogWarning("Failed to create a directory for memory dump ({0}).", Arg.Any<string>());
}

[Fact]
public void TryGetDumpLocation_DumpFileExists_ReturnsNull()
{
// Arrange
_fixture.Options.FileSystem = Substitute.For<IFileSystem>();
_fixture.Options.FileSystem.CreateDirectory(Arg.Any<string>()).Returns(true);
_fixture.Options.FileSystem.FileExists(Arg.Any<string>()).Returns(true);
using var sut = _fixture.GetSut();

// Act
var result = sut.TryGetDumpLocation();

// Assert
result.Should().BeNull();
_fixture.Options.FileSystem.Received().CreateDirectory(Arg.Any<string>());
_fixture.Options.FileSystem.Received().FileExists(Arg.Any<string>());
_fixture.Options.ReceivedLogWarning("Duplicate dump file detected.");
}

[Fact]
public void TryGetDumpLocation_Exception_LogsError()
{
// Arrange
_fixture.Options.FileSystem = Substitute.For<IFileSystem>();
_fixture.Options.FileSystem.CreateDirectory(Arg.Any<string>()).Throws(_ => new Exception());
using var sut = _fixture.GetSut();

// Act
var result = sut.TryGetDumpLocation();

// Assert
result.Should().BeNull();
_fixture.Options.ReceivedLogError(Arg.Any<Exception>(), "Failed to resolve appropriate memory dump location.");
}

[Fact]
public void TryGetDumpLocation_ReturnsFilePath()
{
// Arrange
_fixture.Options.FileSystem = new FakeFileSystem();
using var sut = _fixture.GetSut();

// Act
var result = sut.TryGetDumpLocation();

// Assert
result.Should().NotBeNull();
}
}
#endif