Skip to content

[WIP][consumer] Deadlock with in-flight acknowledgements - #366

Closed
fracasula wants to merge 4 commits into
apache:masterfrom
fracasula:consumer-deadlock
Closed

fracasula wants to merge 4 commits into
apache:masterfrom
fracasula:consumer-deadlock

Conversation

@fracasula

@fracasula fracasula commented Sep 15, 2020 •

Copy link
Copy Markdown

Motivation

This is an integration test built with the intent of replicating the bug reported in this issue. I opened this PR to gather some feedback before working on a fix.

A possible solution would be to move the connectionClosed events out of the eventsCh channel and have them into their own channel (e.g. connectionEventsCh): https://github.com/apache/pulsar-client-go/blob/master/pulsar/consumer_partition.go#L752

This is because some of the events travelling through the eventsCh channel rely on an open connection to finish. So if the eventsCh channel gets full with, say, in-flight ackRequest events, the connectionClosed event cannot be processed until the ackRequest are finished and the ackRequest cannot finish because the connection is closed and the connectionClosed event (which should trigger a reconnection to the broker) is stuck waiting to be pushed to the eventsCh channel.

Given that the connectionClosed event is needed to trigger a reconnection to the broker I think it could make sense to have it in a separate channel.

If this approach sounds sensible to you I can start making modifications.

Replicate the bug

The test doesn't always fail, you'll have to try again. In my case it fails 1 out of 3 times (more or less).
So if you run it just once and you see the test complete instead of failing, then please run it again.

Once the test fails you should see that it timed out after five minutes and that it printed a lot of logs saying Trying to ack {messageID}.

Please check the attached deadlock.zip which shows the logs of a failing test.

Running the test

  • make sure you have docker running and usable from the user that runs the test
  • make sure you do docker pull apachepulsar/pulsar:2.6.1 first
  • then do: go test ./pulsar/ -test.run ^TestDeadlock$ -v -tags integration -count 1

deadlock.zip

@alexku7

alexku7 commented Sep 15, 2020

Copy link
Copy Markdown

is this issue affecting the Go client only or other clients as well ?

@fracasula

Copy link
Copy Markdown
Author

is this issue affecting the Go client only or other clients as well ?

Hi @alexku7,

if you run the test I posted and set up a few breakpoints you'll realize that this is a Golang library issue. I tried with Python multiple times and it never got deadlocked while acking.

Have you noticed that the eventsCh has a buffer of 3 only and that it is used for lots of events, some of which are ackRequest and connectionClosed events? I think the reason why it happens should be clear from my explanation. Do you agree that is the case?

@wolfstudy

Copy link
Copy Markdown
Member
package main

import (
	"context"
	"fmt"
	"github.com/apache/pulsar-client-go/pulsar"
	"log"
	"math/rand"
	"time"
)

func main() {
	//  create client
	client, err := pulsar.NewClient(pulsar.ClientOptions{
		URL:                     "pulsar://localhost:6650",
		MaxConnectionsPerBroker: 1,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	topic := randomName("topic-name")

	// create consumer
	consumer, err := client.Subscribe(pulsar.ConsumerOptions{
		Name:                        randomName("consumer-name"),
		SubscriptionName:            randomName("subscription-name"),
		Topic:                       topic,
		Type:                        pulsar.KeyShared,
		SubscriptionInitialPosition: pulsar.SubscriptionPositionEarliest,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer consumer.Close()

	// create producer
	producer, err := client.CreateProducer(pulsar.ProducerOptions{
		Topic: topic,
		Name:  randomName("producer-name"),
	})
	if err != nil {
		log.Fatal(err)
	}
	defer producer.Close()

	// Publishing a lot of messages to target topic
	countMsg := 10000
	log.Printf("Publishing %d messages", countMsg)

	// publish messages
	for i := 0; i < countMsg; i++ {
		_, err := producer.Send(context.Background(), &pulsar.ProducerMessage{
			Payload:   []byte(fmt.Sprintf("payload-%d", i)),
			Key:       fmt.Sprintf("msg-key-%d", i),
			EventTime: time.Now(),
		})
		if err != nil {
			log.Fatal(err)
		}
	}

	// receive message
	log.Println("Starting consumer routine")
	for i := 1; i <= countMsg; i++ {
		msg, err := consumer.Receive(context.Background())
		if err != nil {
			log.Fatal(err)
		}
		log.Printf("Got message %d", i)
		consumer.Ack(msg)
	}

}

func randomName(prefix string) string {
	return fmt.Sprintf("%s-%x", prefix, rand.Int63())
}

@wolfstudy

Copy link
Copy Markdown
Member

Thanks @fracasula feedback, Here I tried to use the simplest code to simulate this problem, unfortunately, I did not reproduce it.

@fracasula

fracasula commented Sep 16, 2020 •

Copy link
Copy Markdown
Author

Thanks @fracasula feedback, Here I tried to use the simplest code to simulate this problem, unfortunately, I did not reproduce it.

Hi @wolfstudy, I don't understand why you're trying to replicate the bug with that code, it would be nearly impossible. I invite you to read the description of the issue in my first post again, I'll post it here below for convenience:

This is because some of the events travelling through the eventsCh channel rely on an open connection to finish. So if the eventsCh channel gets full with, say, in-flight ackRequest events, the connectionClosed event cannot be processed until the ackRequest are finished and the ackRequest cannot finish because the connection is closed and the connectionClosed event (which should trigger a reconnection to the broker) is stuck waiting to be pushed to the eventsCh channel.

If you want a good chance to reproduce it YOU MUST try to have as much in-flight ackRequest events as possible (best if you ack in a separate go routine for parallelism) and at the same time close the connection multiple times to simulate the behaviour of errors like the Received too big frame size one. That is because Received too big frame size errors trigger a connection close (i.e. r.cnx.TriggerClose()).

This way you'll have a good chance to replicate the deadlock which, in order to happen, would need at least 3 in-flight ackRequest filling the channel while the connection is closed, so that the connectionClosed event won't be processed.

Please do run the test I provided that is already reproducing the bug, it doesn't take much to reverse engineer.

@wolfstudy

wolfstudy commented Sep 21, 2020 •

Copy link
Copy Markdown
Member

Hi @fracasula , I checkout to execute it in your current branch and used the test case you provided and tried to run more than 10 times locally. I didn't reproduce. The locality can work normally.

The only change is that I encountered a context deadline exceeded during the first execution, after which i adjusted the time of the context form 5 minutes to 10 minutes.

	// New context
	ctx, cancel = context.WithTimeout(context.Background(), 10*time.Minute)
	t.Cleanup(cancel)

And the output as follows:

    consumer_partition_integration_test.go:97: Got message 99991
    consumer_partition_integration_test.go:97: Got message 99992
    consumer_partition_integration_test.go:97: Got message 99993
    consumer_partition_integration_test.go:97: Got message 99994
    consumer_partition_integration_test.go:97: Got message 99995
    consumer_partition_integration_test.go:97: Got message 99996
    consumer_partition_integration_test.go:97: Got message 99997
    consumer_partition_integration_test.go:97: Got message 99998
    consumer_partition_integration_test.go:97: Got message 99999
    consumer_partition_integration_test.go:97: Got message 100000
    consumer_partition_integration_test.go:132: Test complete!
07:16:39.592 [Thread-1] INFO  org.apache.pulsar.functions.worker.FunctionMetaDataTopicTailer - Stopping function metadata tailer
07:16:39.593 [pulsar-io-51-10] INFO  org.apache.pulsar.broker.service.ServerCnx - [/127.0.0.1:33174] Closing consumer: 1
07:16:39.593 [pulsar-io-51-10] INFO  org.apache.pulsar.broker.service.AbstractDispatcherSingleActiveConsumer - Removing consumer Consumer{subscription=PersistentSubscription{topic=persistent://public/functions/metadata, name=reader-758e557af5}, consumerId=1, consumerName=c-standalone-fw-localhost-8080-function-metadata-manager, address=/127.0.0.1:33174}
07:16:39.594 [pulsar-io-51-10] INFO  org.apache.pulsar.broker.service.persistent.PersistentSubscription - [persistent://public/functions/metadata][reader-758e557af5] Successfully closed subscription [NonDurableCursorImpl{ledger=public/functions/persistent/metadata, ackPos=9:-1, readPos=9:0}]

go version

Output:

go version go1.14.6 darwin/amd64

@wolfstudy

Copy link
Copy Markdown
Member

I dump the log file of the test case

deadlock.txt

@cckellogg

Copy link
Copy Markdown
Contributor

@fracasula does increasing the events channel buffer help? That number was kind of randomly picked. I would suggest to go ahead a put up a fix.

@wolfstudy

wolfstudy commented Sep 22, 2020 •

Copy link
Copy Markdown
Member

All requests in the go client will enter the incomingRequestChannel, and then the request will be processed in the runEventsLoop. incomingRequestChannel is a channel with a buffer. When the size of the buffer is reached, it will wait for the consumer in the channel (different from the consumer of pulsar) to consume data. In the current processing of the go client, there is no incomingRequestChannel close logic. We previously thought that after closing the consumer and closing the connection, all the corresponding states need to be cleaned up. But in fact, there was no suitable time to close the channel that received the request.

First: After closing the connection, it will immediately enter the logic of reconnection. At this time, you still need to use incomingRequestChannel to receive data.
Second: In runEventsLoop, as long as a data request enters the eventsChannel, the entire processing flow will not be blocked

In my repeated attempts to reproduce locally, I only encountered the following errors:

    consumer_partition_integration_test.go:97: Got message 55800
    consumer_partition_integration_test.go:96:
        	Error Trace:	consumer_partition_integration_test.go:96
        	            				asm_amd64.s:1373
        	Error:      	Received unexpected error:
        	            	context deadline exceeded
        	Test:       	TestDeadlock
11:09:36.912 [pulsar-web-69-11] INFO  org.eclipse.jetty.server.RequestLog - 127.0.0.1 - - [21/Sep/2020:11:09:36 +0000] "GET /admin/v2/persistent/public/functions/coordinate/stats?getPreciseBacklog=false HTTP/1.

This error has nothing to do with the problem itself. It is caused by the context timeout. We try to increase the context timeout to avoid this problem.

@fracasula

fracasula commented Sep 22, 2020 •

Copy link
Copy Markdown
Author

@wolfstudy it may not be a client issue as I mentioned in my last post in this other thread and in our email correspondence. If you look at the video I sent you at 4:20 it shows that there are no consumers connected despite the connection being open. I can see the ping and pongs travelling back and forth with tcpdump though so I think we can assume that the client is connected, correct me if I'm wrong.

$ sudo tcpdump -i docker0 -nn -v -s0 -A port 6650
tcpdump: listening on docker0, link-type EN10MB (Ethernet), capture size 262144 bytes
10:00:08.514601 IP (tos 0x0, ttl 64, id 42719, offset 0, flags [DF], proto TCP (6), length 65)
    172.17.0.1.32794 > 172.17.0.2.6650: Flags [P.], cksum 0x5859 (incorrect -> 0xc76b), seq 3118165760:3118165773, ack 962716458, win 502, options [nop,nop,TS val 823193679 ecr 1498243285], length 13
E..A..@.@.;...............o.9a.*....XY.....
1..OYM`....	.........
10:00:08.514829 IP (tos 0x0, ttl 64, id 21439, offset 0, flags [DF], proto TCP (6), length 65)
    172.17.0.2.6650 > 172.17.0.1.32794: Flags [P.], cksum 0x5859 (incorrect -> 0x4a29), seq 1:14, ack 13, win 509, options [nop,nop,TS val 1498273282 ecr 823193679], length 13
E..AS.@[email protected].*..o.....XY.....
YM..1..O...	.........
10:00:08.514871 IP (tos 0x0, ttl 64, id 42720, offset 0, flags [DF], proto TCP (6), length 52)
    172.17.0.1.32794 > 172.17.0.2.6650: Flags [.], cksum 0x584c (incorrect -> 0xec59), ack 14, win 502, options [nop,nop,TS val 823193680 ecr 1498273282], length 0
E..4..@.@.;...............o.9a.7....XL.....
1..PYM..
10:00:08.516685 IP (tos 0x0, ttl 64, id 21440, offset 0, flags [DF], proto TCP (6), length 65)
    172.17.0.2.6650 > 172.17.0.1.32794: Flags [P.], cksum 0x5859 (incorrect -> 0x521a), seq 14:27, ack 13, win 509, options [nop,nop,TS val 1498273284 ecr 823193680], length 13
E..AS.@[email protected].....
YM..1..P...	.........
10:00:08.516742 IP (tos 0x0, ttl 64, id 42721, offset 0, flags [DF], proto TCP (6), length 52)
    172.17.0.1.32794 > 172.17.0.2.6650: Flags [.], cksum 0x584c (incorrect -> 0xec48), ack 27, win 502, options [nop,nop,TS val 823193682 ecr 1498273284], length 0
E..4..@.@.;...............o.9a.D....XL.....
1..RYM..
10:00:08.517080 IP (tos 0x0, ttl 64, id 42722, offset 0, flags [DF], proto TCP (6), length 65)
    172.17.0.1.32794 > 172.17.0.2.6650: Flags [P.], cksum 0x5859 (incorrect -> 0x4a11), seq 13:26, ack 27, win 502, options [nop,nop,TS val 823193682 ecr 1498273284], length 13
E..A..@.@.;...............o.9a.D....XY.....
1..RYM.....	.........
10:00:08.557481 IP (tos 0x0, ttl 64, id 21441, offset 0, flags [DF], proto TCP (6), length 52)
    172.17.0.2.6650 > 172.17.0.1.32794: Flags [.], cksum 0x584c (incorrect -> 0xec0c), ack 26, win 509, options [nop,nop,TS val 1498273324 ecr 823193682], length 0
E..4S.@[email protected].....
YM.,1..R

The test also prints the following which is mostly from your library:

    consumer_partition_integration_test.go:136: Waiting for group to finish
time="2020-09-22T09:58:38+02:00" level=info msg="Connecting to broker" remote_addr="pulsar://localhost:6650"
time="2020-09-22T09:58:38+02:00" level=info msg="TCP connection established" local_addr="[::1]:55076" remote_addr="pulsar://localhost:6650"
time="2020-09-22T09:58:38+02:00" level=info msg="Connection is ready" local_addr="[::1]:55076" remote_addr="pulsar://localhost:6650"

Yet the consumer is stuck and doesn't proceed with message consumption. May it be the broker not sending the messages? As you can see from the video I'm using the latest image (i.e. streamnative/pulsar-all:2.6.1-sn-3) as per your suggestion.

I also raised the max unacked messages per consumer and per subscription by doing bin/pulsar-admin namespaces set-max-unacked-messages-per-consumer -c 99999999 public/default and bin/pulsar-admin namespaces set-max-unacked-messages-per-subscription -c 99999999 public/default. In fact in the video we can see that blockedSubscriptionOnUnackedMsgs is false.

stats

"subscription-name-2e970542c9706d02" : {
      "msgRateOut" : 0.0,
      "msgThroughputOut" : 0.0,
      "bytesOutCounter" : 0,
      "msgOutCounter" : 0,
      "msgRateRedeliver" : 0.0,
      "chuckedMessageRate" : 0,
      "msgBacklog" : 98316,
      "msgBacklogNoDelayed" : 98316,
      "blockedSubscriptionOnUnackedMsgs" : false,
      "msgDelayed" : 0,
      "unackedMessages" : 0,
      "type" : "Key_Shared",
      "msgRateExpired" : 0.0,
      "lastExpireTimestamp" : 0,
      "lastConsumedFlowTimestamp" : 1600761458710,
      "lastConsumedTimestamp" : 0,
      "lastAckedTimestamp" : 0,
      "consumers" : [ ], <-- NO CONSUMERS HERE
      "isDurable" : true,
      "isReplicated" : false
    },

stats-internal

    "subscription-name-2e970542c9706d02" : {
      "markDeletePosition" : "10:1614",
      "readPosition" : "10:1615",
      "waitingReadOp" : false,
      "pendingReadOps" : 0,
      "messagesConsumedCounter" : 1684,
      "cursorLedger" : 12,
      "cursorLedgerLastEntry" : 1,
      "individuallyDeletedMessages" : "[(10:1615..10:1683],(10:1687..10:1688]]",
      "lastLedgerSwitchTimestamp" : "2020-09-22T07:57:38.505Z",
      "state" : "Open",
      "numberOfEntriesSinceFirstNotAckedMessage" : 1,
      "totalNonContiguousDeletedMessagesRange" : 2,
      "properties" : { }
    },

@jiazhai

jiazhai commented Sep 22, 2020

Copy link
Copy Markdown
Member

Try to provide a brief summary for the deadlock.

In pulsar/internal/connection.go we have 2 channels, closeCh and incomingRequestsCh, which are init as

closeCh:            make(chan interface{}),
incomingRequestsCh: make(chan *request, 10),    < === buffer limited

incomingRequestsCh is a buffered channel with length 10.

image
image

when connection is closed, method func (c *connection) Close() will call func (c *connection) TriggerClose(), which closed closeCh by close(c.closeCh),
image
image

this will cause go routine (in connection.go.run()) exit, then no one will fetch messages in incomingRequestsCh. incomingRequestsCh, whose buffer length is 10, will be filled with incoming requests by method func (c *connection) SendRequestNoWait(req *pb.BaseCommand),
image
image

Then the 10th request, it will be blocked,
image

As show in above dump thread, internalAck in runEventsLoop is blocked, then other requests like re-connection will not get handled, and caused "consumers" : [ ], <-- NO CONSUMERS HERE
image

Backing to func (c *connection) Close(), the connection handler.ConnectionClosed() will hang, because channel pc.eventsCh is blocked as ackRequest is waiting.
image
image

@zzzming

zzzming commented Sep 25, 2020

Copy link
Copy Markdown
Contributor

@jiazhai How about move the consumer and producer listener's ConnectionClosed() code https://github.com/apache/pulsar-client-go/blob/master/pulsar/internal/connection.go#L763

to https://github.com/apache/pulsar-client-go/blob/master/pulsar/internal/connection.go#L372

I hope that can guarantee close of handlers. It becomes something like

	go func() {
		for {
			select {
			case <-c.closeCh:
				c.log.Info("1st go loop closeCh")
				consumerHandlers := make(map[uint64]ConsumerHandler)
				c.consumerHandlersLock.RLock()
				for id, handler := range c.consumerHandlers {
					consumerHandlers[id] = handler
				}
				c.consumerHandlersLock.RUnlock()

				for _, handler := range consumerHandlers {
					handler.ConnectionClosed()
				}

				return

			case req := <-c.incomingRequestsCh:
				if req == nil {
					return // TODO: this never gonna be happen
				}
				c.internalSendRequest(req)
			}
		}
	}()

wolfstudy pushed a commit that referenced this pull request Oct 9, 2020
Fixes #366

### Motivation

In current code of `pulsar/internal/connection.go` we have 2 channels, closeCh and incomingRequestsCh. when the connection closes, the current mis-use of these 2 channels may have a deadlock. 
PR #366 has detailed steps to reproduce and the root cause [analysis](#366 (comment)) .
This PR tries to fix the deadlock.

### Modifications
- make the close logic independent, not in the same loop of normal events handling.
- when the connection closed, handle the existing requests in the channel and return an error to avoid deadlock.

### Verifying this change
passed the tests in #366 
current ut passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants