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

fix(client): Adding graceful shutdown to event loop #2164

Closed
wants to merge 26 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
9022e64
Adding graceful shutdown to event loop
jamdavi Sep 7, 2021
47e12c9
Merge branch 'master' into jamdavi/issue2163
abhipsaMisra Sep 15, 2021
78673e8
Adding transport graceful shutdown timeout
jamdavi Sep 16, 2021
a320560
Merge branch 'jamdavi/issue2163' of https://github.com/Azure/azure-io…
jamdavi Sep 16, 2021
943b667
Adding very short time to blanket test all E2E tests
jamdavi Sep 21, 2021
61739f3
Merge branch 'main' into jamdavi/issue2163
jamdavi Nov 2, 2021
ef19559
Make event loop a non-static member variable
jamdavi Nov 3, 2021
8ccf860
Making event loop non-static for the provisioning handler
jamdavi Nov 3, 2021
380c9dd
Revert "Setting close time back to one second"
jamdavi Nov 3, 2021
b816860
Merge branch 'jamdavi/issue2163' of https://github.com/Azure/azure-io…
jamdavi Nov 3, 2021
b6c5cb7
Adding E2E tests
jamdavi Nov 3, 2021
80ef9c6
Update e2e/test/iothub/MqttTransportHandlerShutdownTests.cs
jamdavi Nov 3, 2021
65b9e10
Merge branch 'main' into jamdavi/issue2163
jamdavi Nov 3, 2021
c5b4ffe
Adding arrange/act/assert comments
jamdavi Nov 3, 2021
407e47a
Adjusting short timeout value to be a bit more permissive
jamdavi Nov 3, 2021
f2e0dca
Update shutdown
jamdavi Nov 17, 2021
24211ce
Merge branch 'main' into jamdavi/issue2163
jamdavi Nov 22, 2021
3add574
Retain legacy singleton if needed.
jamdavi Nov 22, 2021
bef99b0
Whitespace
jamdavi Nov 22, 2021
0360b21
Fixing white space and comments
jamdavi Nov 22, 2021
6aa6e74
Fixing more comments
jamdavi Nov 22, 2021
95cac0d
Fixing more comments
jamdavi Nov 22, 2021
2cad8ec
Spelling
jamdavi Nov 22, 2021
97b0ca4
Changing logic of ref checking
jamdavi Nov 23, 2021
d864b7f
Add ability to await removal and ignore cert tests
jamdavi Nov 23, 2021
3e09b9c
Simplify reference counter and let the Shutdown() method take care of…
jamdavi Nov 29, 2021
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 @@ namespace Microsoft.Azure.Devices.E2ETests.Iothub.Service
{
[TestClass]
[TestCategory("InvalidServiceCertificate")]
[Ignore] // Removed due to invalid cert service being shut down
public class IoTHubCertificateValidationE2ETest : E2EMsTestBase
{
[LoggedTestMethod]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ namespace Microsoft.Azure.Devices.E2ETests.Provisioning
{
[TestClass]
[TestCategory("InvalidServiceCertificate")]
[Ignore] // Removed due to invalid cert service being shut down
public class ProvisioningCertificateValidationE2ETest : E2EMsTestBase
{
[LoggedTestMethod]
Expand Down
52 changes: 47 additions & 5 deletions iothub/device/src/Transport/Mqtt/MqttTransportHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,16 @@ internal sealed class MqttTransportHandler : TransportHandler, IMqttIotHubEventH
private const string ReceiveEventMessagePrefixPattern = "devices/{0}/modules/{1}/";

private static readonly int s_generationPrefixLength = Guid.NewGuid().ToString().Length;
private static readonly Lazy<IEventLoopGroup> s_eventLoopGroup = new Lazy<IEventLoopGroup>(GetEventLoopGroup);
private static readonly ReferenceCounter<IEventLoopGroup> _eventLoopGroupRefCounted = new ReferenceCounter<IEventLoopGroup>();
private static readonly TimeSpan s_regexTimeoutMilliseconds = TimeSpan.FromMilliseconds(500);
private static readonly TimeSpan s_defaultTwinTimeout = TimeSpan.FromSeconds(60);

// Recommended use of DotNetty is to use a single event loop group. In order to allow more flexibility we can let the caller decice if they want to
// use a single event loop group, or possibly use a group per instance of the client.
private readonly bool _useSingleEventLoopGroup;
private readonly IEventLoopGroup _eventLoopGroup;
private readonly TimeSpan _timeoutValueForEventLoop = TimeSpan.Zero;
jamdavi marked this conversation as resolved.
Show resolved Hide resolved

private readonly string _generationId = Guid.NewGuid().ToString();
private readonly string _receiveEventMessageFilter;
private readonly string _receiveEventMessagePrefix;
Expand Down Expand Up @@ -178,6 +184,20 @@ internal MqttTransportHandler(

_webProxy = settings.Proxy;

// If the customer chooses multiple groups we need to honor that here.
_useSingleEventLoopGroup = settings.UseSingleEventLoopGroup;

_timeoutValueForEventLoop = settings.GracefulEventLoopShutdownTimeout;

if (_useSingleEventLoopGroup)
{
_eventLoopGroup = _eventLoopGroupRefCounted.Create(GetEventLoopGroup);
}
else
{
_eventLoopGroup = GetEventLoopGroup();
}

if (channelFactory != null)
{
_channelFactory = channelFactory;
Expand Down Expand Up @@ -476,9 +496,15 @@ protected override void Dispose(bool disposing)
disposableChannel.Dispose();
_channel = null;
}

}
}

/// <summary>
/// Closes the MqttTransport
/// </summary>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>An awaitable task</returns>
public override async Task CloseAsync(CancellationToken cancellationToken)
{
try
Expand All @@ -491,7 +517,6 @@ public override async Task CloseAsync(CancellationToken cancellationToken)
if (TryStop())
{
OnTransportClosedGracefully();

await _closeRetryPolicy.ExecuteAsync(CleanUpImplAsync, cancellationToken).ConfigureAwait(true);
}
else if (State == TransportState.Error)
Expand All @@ -506,6 +531,21 @@ public override async Task CloseAsync(CancellationToken cancellationToken)
}
}

/// <summary>
/// Internal implementation of the close logic that can be reused in Dispose()
/// </summary>
/// <returns></returns>
private Task ShutdownEventLoopGroupInternal()
{
// If the customer chooses multiple groups we need to honor that here.
// The remove method will only return an object if the reference count is zero or if there is no value for the object
if (_useSingleEventLoopGroup && _eventLoopGroupRefCounted.Remove() == null)
{
return TaskHelpers.CompletedTask;
}
return _eventLoopGroup?.ShutdownGracefullyAsync(_timeoutValueForEventLoop, _timeoutValueForEventLoop);
}

#endregion Client operations

#region MQTT callbacks
Expand Down Expand Up @@ -1037,6 +1077,8 @@ private async Task OpenInternalAsync(CancellationToken cancellationToken)
{
await _channel.CloseAsync().ConfigureAwait(true);
}

await ShutdownEventLoopGroupInternal();
});
}

Expand Down Expand Up @@ -1209,7 +1251,7 @@ private Func<IPAddress[], int, Task<IChannel>> CreateChannelFactory(IotHubConnec
iotHubConnectionString.HostName);

Bootstrap bootstrap = new Bootstrap()
.Group(s_eventLoopGroup.Value)
.Group(_eventLoopGroup)
.Channel<TcpSocketChannel>()
.Option(ChannelOption.TcpNodelay, true)
.Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
Expand Down Expand Up @@ -1319,7 +1361,7 @@ private Func<IPAddress[], int, Task<IChannel>> CreateWebSocketChannelFactory(Iot
new LoggingHandler(LogLevel.DEBUG),
_mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings, productInfo, options));

await s_eventLoopGroup.Value.RegisterAsync(clientWebSocketChannel).ConfigureAwait(true);
await _eventLoopGroup.RegisterAsync(clientWebSocketChannel).ConfigureAwait(true);

return clientWebSocketChannel;
};
Expand Down Expand Up @@ -1420,4 +1462,4 @@ private bool IsProxyConfigured()
&& _webProxy != DefaultWebProxySettings.Instance;
}
}
}
}
16 changes: 16 additions & 0 deletions iothub/device/src/Transport/Mqtt/MqttTransportSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -250,5 +250,21 @@ public TransportType GetTransportType()
/// Used by Edge runtime to specify an authentication chain for Edge-to-Edge connections.
/// </summary>
internal string AuthenticationChain { get; set; }

/// <summary>
/// The DotNetty event loop GracefulShutdown timeout.
/// </summary>
/// <remarks>
/// The DotNetty Mqtt transport has a graceful shutdown of the event loop that can block the <see cref="DeviceClient.CloseAsync(System.Threading.CancellationToken)"/> method. This timeout allows you to configure how long the shutdown event will wait for before forcefully shutting down the event loop. Change this if you need your application to respond to the CloseAsync command faster.
/// </remarks>
public TimeSpan GracefulEventLoopShutdownTimeout { get; set; } = TimeSpan.FromSeconds(1);
Copy link
Contributor

Choose a reason for hiding this comment

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

This was 1 millisecond before. I asked why but the only response I see is changing it to 1 second. Either way, I don't understand how we've chosen a default value and why is 1 second a good default? What are the implications to the user?

Copy link
Member Author

Choose a reason for hiding this comment

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

So by default the timeout value is 14 seconds... I can make this a TimeSpan.Zero and then let the customer decide if they want to lower it.

Copy link
Member

Choose a reason for hiding this comment

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

Same questions about he timeout values selected. It would be helpful to add a reference to the netty specs which define these timeout values (default/recommended etc).

Copy link
Member Author

Choose a reason for hiding this comment

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

I can do that.


/// <summary>
/// Sets the MqttTransport to use a single Event Loop Group.
/// </summary>
/// <remarks>
/// This setting is to retain legacy behavior that will use a single Event Loop Group which is the thread pool model for DotNetty. If this is set to false a new group will be created per instance of the Device Client.
Copy link
Member

Choose a reason for hiding this comment

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

We have 1 instance of mqtt adapter per device client, and we can have 1 instance of device client for a particular device identity. Considering that, what does this mean:
"If this is set to false a new group will be created per instance of the Device Client.", i.e. does this refer to the scenario where we dispose a client instance and reinitialize?

/// </remarks>
public bool UseSingleEventLoopGroup { get; set; } = true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ namespace Microsoft.Azure.Devices.Provisioning.Client.Transport
/// </summary>
public class ProvisioningTransportHandlerMqtt : ProvisioningTransportHandler
{
private static readonly MultithreadEventLoopGroup s_eventLoopGroup = new MultithreadEventLoopGroup();
private readonly MultithreadEventLoopGroup s_eventLoopGroup = new MultithreadEventLoopGroup();

// TODO: Unify these constants with IoT Hub Device client.
private const int MaxMessageSize = 256 * 1024;
Expand Down Expand Up @@ -169,6 +169,7 @@ protected override void Dispose(bool disposing)
{
if (disposing)
{
s_eventLoopGroup.ShutdownGracefullyAsync(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
_webSocketChannel?.Dispose();
_webSocketChannel = null;
}
Expand Down
Loading