-
Notifications
You must be signed in to change notification settings - Fork 8
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
fix: recreate AMQP connection when dropped #605
Merged
Merged
Changes from 9 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
3e16405
fix: recreate AMQP connection when dropped
aneojgurhem 4b8d4e6
refactor: use async function
aneojgurhem 0e4fca2
refactor: release instead of requeue in AMQP plugin
aneojgurhem 645707d
refactor: lambda not needed
aneojgurhem 1da81f7
refactor: use singleizer for connection creation
aneojgurhem c9d4406
refactor: remove unneeded AsyncLazy and simplify code
aneojgurhem 749eef3
refactor: remove isInitialized because tests on connections are enough
aneojgurhem 59904ef
refactor: simplify init
aneojgurhem ea099c0
refactor: better toctou management in connection creation
aneojgurhem 195d195
refactor: directly create Singleizer
aneojgurhem File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -37,50 +37,74 @@ namespace ArmoniK.Core.Adapters.Amqp; | |
[UsedImplicitly] | ||
public class ConnectionAmqp : IConnectionAmqp | ||
{ | ||
private readonly AsyncLazy connectionTask_; | ||
private readonly ILogger<ConnectionAmqp> logger_; | ||
private readonly QueueCommon.Amqp options_; | ||
private bool isInitialized_; | ||
private readonly ExecutionSingleizer<Connection> connectionSingleizer_; | ||
private readonly ILogger<ConnectionAmqp> logger_; | ||
private readonly QueueCommon.Amqp options_; | ||
private Connection? connection_; | ||
|
||
public ConnectionAmqp(QueueCommon.Amqp options, | ||
ILogger<ConnectionAmqp> logger) | ||
{ | ||
options_ = options; | ||
logger_ = logger; | ||
connectionTask_ = new AsyncLazy(() => InitTask(this)); | ||
options_ = options; | ||
logger_ = logger; | ||
connectionSingleizer_ = new ExecutionSingleizer<Connection>(); | ||
} | ||
|
||
public Connection? Connection { get; private set; } | ||
|
||
public Task<HealthCheckResult> Check(HealthCheckTag tag) | ||
=> tag switch | ||
{ | ||
HealthCheckTag.Startup or HealthCheckTag.Readiness => Task.FromResult(isInitialized_ | ||
HealthCheckTag.Startup or HealthCheckTag.Readiness => Task.FromResult(connection_ is not null | ||
? HealthCheckResult.Healthy() | ||
: HealthCheckResult.Unhealthy($"{nameof(ConnectionAmqp)} is not yet initialized.")), | ||
HealthCheckTag.Liveness => Task.FromResult(isInitialized_ && Connection is not null && Connection.ConnectionState == ConnectionState.Opened | ||
HealthCheckTag.Liveness => Task.FromResult(connection_ is not null && connection_.ConnectionState == ConnectionState.Opened | ||
? HealthCheckResult.Healthy() | ||
: HealthCheckResult.Unhealthy($"{nameof(ConnectionAmqp)} not initialized or connection dropped.")), | ||
_ => throw new ArgumentOutOfRangeException(nameof(tag), | ||
tag, | ||
null), | ||
}; | ||
|
||
public async Task Init(CancellationToken cancellationToken = default) | ||
=> await connectionTask_; | ||
public Task Init(CancellationToken cancellationToken = default) | ||
=> GetConnectionAsync(cancellationToken); | ||
|
||
private static async Task InitTask(ConnectionAmqp conn, | ||
CancellationToken cancellationToken = default) | ||
public async Task<Connection> GetConnectionAsync(CancellationToken cancellationToken = default) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You can remove "async" if you return the Task from the ExecutionSingleizer directly. |
||
{ | ||
conn.logger_.LogInformation("Get address for session"); | ||
var address = new Address(conn.options_.Host, | ||
conn.options_.Port, | ||
conn.options_.User, | ||
conn.options_.Password, | ||
scheme: conn.options_.Scheme); | ||
if (connection_ is not null && !connection_.IsClosed) | ||
{ | ||
return connection_; | ||
} | ||
|
||
return await connectionSingleizer_.Call(async token => | ||
{ | ||
// this is needed to resolve TOCTOU problem | ||
if (connection_ is not null && !connection_.IsClosed) | ||
{ | ||
return connection_; | ||
} | ||
|
||
var conn = await CreateConnection(options_, | ||
logger_, | ||
token) | ||
.ConfigureAwait(false); | ||
connection_ = conn; | ||
return conn; | ||
}, | ||
cancellationToken) | ||
.ConfigureAwait(false); | ||
} | ||
|
||
private static async Task<Connection> CreateConnection(QueueCommon.Amqp options, | ||
ILogger logger, | ||
CancellationToken cancellationToken = default) | ||
{ | ||
var address = new Address(options.Host, | ||
options.Port, | ||
options.User, | ||
options.Password, | ||
scheme: options.Scheme); | ||
|
||
var connectionFactory = new ConnectionFactory(); | ||
if (conn.options_.Scheme.Equals("AMQPS")) | ||
if (options.Scheme.Equals("AMQPS")) | ||
{ | ||
connectionFactory.SSL.RemoteCertificateValidationCallback = delegate(object _, | ||
X509Certificate? _, | ||
|
@@ -89,45 +113,41 @@ private static async Task InitTask(ConnectionAmqp conn, | |
{ | ||
switch (errors) | ||
{ | ||
case SslPolicyErrors.RemoteCertificateNameMismatch when conn.options_.AllowHostMismatch: | ||
case SslPolicyErrors.RemoteCertificateNameMismatch when options.AllowHostMismatch: | ||
case SslPolicyErrors.None: | ||
return true; | ||
default: | ||
conn.logger_.LogError("SSL error : {error}", | ||
errors); | ||
logger.LogError("SSL error : {error}", | ||
errors); | ||
return false; | ||
} | ||
}; | ||
} | ||
|
||
var retry = 0; | ||
for (; retry < conn.options_.MaxRetries; retry++) | ||
for (; retry < options.MaxRetries; retry++) | ||
{ | ||
try | ||
{ | ||
conn.Connection = await connectionFactory.CreateAsync(address) | ||
.ConfigureAwait(false); | ||
conn.Connection.AddClosedCallback((_, | ||
e) => OnCloseConnection(e, | ||
conn.logger_)); | ||
break; | ||
var connection = await connectionFactory.CreateAsync(address) | ||
.ConfigureAwait(false); | ||
connection.AddClosedCallback((_, | ||
e) => OnCloseConnection(e, | ||
logger)); | ||
|
||
return connection; | ||
} | ||
catch (Exception ex) | ||
{ | ||
conn.logger_.LogInformation(ex, | ||
"Retrying to create connection"); | ||
logger.LogInformation(ex, | ||
"Retrying to create connection"); | ||
await Task.Delay(1000 * retry, | ||
cancellationToken) | ||
.ConfigureAwait(false); | ||
} | ||
} | ||
|
||
if (retry == conn.options_.MaxRetries) | ||
{ | ||
throw new TimeoutException($"{nameof(conn.options_.MaxRetries)} reached"); | ||
} | ||
|
||
conn.isInitialized_ = true; | ||
throw new TimeoutException($"{nameof(options.MaxRetries)} reached"); | ||
} | ||
|
||
private static void OnCloseConnection(Error? error, | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.