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

AttributeError: 'NoneType' object has no attribute 'create_sender_link'

Open sudharsan2020 opened this issue 3 years ago • 13 comments

  • Package Name: azure-servicebus
  • Package Version: 7.11.3
  • Operating System:Linux
  • Python Version: 3.11.5

Describe the bug Rarely I am receiving this error AttributeError with this traceback when trying to send scheduled messages to Servicebus subscription :

 Function.servicebus_triggerUser[0]
      Unexpected error occurred (AttributeError("'NoneType' object has no attribute 'create_sender_link'")). Handler shutting down.
      Traceback (most recent call last):
        File "/home/appuser/.local/lib/python3.11/site-packages/azure/servicebus/_base_handler.py", line 421, in _do_retryable_operation
          return operation(**kwargs)
                 ^^^^^^^^^^^^^^^^^^^
        File "/home/appuser/.local/lib/python3.11/site-packages/azure/servicebus/_base_handler.py", line 500, in _mgmt_request_response
          self._open()
        File "/home/appuser/.local/lib/python3.11/site-packages/azure/servicebus/_servicebus_sender.py", line 265, in _open
          while not self._handler.client_ready():
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/home/appuser/.local/lib/python3.11/site-packages/azure/servicebus/_pyamqp/client.py", line 406, in client_ready
          if not self._client_ready():
                 ^^^^^^^^^^^^^^^^^^^^
        File "/home/appuser/.local/lib/python3.11/site-packages/azure/servicebus/_pyamqp/client.py", line 583, in _client_ready
          self._link = self._session.create_sender_link(
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      AttributeError: 'NoneType' object has no attribute 'create_sender_link'

I have the azure_service_bus_topic_client.schedule_messages() method wrapped with tenacity retrying which retries the operation onServiceBusError, however, this fails when AttributeError is raised.

To Reproduce Steps to reproduce the behavior:

  1. With schedule_messages to send scheduled messages to the Service Bus topic subscription

Expected behavior The ServiceBusClient should successfully send messages without any exceptions

Additional context

  1. Deployed to AKS Dockerized Function app - Python 3.11
  2. Service Bus Topic subscription lock duration set to 5 minutes

sudharsan2020 avatar Nov 06 '23 10:11 sudharsan2020

Thank you for the feedback @sudharsan2020 . We will investigate and get back to you asap.

Could you also provide some debug logs and traces that can help us troubleshoot ? If you can share some of your code as well that would be great.

Turning on debug logs

servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR, logging_enable=True)

import logging
import sys

logger = logging.getLogger('azure.servicebus')
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

kashifkhan avatar Nov 06 '23 15:11 kashifkhan

@kashifkhan Please find the code to send the results to the service bus trigger

Logic

def send_scheduled_message(
        request_model: RequestModel,
):
    azure_service_bus_client.send_scheduled_message(
        pay_load=request_model.model_dump(),
        subscription_filter=SUBSCRIPTION_NAME,
        schedule_enqueue_time=`0,
    )

Wrapper code to send scheduled message

    def send_scheduled_message(
            self, pay_load: dict, subscription_filter: str, schedule_enqueue_time: int, **kwargs
    ) -> None:
        """
        Send a single message with a scheduled enqueue time to a service or endpoint.

        Args:
            pay_load (dict): A dictionary containing the message payload.
            subscription_filter (str): The subscription filter to apply for the message.
            schedule_enqueue_time (int): The scheduled enqueue time in seconds.
            **kwargs: Additional keyword arguments that can be passed to customize the message sending process.

        Returns:
            None: This function does not return a value.

        """
        try:
            for attempt in Retrying(**self._tenacity_retry_options):
                with attempt:
                    # Construct a message
                    service_bus_msg = ServiceBusMessage(
                        json.dumps(pay_load),
                        subject=subscription_filter,
                        application_properties=kwargs.get("application_properties", None),
                        custom_properties=kwargs.get("custom_properties", None),
                    )

                    scheduled_time_utc = datetime.now(timezone.utc) + timedelta(seconds=schedule_enqueue_time)

                    # Send a scheduled message
                    _ = self.azure_service_bus_topic_client.schedule_messages(
                        service_bus_msg, scheduled_time_utc
                    )

        except RetryError:
            raise

Request model

We are using Pydantic for the data models

class RequestModel(BaseModel):
    j_id: str
    d_id: str
    a_id: str
    auth_key: str
    flag: bool
    id: Optional[str] = Field(default=None)
    field_mappings: Optional[List[str]] = Field(default=None)
    count: Optional[int] = Field(default=1)

The issue doesn't occur if we are not sending application properties. The issue persists when we are sending request_model.model_dump() as application_properties in the Service Bus Message

sudharsan2020 avatar Nov 07 '23 10:11 sudharsan2020

Thank you for the details @sudharsan2020 . Will update once we can repro on our end. Are you by any chance using any threading in your application?

kashifkhan avatar Nov 07 '23 14:11 kashifkhan

@kashifkhan No we aren't using any threading. The application is deployed as an Azure Service Bus Trigger as a Docker instance.

sudharsan2020 avatar Nov 07 '23 14:11 sudharsan2020

I have been facing the same error. We are using an Azure Container Group instance, and it restarts whenever it encounters this error, which seems to happen randomly. We can see this behaviour in the Log Analytics Workspace.

gabrielmdesidera avatar Nov 23 '23 14:11 gabrielmdesidera

@kashifkhan Do you've any update on the issue?

sudharsan2020 avatar Nov 29 '23 08:11 sudharsan2020

I have the same error, but I'm using gunicorn (workers 4), fastapi and async service bus.

kkzetAM avatar Dec 05 '23 07:12 kkzetAM

I tried removing the application_properties while sending the service bus message and the exception wasn't thrown. My application property had a Pydantic model of List type which could've possibly caused the issue. However after removing the application_properties, I didn't encounter the error

sudharsan2020 avatar Dec 05 '23 07:12 sudharsan2020

Hi @sudharsan2020, will you be able to provide some debug and network logs using the following snippet

We are interested to see why not sending in any application properties stops the issue. The logs will help us see whats happening over the wire and behind the scenes and pinpoint the source of the problem


import logging
import sys

logger = logging.getLogger('azure.servicebus')
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)
servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR, logging_enable=True)

kashifkhan avatar Dec 05 '23 20:12 kashifkhan

Hi @sudharsan2020. Thank you for opening this issue and giving us the opportunity to assist. To help our team better understand your issue and the details of your scenario please provide a response to the question asked above or the information requested above. This will help us more accurately address your issue.

github-actions[bot] avatar Dec 05 '23 20:12 github-actions[bot]

Hi @sudharsan2020, we're sending this friendly reminder because we haven't heard back from you in 7 days. We need more information about this issue to help address it. Please be sure to give us your input. If we don't hear back from you within 14 days of this comment the issue will be automatically closed. Thank you!

github-actions[bot] avatar Dec 12 '23 21:12 github-actions[bot]

Hi @kashifkhan, we have encountered the same issue here where we got AttributeError: 'NoneType' object has no attribute 'create_sender_link' without stopping application properties.

Is there any update on the issue? thx!

GanniPiece avatar Feb 21 '24 01:02 GanniPiece

@kashifkhan This is the only error message I could see after enabling the debug logs.

Failed to initiate the connection due to exception: timed out Error condition: amqp:socket-error.

rawStack:

Traceback (most recent call last):
  File "/home/appuser/.local/lib/python3.11/site-packages/opentelemetry/trace/__init__.py", line 573, in use_span
    yield span
  File "/home/appuser/.local/lib/python3.11/site-packages/azure/servicebus/_common/tracing.py", line 123, in send_trace_context_manager
    yield
  File "/home/appuser/.local/lib/python3.11/site-packages/azure/servicebus/_servicebus_sender.py", line 357, in schedule_messages
    return self._mgmt_request_response_with_retry(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/appuser/.local/lib/python3.11/site-packages/azure/servicebus/_base_handler.py", line 550, in _mgmt_request_response_with_retry
    return self._do_retryable_operation(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/appuser/.local/lib/python3.11/site-packages/azure/servicebus/_base_handler.py", line 436, in _do_retryable_operation
    raise last_exception from None
azure.servicebus.exceptions.ServiceBusConnectionError: Failed to initiate the connection due to exception: timed out Error condition: amqp:socket-error.

Appinsights:

image

@GanniPiece We were able to reduce the exceptions significantly after implementing the below code to get topic_sender when it becomes None.

class AzureServiceBusClient:
    def __init__(self, topic_name: str, logger: Logger) -> None:
        self.azure_service_bus_client = ServiceBusClient.from_connection_string(
            os.environ["ServiceBusConnectionString"], logging_enable=True
        )
        self.topic_name = topic_name

        self.logger = logger
        self._tenacity_retry_options = self._get_tenacity_retry_options()
        self.azure_service_bus_topic_client: ServiceBusSender | None = None

    def _get_topic_sender(self) -> ServiceBusSender:
        """
        Returns the topic sender client
        :return: ServiceBus topic sender
        """
        if self.azure_service_bus_topic_client is not None:
            return self.azure_service_bus_topic_client
        return self.azure_service_bus_client.get_topic_sender(
            topic_name=self.topic_name,
        )

Earlier we were using the get_topic_sender in the __init__ which caused much higher failure rates than the current code. Please try and let me know the feedback.

The code was adapted from: https://github.com/MulliganFunding/boilermaker-servicebus/blob/main/boilermaker/service_bus.py#L49

sudharsan2020 avatar Mar 09 '24 11:03 sudharsan2020