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

Adds .NET distributed tracing instrumentation & metrics. #1200

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
18 changes: 18 additions & 0 deletions src/FirebirdSql.Data.FirebirdClient.Tests/FbTransactionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,22 @@ public async Task SnapshotAtNumber()
}
}
}

[Test]
public async Task CanGetTransactionId()
{
if (!EnsureServerVersionAtLeast(new Version(2, 5, 0, 0)))
return;

await using (var transaction1 = await Connection.BeginTransactionAsync())
{
var idFromInfo = await new FbTransactionInfo(transaction1).GetTransactionIdAsync();
Assert.NotZero(idFromInfo);

var command = new FbCommand("SELECT current_transaction FROM rdb$database", Connection, transaction1);
var idFromSql = await command.ExecuteScalarAsync();

Assert.AreEqual(idFromInfo, idFromSql);
}
}
}
4 changes: 4 additions & 0 deletions src/FirebirdSql.Data.FirebirdClient/Common/IscHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,10 @@ public static List<object> ParseTransactionInfo(byte[] buffer, Charset charset)
case IscCodes.isc_info_error:
throw FbException.Create("Received error response.");

case IscCodes.isc_info_tra_id:
info.Add(VaxInteger(buffer, pos, length));
break;

case IscCodes.fb_info_tra_snapshot_number:
info.Add(VaxInteger(buffer, pos, length));
break;
Expand Down
133 changes: 97 additions & 36 deletions src/FirebirdSql.Data.FirebirdClient/FirebirdClient/FbCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,14 @@
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FirebirdSql.Data.Common;
using FirebirdSql.Data.Logging;
using FirebirdSql.Data.Metrics;
using FirebirdSql.Data.Trace;

namespace FirebirdSql.Data.FirebirdClient;

Expand All @@ -49,6 +52,8 @@ public sealed class FbCommand : DbCommand, IFbPreparedCommand, IDescriptorFiller
private int? _commandTimeout;
private int _fetchSize;
private Type[] _expectedColumnTypes;
private Activity _currentActivity;
private long _startedAtTicks;

#endregion

Expand Down Expand Up @@ -1094,7 +1099,10 @@ internal void Release()
_statement.Dispose2();
_statement = null;
}

TraceCommandStop();
}

Task IFbPreparedCommand.ReleaseAsync(CancellationToken cancellationToken) => ReleaseAsync(cancellationToken);
internal async Task ReleaseAsync(CancellationToken cancellationToken = default)
{
Expand All @@ -1112,6 +1120,8 @@ internal async Task ReleaseAsync(CancellationToken cancellationToken = default)
await _statement.Dispose2Async(cancellationToken).ConfigureAwait(false);
_statement = null;
}

TraceCommandStop();
}

void IFbPreparedCommand.TransactionCompleted() => TransactionCompleted();
Expand Down Expand Up @@ -1332,6 +1342,41 @@ private async ValueTask UpdateParameterValuesAsync(Descriptor descriptor, Cancel

#endregion

#region Tracing

private void TraceCommandStart()
{
Debug.Assert(_currentActivity == null);
if (FbActivitySource.Source.HasListeners())
_currentActivity = FbActivitySource.CommandStart(this);

_startedAtTicks = FbMetricsStore.CommandStart();
}

private void TraceCommandStop()
{
if (_currentActivity != null)
{
// Do not set status to Ok: https://opentelemetry.io/docs/concepts/signals/traces/#span-status
_currentActivity.Dispose();
_currentActivity = null;
}

FbMetricsStore.CommandStop(_startedAtTicks, Connection);
_startedAtTicks = 0;
}

private void TraceCommandException(Exception e)
{
if (_currentActivity != null)
{
FbActivitySource.CommandException(_currentActivity, e);
_currentActivity = null;
}
}

#endregion Tracing

#region Private Methods

private void Prepare(bool returnsSet)
Expand Down Expand Up @@ -1476,57 +1521,73 @@ private async Task PrepareAsync(bool returnsSet, CancellationToken cancellationT
private void ExecuteCommand(CommandBehavior behavior, bool returnsSet)
{
LogMessages.CommandExecution(Log, this);
TraceCommandStart();
try
{
Prepare(returnsSet);

Prepare(returnsSet);
if ((behavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess ||
(behavior & CommandBehavior.SingleResult) == CommandBehavior.SingleResult ||
(behavior & CommandBehavior.SingleRow) == CommandBehavior.SingleRow ||
(behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection ||
behavior == CommandBehavior.Default)
{
// Set the fetch size
_statement.FetchSize = _fetchSize;

if ((behavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess ||
(behavior & CommandBehavior.SingleResult) == CommandBehavior.SingleResult ||
(behavior & CommandBehavior.SingleRow) == CommandBehavior.SingleRow ||
(behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection ||
behavior == CommandBehavior.Default)
{
// Set the fetch size
_statement.FetchSize = _fetchSize;
// Set if it's needed the Records Affected information
_statement.ReturnRecordsAffected = _connection.ConnectionOptions.ReturnRecordsAffected;

// Set if it's needed the Records Affected information
_statement.ReturnRecordsAffected = _connection.ConnectionOptions.ReturnRecordsAffected;
// Validate input parameter count
if (_namedParameters.Count > 0 && !HasParameters)
{
throw FbException.Create("Must declare command parameters.");
}

// Validate input parameter count
if (_namedParameters.Count > 0 && !HasParameters)
{
throw FbException.Create("Must declare command parameters.");
// Execute
_statement.Execute(CommandTimeout * 1000, this);
}

// Execute
_statement.Execute(CommandTimeout * 1000, this);
}
catch (Exception e)
{
TraceCommandException(e);
throw;
}
}
private async Task ExecuteCommandAsync(CommandBehavior behavior, bool returnsSet, CancellationToken cancellationToken = default)
{
LogMessages.CommandExecution(Log, this);
TraceCommandStart();
try
{
await PrepareAsync(returnsSet, cancellationToken).ConfigureAwait(false);

await PrepareAsync(returnsSet, cancellationToken).ConfigureAwait(false);
if ((behavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess ||
(behavior & CommandBehavior.SingleResult) == CommandBehavior.SingleResult ||
(behavior & CommandBehavior.SingleRow) == CommandBehavior.SingleRow ||
(behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection ||
behavior == CommandBehavior.Default)
{
// Set the fetch size
_statement.FetchSize = _fetchSize;

if ((behavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess ||
(behavior & CommandBehavior.SingleResult) == CommandBehavior.SingleResult ||
(behavior & CommandBehavior.SingleRow) == CommandBehavior.SingleRow ||
(behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection ||
behavior == CommandBehavior.Default)
{
// Set the fetch size
_statement.FetchSize = _fetchSize;
// Set if it's needed the Records Affected information
_statement.ReturnRecordsAffected = _connection.ConnectionOptions.ReturnRecordsAffected;

// Set if it's needed the Records Affected information
_statement.ReturnRecordsAffected = _connection.ConnectionOptions.ReturnRecordsAffected;
// Validate input parameter count
if (_namedParameters.Count > 0 && !HasParameters)
{
throw FbException.Create("Must declare command parameters.");
}

// Validate input parameter count
if (_namedParameters.Count > 0 && !HasParameters)
{
throw FbException.Create("Must declare command parameters.");
// Execute
await _statement.ExecuteAsync(CommandTimeout * 1000, this, cancellationToken).ConfigureAwait(false);
}

// Execute
await _statement.ExecuteAsync(CommandTimeout * 1000, this, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
TraceCommandException(e);
throw;
}
}

Expand Down
15 changes: 15 additions & 0 deletions src/FirebirdSql.Data.FirebirdClient/FirebirdClient/FbConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@
//$Authors = Carlos Guzman Alvarez, Jiri Cincura ([email protected])

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using FirebirdSql.Data.Common;
using FirebirdSql.Data.Logging;
using FirebirdSql.Data.Metrics;

namespace FirebirdSql.Data.FirebirdClient;

Expand Down Expand Up @@ -189,6 +191,12 @@ public override string ConnectionString
_options = new ConnectionString(value);
_options.Validate();
_connectionString = value;

MetricsConnectionAttributes = [
new("db.system", "firebird"),
new("db.namespace", _options.Database),
new("server.address", $"{_options.DataSource}:{_options.Port}")
];
}
}
}
Expand Down Expand Up @@ -269,6 +277,8 @@ internal bool IsClosed
get { return _state == ConnectionState.Closed; }
}

internal KeyValuePair<string, object>[] MetricsConnectionAttributes;

#endregion

#region Protected Properties
Expand Down Expand Up @@ -553,6 +563,7 @@ public override async Task ChangeDatabaseAsync(string databaseName, Cancellation
public override void Open()
{
LogMessages.ConnectionOpening(Log, this);
var startedAtTicks = FbMetricsStore.ConnectionOpening();

if (string.IsNullOrEmpty(_connectionString))
{
Expand Down Expand Up @@ -645,10 +656,13 @@ public override void Open()
}

LogMessages.ConnectionOpened(Log, this);
FbMetricsStore.ConnectionOpened(startedAtTicks, this._options.NormalizedConnectionString);
}

public override async Task OpenAsync(CancellationToken cancellationToken)
{
LogMessages.ConnectionOpening(Log, this);
var startedAtTicks = FbMetricsStore.ConnectionOpening();

if (string.IsNullOrEmpty(_connectionString))
{
Expand Down Expand Up @@ -741,6 +755,7 @@ public override async Task OpenAsync(CancellationToken cancellationToken)
}

LogMessages.ConnectionOpened(Log, this);
FbMetricsStore.ConnectionOpened(startedAtTicks, this._options.NormalizedConnectionString);
}

public override void Close()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,10 @@ static long GetTicks()
var ticks = Environment.TickCount;
return ticks + -(long)int.MinValue;
}

internal int AvailableCount => _available.Count;
internal int BusyCount => _busy.Count;
internal int MaxSize => _connectionString.MaxPoolSize;
}

int _disposed;
Expand Down Expand Up @@ -220,6 +224,12 @@ internal void ClearPool(ConnectionString connectionString)
}
}

internal Dictionary<string, (int idleCount, int busyCount, int maxSize)> GetMetrics() =>
_pools.ToDictionary(
kvp => kvp.Key,
kvp => (kvp.Value.AvailableCount, kvp.Value.BusyCount, kvp.Value.MaxSize)
);

public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@ public sealed class FbTransactionInfo

#region Methods

public long GetTransactionId()
{
return GetValue<long>(IscCodes.isc_info_tra_id);
}
public Task<long> GetTransactionIdAsync(CancellationToken cancellationToken = default)
{
return GetValueAsync<long>(IscCodes.isc_info_tra_id, cancellationToken);
}

public long GetTransactionSnapshotNumber()
{
return GetValue<long>(IscCodes.fb_info_tra_snapshot_number);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="8.0.1" />
</ItemGroup>
<ItemGroup>
<Compile Update="FirebirdClient\FbBatchCommand.cs" />
Expand Down
Loading