CancelRequest() private method

private CancelRequest ( ) : void
return void
示例#1
0
        ///<summary>
        /// This method is responsible to handle all protocol messages sent from the backend.
        /// It holds all the logic to do it.
        /// To exchange data, it uses a Mediator object from which it reads/writes information
        /// to handle backend requests.
        /// </summary>
        ///
        internal IEnumerable <IServerResponseObject> ProcessBackendResponsesEnum(NpgsqlConnector context)
        {
            try
            {
                // Flush buffers to the wire.
                context.Stream.Flush();

                // Process commandTimeout behavior.

                if ((context.Mediator.BackendCommandTimeout > 0) &&
                    (!CheckForContextSocketAvailability(context, SelectMode.SelectRead)))
                {
                    // If timeout occurs when establishing the session with server then
                    // throw an exception instead of trying to cancel query. This helps to prevent loop as
                    // CancelRequest will also try to stablish a connection and sends commands.
                    if (!((this is NpgsqlStartupState || this is NpgsqlConnectedState)))
                    {
                        try
                        {
                            context.CancelRequest();

                            ProcessAndDiscardBackendResponses(context);
                        }
                        catch (Exception)
                        {
                        }
                        // We should have gotten an error from CancelRequest(). Whether we did or not, what we
                        // really have is a timeout exception, and that will be less confusing to the user than
                        // "operation cancelled by user" or similar, so whatever the case, that is what we'll throw.
                        // Changed message again to report about the two possible timeouts: connection or command
                        // as the establishment timeout only was confusing users when the timeout was a command timeout.
                    }

                    throw new NpgsqlException(resman.GetString("Exception_ConnectionOrCommandTimeout"));
                }

                switch (context.BackendProtocolVersion)
                {
                case ProtocolVersion.Version2:
                    return(ProcessBackendResponses_Ver_2(context));

                case ProtocolVersion.Version3:
                    return(ProcessBackendResponses_Ver_3(context));

                default:
                    throw new NpgsqlException(resman.GetString("Exception_UnknownProtocol"));
                }
            }
            catch (ThreadAbortException)
            {
                try
                {
                    context.CancelRequest();
                    context.Close();
                }
                catch {}

                throw;
            }
        }
示例#2
0
        /// <summary>
        /// Repeatedly attempts to rollback, to support timeout-triggered rollbacks that occur while the connection is busy.
        /// </summary>
        void RollbackLocal()
        {
            Debug.Assert(_connector != null, "No connector");
            Debug.Assert(_localTx != null, "No local transaction");

            var attempt = 0;

            while (true)
            {
                try
                {
                    _localTx.Rollback();
                    return;
                }
                catch (NpgsqlOperationInProgressException)
                {
                    // This really shouldn't be necessary, but just in case
                    if (attempt++ == MaximumRollbackAttempts)
                    {
                        throw new Exception($"Could not roll back after {MaximumRollbackAttempts} attempts, aborting. Transaction is in an unknown state.");
                    }

                    Log.Logger.LogWarning(NpgsqlEventId.ConnectionInUseDuringRollback, "[{ConnectorId}] Connection in use while trying to rollback, will cancel and retry (localid={TransactionId}", _connector.Id, _txId);
                    _connector.CancelRequest();
                    // Cancellations are asynchronous, give it some time
                    Thread.Sleep(500);
                }
            }
        }
示例#3
0
        /// <summary>
        /// Cancels and terminates an ongoing operation. Any data already written will be discarded.
        /// </summary>
        public void Cancel()
        {
            CheckDisposed();

            if (CanWrite)
            {
                _isDisposed = true;
                _buf.Clear();
                _connector.SendSingleMessage(new CopyFailMessage());
                try
                {
                    var msg = _connector.ReadSingleMessage();
                    // The CopyFail should immediately trigger an exception from the read above.
                    _connector.Break();
                    throw new Exception("Expected ErrorResponse when cancelling COPY but got: " + msg.Code);
                }
                catch (NpgsqlException e)
                {
                    if (e.Code == "57014")
                    {
                        return;
                    }
                    throw;
                }
            }
            else
            {
                _connector.CancelRequest();
            }
        }
示例#4
0
        void RollbackLocal()
        {
            Log.Debug($"Single-phase transaction rollback (localid={_txId})", _connector.Id);

            var attempt = 0;

            while (true)
            {
                try
                {
                    _localTx.Rollback();
                    return;
                }
                catch (NpgsqlOperationInProgressException)
                {
                    // Repeatedly attempts to rollback, to support timeout-triggered rollbacks that occur
                    // while the connection is busy.

                    // This really shouldn't be necessary, but just in case
                    if (attempt++ == MaximumRollbackAttempts)
                    {
                        throw new Exception($"Could not roll back after {MaximumRollbackAttempts} attempts, aborting. Transaction is in an unknown state.");
                    }

                    Log.Warn($"Connection in use while trying to rollback, will cancel and retry (localid={_txId}", _connector.Id);
                    _connector.CancelRequest();
                    // Cancellations are asynchronous, give it some time
                    Thread.Sleep(500);
                }
            }
        }
示例#5
0
        async Task Cancel(bool async)
        {
            CheckDisposed();

            if (CanWrite)
            {
                _isDisposed = true;
                _writeBuf.EndCopyMode();
                _writeBuf.Clear();
                await _connector.WriteCopyFail(async);

                await _connector.Flush(async);

                try
                {
                    var msg = await _connector.ReadMessage(async);

                    // The CopyFail should immediately trigger an exception from the read above.
                    _connector.Break();
                    throw new NpgsqlException("Expected ErrorResponse when cancelling COPY but got: " + msg.Code);
                }
                catch (PostgresException e)
                {
                    if (e.SqlState == PostgresErrorCodes.QueryCanceled)
                    {
                        return;
                    }
                    throw;
                }
            }
            else
            {
                _connector.CancelRequest();
            }
        }
示例#6
0
        /// <summary>
        /// Cancels and terminates an ongoing operation. Any data already written will be discarded.
        /// </summary>
        public void Cancel()
        {
            CheckDisposed();

            if (CanWrite)
            {
                _isDisposed = true;
                _buf.Clear();
                _connector.SendSingleMessage(new CopyFailMessage());
                try
                {
                    var msg = _connector.ReadSingleMessage();
                    _connector.State = ConnectorState.Broken;
                    throw new Exception("Expected ErrorResponse when cancelling COPY but got: " + msg.Code);
                }
                catch (NpgsqlException e)
                {
                    if (e.Code == "57014")
                    {
                        return;
                    }
                    throw;
                }
            }
            else
            {
                _connector.CancelRequest();
            }
        }
示例#7
0
 internal IEnumerable <IServerResponseObject> ProcessExistingBackendResponses(NpgsqlConnector context)
 {
     try
     {
         return(ProcessBackendResponses_Ver_3(context));
     }
     catch (ThreadAbortException)
     {
         try
         {
             context.CancelRequest();
             context.Close();
         }
         catch { }
         throw;
     }
 }
示例#8
0
        /// <summary>
        /// Attempts to cancel the execution of a <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see>.
        /// </summary>
        /// <remarks>This Method isn't implemented yet.</remarks>
        public override void Cancel()
        {
            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "Cancel");

            try
            {
                // get copy for thread safety of null test
                NpgsqlConnector connector = Connector;
                if (connector != null)
                {
                    connector.CancelRequest();
                }
            }
            catch (IOException)
            {
                Connection.ClearPool();
            }
            catch (NpgsqlException)
            {
                // Cancel documentation says the Cancel doesn't throw on failure
            }
        }
示例#9
0
        ///<summary>
        /// This method is responsible to handle all protocol messages sent from the backend.
        /// It holds all the logic to do it.
        /// To exchange data, it uses a Mediator object from which it reads/writes information
        /// to handle backend requests.
        /// </summary>
        ///
        internal virtual void ProcessBackendResponses(NpgsqlConnector context)
        {
            try
            {
                // Process commandTimeout behavior.

                if ((context.Mediator.CommandTimeout > 0) && (!context.Socket.Poll(1000000 * context.Mediator.CommandTimeout, SelectMode.SelectRead)))
                {
                    // If timeout occurs when establishing the session with server then
                    // throw an exception instead of trying to cancel query. This helps to prevent loop as CancelRequest will also try to stablish a connection and sends commands.
                    if ((this is NpgsqlStartupState || this is NpgsqlConnectedState))
                    {
                        throw new NpgsqlException(resman.GetString("Exception_ConnectionTimeout"));
                    }
                    else
                    {
                        context.CancelRequest();
                    }
                }



                switch (context.BackendProtocolVersion)
                {
                case ProtocolVersion.Version2:
                    ProcessBackendResponses_Ver_2(context);
                    break;

                case ProtocolVersion.Version3:
                    ProcessBackendResponses_Ver_3(context);
                    break;
                }
            }
            finally
            {
                // reset expectations right after getting new responses
                context.Mediator.ResetExpectations();
            }
        }
示例#10
0
        ///<summary>
        /// This method is responsible to handle all protocol messages sent from the backend.
        /// It holds all the logic to do it.
        /// To exchange data, it uses a Mediator object from which it reads/writes information
        /// to handle backend requests.
        /// </summary>
        ///
        internal IEnumerable<IServerResponseObject> ProcessBackendResponsesEnum(NpgsqlConnector context)
        {
            try
            {
            // Process commandTimeout behavior.

            if ((context.Mediator.CommandTimeout > 0) &&
                (!context.Socket.Poll(1000000*context.Mediator.CommandTimeout, SelectMode.SelectRead)))
            {
                // If timeout occurs when establishing the session with server then
                // throw an exception instead of trying to cancel query. This helps to prevent loop as CancelRequest will also try to stablish a connection and sends commands.
                if (!((this is NpgsqlStartupState || this is NpgsqlConnectedState || context.CancelRequestCalled)))
                {
                    try
                    {
                        context.CancelRequest();
                        foreach (IServerResponseObject obj in ProcessBackendResponsesEnum(context))
                        {
                            if (obj is IDisposable)
                            {
                                (obj as IDisposable).Dispose();
                            }
                        }
                    }
                    catch(Exception ex)
                    {
                    }
                    //We should have gotten an error from CancelRequest(). Whether we did or not, what we
                    //really have is a timeout exception, and that will be less confusing to the user than
                    //"operation cancelled by user" or similar, so whatever the case, that is what we'll throw.
                    // Changed message again to report about the two possible timeouts: connection or command as the establishment timeout only was confusing users when the timeout was a command timeout.
                }
                throw new NpgsqlException(resman.GetString("Exception_ConnectionOrCommandTimeout"));
            }
            switch (context.BackendProtocolVersion)
            {
                case ProtocolVersion.Version2:
                    return ProcessBackendResponses_Ver_2(context);
                case ProtocolVersion.Version3:
                    return ProcessBackendResponses_Ver_3(context);
                default:
                    throw new NpgsqlException(resman.GetString("Exception_UnknownProtocol"));
            }

            }

            catch(ThreadAbortException)
            {
                try
                {
                    context.CancelRequest();
                    context.Close();
                }
                catch {}

                throw;
            }
        }
示例#11
0
 /// <summary>
 /// Cancels an ongoing export.
 /// </summary>
 public void Cancel()
 {
     _connector.CancelRequest();
 }
示例#12
0
 internal IEnumerable<IServerResponseObject> ProcessExistingBackendResponses(NpgsqlConnector context)
 {
     try
     {
         return ProcessBackendResponses_Ver_3(context);
     }
     catch (ThreadAbortException)
     {
         try
         {
             context.CancelRequest();
             context.Close();
         }
         catch { }
         throw;
     }
 }
示例#13
0
        ///<summary>
        /// This method is responsible to handle all protocol messages sent from the backend.
        /// It holds all the logic to do it.
        /// To exchange data, it uses a Mediator object from which it reads/writes information
        /// to handle backend requests.
        /// </summary>
        ///
        internal virtual void ProcessBackendResponses( NpgsqlConnector context )
        {

            try
            {
                
                // Process commandTimeout behavior.
                
                if ((context.Mediator.CommandTimeout > 0) && (!context.Socket.Poll(1000000 * context.Mediator.CommandTimeout, SelectMode.SelectRead)))
                {
                    // If timeout occurs when establishing the session with server then
                    // throw an exception instead of trying to cancel query. This helps to prevent loop as CancelRequest will also try to stablish a connection and sends commands.
                    if ((this is NpgsqlStartupState || this is NpgsqlConnectedState))
                        throw new NpgsqlException(resman.GetString("Exception_ConnectionTimeout"));
                   else
                       context.CancelRequest();

                }
                    
                
                
                switch (context.BackendProtocolVersion)
                {
                case ProtocolVersion.Version2 :
                    ProcessBackendResponses_Ver_2(context);
                    break;

                case ProtocolVersion.Version3 :
                    ProcessBackendResponses_Ver_3(context);
                    break;

                }
            }
            finally
            {
                // reset expectations right after getting new responses
                context.Mediator.ResetExpectations();
            }
        }
示例#14
0
        ///<summary>
        /// This method is responsible to handle all protocol messages sent from the backend.
        /// It holds all the logic to do it.
        /// To exchange data, it uses a Mediator object from which it reads/writes information
        /// to handle backend requests.
        /// </summary>
        ///
        internal IEnumerable<IServerResponseObject> ProcessBackendResponsesEnum(NpgsqlConnector context)
        {
            try
            {
                // Flush buffers to the wire.
                context.Stream.Flush();

                // Process commandTimeout behavior.

                if ((context.Mediator.BackendCommandTimeout > 0) &&
                        (!CheckForContextSocketAvailability(context, SelectMode.SelectRead)))
                {
                    // If timeout occurs when establishing the session with server then
                    // throw an exception instead of trying to cancel query. This helps to prevent loop as
                    // CancelRequest will also try to stablish a connection and sends commands.
                    if (!((this is NpgsqlStartupState || this is NpgsqlConnectedState)))
                    {
                        try
                        {
                            context.CancelRequest();

                            ProcessAndDiscardBackendResponses(context);
                        }
                        catch(Exception)
                        {
                        }
                        // We should have gotten an error from CancelRequest(). Whether we did or not, what we
                        // really have is a timeout exception, and that will be less confusing to the user than
                        // "operation cancelled by user" or similar, so whatever the case, that is what we'll throw.
                        // Changed message again to report about the two possible timeouts: connection or command
                        // as the establishment timeout only was confusing users when the timeout was a command timeout.
                    }

                    throw new NpgsqlException(resman.GetString("Exception_ConnectionOrCommandTimeout"));
                }

                return ProcessBackendResponses(context);
            }
            catch(ThreadAbortException)
            {
                try
                {
                    context.CancelRequest();
                    context.Close();
                }
                catch {}

                throw;
            }

        }
示例#15
0
        ///<summary>
        /// This method is responsible to handle all protocol messages sent from the backend.
        /// It holds all the logic to do it.
        /// To exchange data, it uses a Mediator object from which it reads/writes information
        /// to handle backend requests.
        /// </summary>
        ///
        internal IEnumerable<IServerResponseObject> ProcessBackendResponsesEnum(NpgsqlConnector context)
        {
            try
            {
                // Flush buffers to the wire.
                context.Stream.Flush();

                // Process commandTimeout behavior.

                // We will give an extra 5 seconds to context.Mediator.CommandTimeout
                // because we'd prefer to receive a timeout error from PG
                // than to be forced to start a new connection and send a cancel request.
                // The result is that a timeout could take 5 seconds too long to occur, but if everything
                // is healthy, that shouldn't happen.
                if ((context.Mediator.BackendCommandTimeout > 0) && (!context.Stream.WaitAvailable(TimeSpan.FromSeconds(context.Mediator.BackendCommandTimeout + 5))))
                {
                    // If timeout occurs when establishing the session with server then
                    // throw an exception instead of trying to cancel query. This helps to prevent loop as
                    // CancelRequest will also try to stablish a connection and sends commands.
                    if (!((this is NpgsqlStartupState || this is NpgsqlConnectedState)))
                    {
                        try
                        {
                            context.CancelRequest();

                            ProcessAndDiscardBackendResponses(context);
                        }
                        catch(Exception)
                        {
                        }
                        // We should have gotten an error from CancelRequest(). Whether we did or not, what we
                        // really have is a timeout exception, and that will be less confusing to the user than
                        // "operation cancelled by user" or similar, so whatever the case, that is what we'll throw.
                        // Changed message again to report about the two possible timeouts: connection or command
                        // as the establishment timeout only was confusing users when the timeout was a command timeout.
                    }

                    throw new NpgsqlException(resman.GetString("Exception_ConnectionOrCommandTimeout"));
                }

                switch (context.BackendProtocolVersion)
                {
                    case ProtocolVersion.Version2:
                        return ProcessBackendResponses_Ver_2(context);
                    case ProtocolVersion.Version3:
                        return ProcessBackendResponses_Ver_3(context);
                    default:
                        throw new NpgsqlException(resman.GetString("Exception_UnknownProtocol"));
                }

            }
            catch(ThreadAbortException)
            {
                try
                {
                    context.CancelRequest();
                    context.Close();
                }
                catch {}

                throw;
            }
        }