azure-sdk-for-python icon indicating copy to clipboard operation
azure-sdk-for-python copied to clipboard

Possible memory leak receiving messages in servicebus 0.50.3

Open andrea-cassioli-maersk opened this issue 5 years ago • 22 comments

  • Package Name: servicebus
  • Package Version: 0.50.3
  • Operating System: Linux Alpine/Debian, OSX
  • Python Version: 3.8.6

Describe the bug Apparently memory leaks from receiving messages.

To Reproduce Steps to reproduce the behavior:

  1. create a queue client
  2. create a receiver
  3. receive (and ignore) a message
  4. back to point 1

Expected behavior No relevant memory usage increase.

Code

Here a sample of the code I use to replicate. Notice I am not processing messages and I am running against an empty queue.

import os

from azure.servicebus import ServiceBusClient, ReceiveSettleMode


if __name__ == '__main__':

    service_bus_client = ServiceBusClient(service_namespace=os.environ['AZURE_BUS_NAMESPACE'],
                                          shared_access_key_name=os.environ['AZURE_BUS_KEY_NAME'],
                                          shared_access_key_value=os.environ['AZURE_BUS_KEY_VALUE'])
    queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])

    for _ in range (1000000):
        # ofc I could create the queue once, but this is closer to my actual code
        queue = service_bus_client.get_queue(queue_name=queue_name)
        with queue.get_receiver(mode=ReceiveSettleMode.PeekLock) as receiver:
            msg_batch = receiver.fetch_next(max_batch_size=1, timeout=1)
            # notice I do not really expect to receive any message, printing just to keep it busy....
            print(msg_batch)

Additional context I know that I am not running on the latest version, but I have the feeling the issue might be in the uamqp layer and therefore of interest for also the new versions as well.

andrea-cassioli-maersk avatar Dec 10 '20 09:12 andrea-cassioli-maersk

hey @andrea-cassioli-maersk , thanks for reporting.

Could you also share the version of uamqp that you use? (pip show uamqp would give version number)

yunhaoling avatar Dec 10 '20 21:12 yunhaoling

Here it is

08:29 $ pip3.8 show uamqp 
Name: uamqp
Version: 1.2.12
Summary: AMQP 1.0 Client Library for Python

andrea-cassioli-maersk avatar Dec 11 '20 07:12 andrea-cassioli-maersk

A bit more investigation. Running

import os
from azure.servicebus import ServiceBusClient, ReceiveSettleMode

if __name__ == '__main__':
    service_bus_client = ServiceBusClient(service_namespace=os.environ['AZURE_BUS_NAMESPACE'],
                                          shared_access_key_name=os.environ['AZURE_BUS_KEY_NAME'],
                                          shared_access_key_value=os.environ['AZURE_BUS_KEY_VALUE'])
    queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
    for _ in range(1000000):
        queue = service_bus_client.get_queue(queue_name=queue_name)

        with queue.get_receiver(mode=ReceiveSettleMode.PeekLock) as receiver:

                msg_batch = receiver.fetch_next(max_batch_size=1, timeout=1)
                # notice I do not really expect to receive any message, printing just to keep it busy....
                print(msg_batch)

Still I see memory increase. However, the following code runs clean:

import os

from azure.servicebus import ServiceBusClient, ReceiveSettleMode

if __name__ == '__main__':

    service_bus_client = ServiceBusClient(service_namespace=os.environ['AZURE_BUS_NAMESPACE'],
                                          shared_access_key_name=os.environ['AZURE_BUS_KEY_NAME'],
                                          shared_access_key_value=os.environ['AZURE_BUS_KEY_VALUE'])
    queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
    queue = service_bus_client.get_queue(queue_name=queue_name)

    with queue.get_receiver(mode=ReceiveSettleMode.PeekLock) as receiver:
        for _ in range(1000000):

            msg_batch = receiver.fetch_next(max_batch_size=1, timeout=1)
            # notice I do not really expect to receive any message, printing just to keep it busy....
            print(msg_batch)

So I think the receiver must be the reason.

I have tried version 7 and I see similar behaviour. For instance

import os
from azure.servicebus import ServiceBusClient
from azure.servicebus.exceptions import OperationTimeoutError

if __name__ == '__main__':
    queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
    with ServiceBusClient.from_connection_string(conn_str=os.environ['AZURE_BUS_CONN_STR']) as service_bus_client:
        for i in range(100000):
            with service_bus_client.get_queue_receiver(queue_name=queue_name) as receiver:
                try:
                    received_msgs = receiver.peek_messages(max_message_count=1, timeout=10)
                    print(i, received_msgs)
                except OperationTimeoutError:
                    pass

shows a slow memory increase, but

import os
from azure.servicebus import ServiceBusClient
from azure.servicebus.exceptions import OperationTimeoutError

if __name__ == '__main__':
    queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
    with ServiceBusClient.from_connection_string(conn_str=os.environ['AZURE_BUS_CONN_STR']) as service_bus_client:
        with service_bus_client.get_queue_receiver(queue_name=queue_name) as receiver:
            for i in range(100000):
                try:
                    received_msgs = receiver.peek_messages(max_message_count=1, timeout=10)
                    print(i, received_msgs)
                except OperationTimeoutError:
                    pass

it is again clean.

andrea-cassioli-maersk avatar Dec 16 '20 11:12 andrea-cassioli-maersk

Hi guys, any thoughts?

andrea-cassioli-maersk avatar Dec 21 '20 12:12 andrea-cassioli-maersk

hey @andrea-cassioli-maersk , sorry it's a bit crowded recently and I really appreciate your debugging process.

based on what you provide, I think it's either the connection or client in uamqp that causes the issue. As you may know the uamqp library is built on top of c libraries. It's could be the cython binding layer or the c libraries leaking the memory.

will you get memory leak if you only get receiver not try to establish the connection? (suppose you're using v5)

with ServiceBusClient.from_connection_string(conn_str=os.environ['AZURE_BUS_CONN_STR']) as service_bus_client:
    for i in range(100000):
        service_bus_client.get_queue_receiver(queue_name=queue_name)

yunhaoling avatar Dec 21 '20 20:12 yunhaoling

Thanks @yunhaoling , just tried what you proposed on v7 (did you mean 0.5?

import os
from azure.servicebus import ServiceBusClient

if __name__ == '__main__':
    queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
    with ServiceBusClient.from_connection_string(conn_str=os.environ['AZURE_BUS_CONN_STR']) as service_bus_client:
        while True:
            service_bus_client.get_queue_receiver(queue_name=queue_name)

and the memory just explodes!

However

import os
import time
from azure.servicebus import ServiceBusClient
from azure.servicebus.exceptions import OperationTimeoutError

if __name__ == '__main__':
    queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
    with ServiceBusClient.from_connection_string(conn_str=os.environ['AZURE_BUS_CONN_STR']) as service_bus_client:
        while True:
            with service_bus_client.get_queue_receiver(queue_name=queue_name) as r:
                pass

seems stable with a tiny increase in memory consumption.

andrea-cassioli-maersk avatar Dec 22 '20 08:12 andrea-cassioli-maersk

hey @andrea-cassioli-maersk , may I ask how long do you run the program with the code?

import os
import time
from azure.servicebus import ServiceBusClient
from azure.servicebus.exceptions import OperationTimeoutError

if __name__ == '__main__':
    queue_name = '-'.join([os.environ['AZURE_BUS_QUEUE'], 'low'])
    with ServiceBusClient.from_connection_string(conn_str=os.environ['AZURE_BUS_CONN_STR']) as service_bus_client:
        while True:
            with service_bus_client.get_queue_receiver(queue_name=queue_name) as r:
                pass

I'm wondering whether it's because running not long enough that the garbage collection doesn't kick in yet

yunhaoling avatar Dec 23 '20 18:12 yunhaoling

I tried running that code in a docker container for say 2 hours and the memory increased several Mb. Not sure if the GC should already kick in already.

andrea-cassioli-maersk avatar Dec 28 '20 11:12 andrea-cassioli-maersk

BTW, my application runs for days and there I see the memory going up to fill Gbytes. This behaviour started when we moved to 0.50.

andrea-cassioli-maersk avatar Jan 11 '21 13:01 andrea-cassioli-maersk

Any feedback? It would be good to know if it is an issue in 0.50.X and whether upgrading to 7 will solve the issue.

andrea-cassioli-maersk avatar Jan 14 '21 13:01 andrea-cassioli-maersk

hey @andrea-cassioli-maersk , confirming the issue on linux -- I ran the code on a linux vm over 24 hrs and the memory did increase constantly. thanks for your instructions! at least we know that the leak happens during the connection establishment/shutdown process. I believe it's an issue in the uamqp, I need further investigation into the underlying module like Cython, C, that's the place where leaks most likely could take place.

yunhaoling avatar Jan 14 '21 18:01 yunhaoling

Hey @yunhaoling thanks for confirming the issue! Indeed we spot it on Linux Docker containers and then confirmed on Mac as well.

Do you believe upgrading to version 7 would solve, or at least mitigate?

andrea-cassioli-maersk avatar Jan 15 '21 07:01 andrea-cassioli-maersk

@andrea-cassioli-maersk , I don't think so as the leak happened in uamqp, but I would strongly recommend you to upgrade v7, as we v0.50 is deprecated.

I have found a potential leaking place in the cython layer https://github.com/Azure/azure-uamqp-python/blob/b7de7bab1b8d0b2457ff77bd3b3188efb5c1b065/src/cbs.pyx#L26-L37 where a C string is not deallocated properly, will try something to see if fixing this one could mitigate the leak issue.

yunhaoling avatar Jan 20 '21 19:01 yunhaoling

@yunhaoling thanks for the clarification, we will migrate to 7 soon. Please keep me posted on the leak.

andrea-cassioli-maersk avatar Jan 21 '21 07:01 andrea-cassioli-maersk

Just to confirm, the memory leak is definitely affecting version 7. We update our code and we are experiencing the same issue.

andrea-cassioli-maersk avatar Feb 16 '21 10:02 andrea-cassioli-maersk

This leak is affecting us too. It's not good for it's to be leaking memory like this. It could well be in the underlying C libraries somewhere.

ian-young-sydney avatar Feb 21 '21 23:02 ian-young-sydney

hey folks, I have some free cycles this week and will dig deep into the underlying C libraries to see if can find anything.

yunhaoling avatar Feb 23 '21 19:02 yunhaoling

posting updates for the memory leak issue:

it seems like the memory happens during the session establishment process in the cython layer, in the on_link_attached callback source and target from the c module would be cloned (reference count + 1), while I didn't find any code that destroy those two cloned variables (reference count -1).

more details could be found in my PR: https://github.com/Azure/azure-uamqp-python/pull/215.

I'm still testing and finding the right solution for it, thanks for your patience

yunhaoling avatar Mar 04 '21 12:03 yunhaoling

hey folks, we have released uamqp v1.4.0 which fixed the memory leak in uamqp cython layer. please update the uamqp via pip install uamqp --upgrade to try out the fix.

I have validated the fix by valgrind (which is a C memory debug tool), no memory leaks on my side. (The memory usage might grow but after a while python GC would kick in).

I'm closing the issue now. feel free to reopen if you still run encounter the issue, thanks for your patience!

also details could be found here in the PR: https://github.com/Azure/azure-uamqp-python/pull/230

yunhaoling avatar May 03 '21 20:05 yunhaoling

Hi @yunhaoling, it seems there are still some memory issues in version 7.2.0 of the service bus python package.
I ran a similar version to the script below for around 6 hours, explicitly calling the GC every few iterations and the memory just kept growing.

        while passed_secs < time_limit_secs:
            # ofc I could create the queue once, but this is closer to my actual code
            with service_bus_client.get_queue_receiver(queue_name=queue_name) as receiver:
                msg_batch = receiver.receive_messages(max_message_count=1,
                                                    max_wait_time=3)
                # notice I do not really expect to receive any message, printing just to keep it busy....
                print(msg_batch)
                if cnt % 100 == 0:
                    print("Forcing GC to run")
                    gc.collect()

Below you can see also a plot of how the memory grows: single_service_bus

When instead I initialized the service bus client within the while loop above, we see that the memory increases at a much slower rate: restart_service_bus

Could you check if you see the same at your end?

alberto-delgado-maersk avatar Jun 04 '21 13:06 alberto-delgado-maersk