Ejemplo n.º 1
0
            public void Handle(CommandFailedEvent @event)
            {
                var exception = @event.Failure;

                var mongoCommandException = exception as MongoCommandException;

                if (mongoCommandException != null)
                {
                    exception = new MongoCommandException(
                        mongoCommandException.ConnectionId,
                        mongoCommandException.Message,
                        RecursivelyMaterialize(mongoCommandException.Command),
                        RecursivelyMaterialize(mongoCommandException.Result));
                }

                @event = new CommandFailedEvent(
                    @event.CommandName,
                    exception,
                    @event.OperationId,
                    @event.RequestId,
                    @event.ConnectionId,
                    @event.ServiceId,
                    @event.Duration);
                _parent.Capture(@event);
            }
        public static bool EnsureIndexesShouldDropAndRetry(this MongoCommandException ex, IndexDefinition index)
        {
            //
            // index already exists, but with different options
            // Check using the error code - all error codes are defined here and have been stable over time, with only new codes added:
            // https://github.com/mongodb/mongo/blob/v3.4/src/mongo/base/error_codes.err
            //
            if (ex.Code == 86)
            {
                return(true);
            }

            //
            // index already exists
            //
            else if (ex.Message.StartsWith("Command createIndexes failed: Index must have unique name.The existing index:"))
            {
                // check if the existing and the requested index are different

                var indexes = ex.Message
                              .Remove(0, "Command createIndexes failed: Index must have unique name.The existing index: ".Length)
                              .Split(new string[] { " has the same name as the requested index: " }, StringSplitOptions.None);

                return(!indexes[0].Trim().Equals(indexes[1].Trim()));
            }

            return(false);
        }
Ejemplo n.º 3
0
 public static bool IsWriteConflictExcpetion(this MongoCommandException mongoCommandException)
 {
     if (mongoCommandException.Code.Equals(MongoErrorCode.WriteConflict))
     {
         return(true);
     }
     return(false);
 }
 public void Constructor_with_2_arguments_should_work()
 {
     var command = new BsonDocument("command", 1);
     var exception = new MongoCommandException("message", command);
     exception.Message.Should().Be("message");
     exception.InnerException.Should().BeNull();
     exception.Command.Equals(command).Should().BeTrue();
     exception.Result.Should().BeNull();
 }
Ejemplo n.º 5
0
        protected override Task <CrudResult <string> > PersistAddEntityAsync(T entity)
        {
            TaskCompletionSource <CrudResult <String> > tcs = new TaskCompletionSource <CrudResult <String> >();

            mongoDatabase.GetCollection <T>(this.tableName).InsertOneAsync(entity).ContinueWith(resultTask => {
                if (resultTask.IsFaulted)
                {
                    MongoCommandException mongoException = resultTask.Exception?.InnerException as MongoCommandException;
                    if (mongoException != null && mongoException.CodeName == "OperationNotSupportedInTransaction")
                    {
                        try
                        {
                            mongoDatabase.CreateCollection(tableName);
                            //List<CreateIndexModel<User>> indexModelList = new List<CreateIndexModel<User>>();
                            //var emailIndexOption = new CreateIndexOptions();
                            //emailIndexOption.Unique = true;
                            //var emailIndexKey = Builders<User>.IndexKeys.Ascending(user => user.Email);
                            //var emailIndexModel = new CreateIndexModel<User>(emailIndexKey, emailIndexOption);
                            //indexModelList.Add(emailIndexModel);

                            ////adding examId of UserExams field as Index
                            //var examIdIndexKey = Builders<User>.IndexKeys.Ascending(new StringFieldDefinition<User>($"{nameof(User.UserExams)}.{nameof(UserExam.ExamId)}"));
                            //var examIdIndexModel = new CreateIndexModel<User>(examIdIndexKey);
                            //indexModelList.Add(examIdIndexModel);

                            ////adding testId of UserTests field as Index
                            //var testIdIndexKey = Builders<User>.IndexKeys.Ascending(new StringFieldDefinition<User>($"{nameof(User.UserTests)}.{nameof(UserTest.TestId)}"));
                            //var testIdIndexModel = new CreateIndexModel<User>(testIdIndexKey);
                            //indexModelList.Add(testIdIndexModel);

                            ////adding subscriptionId of Subscriptions field as Index
                            //var subscriptionIdIndexKey = Builders<User>.IndexKeys.Ascending(new StringFieldDefinition<User>($"{nameof(User.Subscriptions)}.{nameof(Subscription.Id)}"));
                            //var subscriptionIdIndexModel = new CreateIndexModel<User>(subscriptionIdIndexKey);
                            //indexModelList.Add(subscriptionIdIndexModel);

                            //adding all the indexes.
                            //mongoTransaction.Database.GetCollection<User>(this.tableName).Indexes.CreateMany(indexModelList);
                            //mongoTransaction.Database.GetCollection<User>(this.tableName).InsertOne(mongoTransaction.SessionHandle, entity);
                        }
                        catch (Exception ex)
                        {
                            tcs.SetException(ex);
                        }
                    }

                    tcs.SetException(resultTask.Exception);
                }
                else
                {
                    tcs.SetResult(CrudResult <String> .Success(entity.Id));
                }
            });
            return(tcs.Task);
        }
 public void Constructor_with_4_arguments_should_work()
 {
     var command = new BsonDocument("command", 1);
     var result = new BsonDocument("result", 2);
     var innerException = new Exception("inner");
     var exception = new MongoCommandException("message", command, result, innerException);
     exception.Message.Should().Be("message");
     exception.InnerException.Message.Should().Be("inner");
     exception.Command.Equals(command).Should().BeTrue();
     exception.Result.Equals(result).Should().BeTrue();
 }
        private MongoException WrapNotSupportedRetryableWriteException(MongoCommandException exception)
        {
            const string friendlyErrorMessage =
                "This MongoDB deployment does not support retryable writes. " +
                "Please add retryWrites=false to your connection string.";

            return(new MongoCommandException(
                       exception.ConnectionId,
                       friendlyErrorMessage,
                       exception.Command,
                       exception.Result,
                       innerException: exception));
        }
Ejemplo n.º 8
0
        private Task <bool> TryHandleIndexCommandExceptionAsync(
            MongoCommandException exception,
            IndexDefinition <TDocument> indexDefinition,
            CancellationToken cancellationToken)
        {
            var command = exception.Command;
            var code    = exception.Code;

            return(code switch
            {
                MongoCommandErrorCodes.IndexOptionsConflict => TryHandleIndexOptionsConflictAsync(command, indexDefinition, cancellationToken),
                _ => Task.FromResult(false)
            });
Ejemplo n.º 9
0
 private static string MongoCommandExceptionHandle(MongoCommandException ex,
                                                   List <TreeNode> trvMongoDb,
                                                   TreeNode connectionNode,
                                                   string mongoConnKey)
 {
     //listDatabase命令错误,本质是用户名称错误
     if (ex.Result["errmsg"] == "unauthorized")
     {
         if (!GuiConfig.IsUseDefaultLanguage)
         {
             connectionNode.Text += "[" +
                                    GuiConfig.GetText(
                 TextType.ExceptionAuthenticationException) + "]";
             Utility.ExceptionDeal(ex,
                                   GuiConfig.GetText(
                                       TextType.ExceptionAuthenticationException),
                                   GuiConfig.GetText(
                                       TextType.ExceptionAuthenticationExceptionNote));
         }
         else
         {
             connectionNode.Text += "[MongoCommandExceptionHandle]";
             Utility.ExceptionDeal(ex, "MongoCommandExceptionHandle:", "Please check UserName and Password");
         }
     }
     else
     {
         if (!GuiConfig.IsUseDefaultLanguage)
         {
             connectionNode.Text += "[" +
                                    GuiConfig.GetText(
                 TextType.ExceptionNotConnected) + "]";
             Utility.ExceptionDeal(ex,
                                   GuiConfig.GetText(TextType.ExceptionNotConnected),
                                   "Unknown Exception");
         }
         else
         {
             connectionNode.Text += "[Exception]";
             Utility.ExceptionDeal(ex, "Not Connected", "Unknown Exception");
         }
     }
     connectionNode.Tag = ConstMgr.ConnectionExceptionTag + ":" + mongoConnKey;
     trvMongoDb.Add(connectionNode);
     return(mongoConnKey);
 }
        protected override Task <CrudResult <string> > PersistAddEntityAsync(Core.Models.Tag entity)
        {
            TaskCompletionSource <CrudResult <string> > tcs = new TaskCompletionSource <CrudResult <string> >();

            mongoDatabase.GetCollection <Core.Models.Tag>(this.tableName).InsertOneAsync(entity).ContinueWith(resultTask => {
                if (resultTask.IsFaulted)
                {
                    MongoCommandException mongoException = resultTask.Exception?.InnerException as MongoCommandException;
                    if (mongoException != null && mongoException.CodeName == "OperationNotSupportedInTransaction")
                    {
                        try
                        {
                            mongoDatabase.CreateCollection(tableName);
                            List <CreateIndexModel <Core.Models.Tag> > indexModelList = new List <CreateIndexModel <Core.Models.Tag> >();



                            ////adding userId as Index
                            var userIdIndexKey   = Builders <Core.Models.Tag> .IndexKeys.Ascending(new StringFieldDefinition <Core.Models.Tag>($"{nameof(Core.Models.Tag.UserId)}"));
                            var userIdIndexModel = new CreateIndexModel <Core.Models.Tag>(userIdIndexKey);
                            indexModelList.Add(userIdIndexModel);

                            ////adding name as Index
                            var nameIndexKey   = Builders <Core.Models.Tag> .IndexKeys.Ascending(new StringFieldDefinition <Core.Models.Tag>($"{nameof(Core.Models.Tag.Name)}"));
                            var nameIndexModel = new CreateIndexModel <Core.Models.Tag>(nameIndexKey);
                            indexModelList.Add(nameIndexModel);


                            //adding all the indexes.
                            mongoDatabase.GetCollection <Core.Models.Tag>(this.tableName).Indexes.CreateMany(indexModelList);
                        }
                        catch (Exception ex)
                        {
                            tcs.SetException(ex);
                        }
                    }

                    tcs.SetException(resultTask.Exception);
                }
                else
                {
                    tcs.SetResult(CrudResult <String> .Success(entity.Id));
                }
            });
            return(tcs.Task);
        }
        public static MongoCommandException CreateMongoCommandException(int code = 1, string label = null)
        {
            var clusterId        = new ClusterId(1);
            var endPoint         = new DnsEndPoint("localhost", 27017);
            var serverId         = new ServerId(clusterId, endPoint);
            var connectionId     = new ConnectionId(serverId);
            var message          = "Fake MongoCommandException";
            var command          = BsonDocument.Parse("{ command : 1 }");
            var result           = BsonDocument.Parse($"{{ ok: 0, code : {code} }}");
            var commandException = new MongoCommandException(connectionId, message, command, result);

            if (label != null)
            {
                commandException.AddErrorLabel(label);
            }

            return(commandException);
        }
Ejemplo n.º 12
0
        internal void ShouldInvalidateServer_should_return_expected_result_for_MongoCommandException(ServerErrorCode?code, string message, bool expectedResult)
        {
            _subject.Initialize();
            var clusterId     = new ClusterId(1);
            var serverId      = new ServerId(clusterId, new DnsEndPoint("localhost", 27017));
            var connectionId  = new ConnectionId(serverId);
            var command       = new BsonDocument("command", 1);
            var commandResult = new BsonDocument
            {
                { "ok", 0 },
                { "code", () => (int)code.Value, code.HasValue },
                { "errmsg", message, message != null }
            };
            var exception = new MongoCommandException(connectionId, "message", command, commandResult);

            var result = _subject.ShouldInvalidateServer(new Mock <IConnectionHandle>().Object, exception, new ServerDescription(_subject.ServerId, _subject.EndPoint), out _);

            result.Should().Be(expectedResult);
        }
        public void Serialization_should_work()
        {
            var command = new BsonDocument("command", 1);
            var result = new BsonDocument("result", 2);
            var innerException = new Exception("inner");
            var exception = new MongoCommandException("message", command, result, innerException);

            var formatter = new BinaryFormatter();
            using (var stream = new MemoryStream())
            {
                formatter.Serialize(stream, exception);
                stream.Position = 0;
                var rehydrated = (MongoCommandException)formatter.Deserialize(stream);
                rehydrated.Message.Should().Be("message");
                rehydrated.InnerException.Message.Should().Be("inner");
                rehydrated.Command.Equals(command).Should().BeTrue();
                rehydrated.Result.Equals(result).Should().BeTrue();
            }
        }
Ejemplo n.º 14
0
        public static MongoError GetError(this MongoCommandException exception)
        {
            var error  = MongoError.Unknown;
            var result = exception.CommandResult;

            if (result != null)
            {
                var response = result.Response;
                if (response != null)
                {
                    error = GetMongoError(response);
                }
                if (error == MongoError.Unknown && IsErrorStringMatch(GetMongoErrorMessage(result), "not master"))
                {
                    error = MongoError.NotMaster;
                }
            }
            return(error);
        }
Ejemplo n.º 15
0
 private bool IsCollectionNotFoundException(MongoCommandException ex)
 {
     return(ex.Code == 26);
 }
Ejemplo n.º 16
0
 private bool ShouldIgnoreException(MongoCommandException ex)
 {
     return(ex.ErrorMessage == "ns not found");
 }
Ejemplo n.º 17
0
 internal static TopologyVersion FromMongoCommandException(MongoCommandException commandException)
 {
     return(FromMongoCommandResponse(commandException.Result));
 }
 private bool IsMongoCursorNotFoundException(MongoCommandException exception)
 {
     return(exception.Code == (int)ServerErrorCode.CursorNotFound);
 }
Ejemplo n.º 19
0
 private bool ShouldIgnoreException(MongoCommandException ex)
 {
     return(ex.ErrorMessage != null && ex.ErrorMessage.Contains("ns not found"));
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MongoMapReduceException"/> class.
 /// </summary>
 /// <param name="exception">The exception.</param>
 /// <param name="mapReduce">The map reduce.</param>
 public MongoMapReduceException(MongoCommandException exception, MapReduce mapReduce)
     :base(exception.Message,exception.Error, exception.Command) {
     MapReduceResult = new MapReduce.MapReduceResult(exception.Error);
 }
        private TCommandResult ProcessResponse(ConnectionId connectionId, CommandMessage responseMessage)
        {
            using (new CommandMessageDisposer(responseMessage))
            {
                var rawDocument = responseMessage.Sections.OfType <Type0CommandMessageSection <RawBsonDocument> >().Single().Document;

                var binaryReaderSettings = new BsonBinaryReaderSettings();
                if (_messageEncoderSettings != null)
                {
                    binaryReaderSettings.Encoding = _messageEncoderSettings.GetOrDefault <UTF8Encoding>(MessageEncoderSettingsName.ReadEncoding, Utf8Encodings.Strict);
#pragma warning disable 618
                    if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
                    {
                        binaryReaderSettings.GuidRepresentation = _messageEncoderSettings.GetOrDefault <GuidRepresentation>(MessageEncoderSettingsName.GuidRepresentation, GuidRepresentation.CSharpLegacy);
                    }
#pragma warning restore 618
                }
                ;

                BsonValue clusterTime;
                if (rawDocument.TryGetValue("$clusterTime", out clusterTime))
                {
                    // note: we are assuming that _session is an instance of ClusterClockAdvancingClusterTime
                    // and that calling _session.AdvanceClusterTime will have the side effect of advancing the cluster's ClusterTime also
                    var materializedClusterTime = ((RawBsonDocument)clusterTime).Materialize(binaryReaderSettings);
                    _session.AdvanceClusterTime(materializedClusterTime);
                }

                BsonValue operationTime;
                if (rawDocument.TryGetValue("operationTime", out operationTime))
                {
                    _session.AdvanceOperationTime(operationTime.AsBsonTimestamp);
                }

                if (rawDocument.GetValue("ok", false).ToBoolean())
                {
                    if (rawDocument.TryGetValue("recoveryToken", out var rawRecoveryToken))
                    {
                        var recoveryToken = ((RawBsonDocument)rawRecoveryToken).Materialize(binaryReaderSettings);
                        _session.CurrentTransaction.RecoveryToken = recoveryToken;
                    }
                }
                else
                {
                    var materializedDocument = rawDocument.Materialize(binaryReaderSettings);

                    var commandName = _command.GetElement(0).Name;
                    if (commandName == "$query")
                    {
                        commandName = _command["$query"].AsBsonDocument.GetElement(0).Name;
                    }

                    var notPrimaryOrNodeIsRecoveringException = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, _command, materializedDocument, "errmsg");
                    if (notPrimaryOrNodeIsRecoveringException != null)
                    {
                        throw notPrimaryOrNodeIsRecoveringException;
                    }

                    var mappedException = ExceptionMapper.Map(connectionId, materializedDocument);
                    if (mappedException != null)
                    {
                        throw mappedException;
                    }

                    string    message;
                    BsonValue errmsgBsonValue;
                    if (materializedDocument.TryGetValue("errmsg", out errmsgBsonValue) && errmsgBsonValue.IsString)
                    {
                        var errmsg = errmsgBsonValue.ToString();
                        message = string.Format("Command {0} failed: {1}.", commandName, errmsg);
                    }
                    else
                    {
                        message = string.Format("Command {0} failed.", commandName);
                    }

                    var exception = new MongoCommandException(connectionId, message, _command, materializedDocument);

                    // https://jira.mongodb.org/browse/CSHARP-2678
                    if (IsRetryableWriteExceptionAndDeploymentDoesNotSupportRetryableWrites(exception))
                    {
                        throw WrapNotSupportedRetryableWriteException(exception);
                    }
                    else
                    {
                        throw exception;
                    }
                }

                if (rawDocument.Contains("writeConcernError"))
                {
                    var materializedDocument = rawDocument.Materialize(binaryReaderSettings);
                    var writeConcernError    = materializedDocument["writeConcernError"].AsBsonDocument;
                    var message            = writeConcernError.AsBsonDocument.GetValue("errmsg", null)?.AsString;
                    var writeConcernResult = new WriteConcernResult(materializedDocument);
                    throw new MongoWriteConcernException(connectionId, message, writeConcernResult);
                }

                using (var stream = new ByteBufferStream(rawDocument.Slice, ownsBuffer: false))
                {
                    using (var reader = new BsonBinaryReader(stream, binaryReaderSettings))
                    {
                        var context = BsonDeserializationContext.CreateRoot(reader);
                        return(_resultSerializer.Deserialize(context));
                    }
                }
            }
        }
 private bool ShouldIgnoreException(MongoCommandException ex)
 {
     return
         (ex.Code == (int)ServerErrorCode.NamespaceNotFound ||
          ex.ErrorMessage == "ns not found");
 }
 private bool IsRetryableWriteExceptionAndDeploymentDoesNotSupportRetryableWrites(MongoCommandException exception)
 {
     return
         (exception.Result.TryGetValue("code", out var errorCode) &&
          errorCode.ToInt32() == 20 &&
          exception.Result.TryGetValue("errmsg", out var errmsg) &&
          errmsg.AsString.StartsWith("Transaction numbers", StringComparison.Ordinal));
 }
 bool WriteConflictUnderTransaction(MongoCommandException e)
 {
     return(useTransaction && e.HasErrorLabel("TransientTransactionError") && e.CodeName == "WriteConflict");
 }