При создании индекса на MongoDB мы получаем тайм-аут после 0 мс выбора сервера.
Ошибка возникает только в Linux (Ubuntu 18.04.2 LTS ARM64) / Raspberry Pi 3+.
На Windows 10 работает нормально без проблем.
Мы пытаемся добавить индекс при запуске приложения. База данных не имеет записей.
Я решил эту проблему, добавив Task.Delay(3000)
непосредственно перед добавлением индекса.
Кто-нибудь знает, что происходит? Я пока оставлю Task.Delay, но было бы лучше, если бы я справился с этим более хорошим способом.
Код:
using MongoDB.Bson;
using MongoDB.Driver;
private static async void AddIndexes(IMongoDatabase mongoDatabase)
{
// Compound index on type discriminator and user key
var typeUserIxDef = Builders<BsonDocument>.IndexKeys.Combine(
Builders<BsonDocument>.IndexKeys.Ascending("_t"),
Builders<BsonDocument>.IndexKeys.Ascending("Header.UserKey"));
var typeUserIxModel = new CreateIndexModel<BsonDocument>(typeUserIxDef);
// Hashed index on Header.Id
var headerIdIxDef = Builders<BsonDocument>.IndexKeys.Hashed("Header._id");
var headerIdIxModel = new CreateIndexModel<BsonDocument>(headerIdIxDef);
var indexModels = new List<CreateIndexModel<BsonDocument>>() { typeUserIxModel, headerIdIxModel };
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
await Task.Delay(3000);
}
// here System.TimeoutException happens on CreateManyAsync without Task.Delay on Linux
await mongoDatabase
.GetCollection<BsonDocument>("App")
.Indexes
.CreateManyAsync(indexModels);
}
Сообщение об исключении:
System.TimeoutException: A timeout occured after 0ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. (...)
Трассировка стека:
System.TimeoutException: A timeout occured after 0ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "Automatic", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "127.0.0.1:27017" }", EndPoint: "127.0.0.1:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: Connection refused 127.0.0.1:27017
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__271_0(IAsyncResult iar)
--- End of stack trace from previous location where exception was thrown ---
at MongoDB.Driver.Core.Connections.TcpStreamFactory.ConnectAsync(Socket socket, EndPoint endPoint, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Connections.TcpStreamFactory.CreateStreamAsync(EndPoint endPoint, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelperAsync(CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelperAsync(CancellationToken cancellationToken)
at MongoDB.Driver.Core.Servers.ServerMonitor.HeartbeatAsync(CancellationToken cancellationToken)" }] }.
at MongoDB.Driver.Core.Clusters.Cluster.ThrowTimeoutException(IServerSelector selector, ClusterDescription description)
at MongoDB.Driver.Core.Clusters.Cluster.SelectServerAsync(IServerSelector selector, CancellationToken cancellationToken)
at MongoDB.Driver.MongoClient.AreSessionsSupportedAfterSeverSelctionAsync(CancellationToken cancellationToken)
at MongoDB.Driver.MongoClient.AreSessionsSupportedAsync(CancellationToken cancellationToken)
at MongoDB.Driver.MongoClient.StartImplicitSessionAsync(CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)
at Our.Project.MongoDB.Mongo.AddIndexes(IMongoDatabase mongoDatabase)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__7_1(Object state)
at System.Threading.QueueUserWorkItemCallbackDefaultContext.<>c.<.cctor>b__5_0(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.QueueUserWorkItemCallbackDefaultContext.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Информация о системе:
OS: Ubuntu 18.04.2 LTS ARM64 on Raspberry Pi 3+
mongo: db version v4.0.9 - retrieved for previous linux system (Ubuntu 16.04 ARM64)
MongoDB.Driver: 2.8.1 (.NET core nuget)