opentelemetry-python icon indicating copy to clipboard operation
opentelemetry-python copied to clipboard

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

Open wbzdssm opened this issue 3 years ago • 3 comments

Describe your environment runtime: python3.6.1; sdk version: 1.7.1

Steps to reproduce Describe exactly how to reproduce the error. Include a code sample if applicable.

What is the expected behavior? What did you expect to see? I use python3.6.1 runtime; But i have a problem,

File "index.py", line 17, in <module>
with tracer.start_as_current_span("foo"):
File "/opt/python3.6.1/lib/python3.6/contextlib.py", line 82, in enter
return next(self.gen)
File "/opt/python3.6.1/lib/python3.6/site-packages/opentelemetry/sdk/trace/init.py", line 980, in start_as_current_span
set_status_on_exception=set_status_on_exception,
File "/opt/python3.6.1/lib/python3.6/site-packages/opentelemetry/sdk/trace/init.py", line 1003, in start_span
context
File "/opt/python3.6.1/lib/python3.6/site-packages/opentelemetry/trace/propagation/init.py", line 48, in get_current_span
span = get_value(_SPAN_KEY, context=context)
File "/opt/python3.6.1/lib/python3.6/site-packages/opentelemetry/context/init.py", line 96, in get_value
return context.get(key) if context is not None else get_current().get(key)
File "/opt/python3.6.1/lib/python3.6/site-packages/opentelemetry/context/init.py", line 67, in wrapper
return func(args, *kwargs) # type: ignore[misc]
File "/opt/python3.6.1/lib/python3.6/site-packages/opentelemetry/context/init.py", line 131, in get_current
return _RUNTIME_CONTEXT.get_current() # type:ignore
AttributeError: 'NoneType' object has no attribute 'get_current'

my code is:

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
BatchSpanProcessor,
ConsoleSpanExporter,
)

provider = TracerProvider()
processor = BatchSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

tracer = trace.get_tracer(name)

with tracer.start_as_current_span("foo"):
with tracer.start_as_current_span("bar"):
with tracer.start_as_current_span("baz"):
print("Hello world from OpenTelemetry Python!")

What is the actual behavior? What did you see instead?

Additional context Add any other context about the problem here. https://opentelemetry-python.readthedocs.io/en/stable/getting-started.html

wbzdssm avatar Nov 24 '21 07:11 wbzdssm

I spent sometime looking into this and found that there was an import error. typing.NoReturn is newly added in 3.6.2 which was the reason for error. Can you try with 3.6.2 or later?

srikanthccv avatar Nov 25 '21 13:11 srikanthccv

I ran into this on python 3.10.0 and opentelemetry-sdk 1.10.0, upgrading to 1.11.0 seems to have resolved the issue.

matschaffer avatar Apr 21 '22 05:04 matschaffer

I ran into this on python 3.10.0 and opentelemetry-sdk 1.10.0, upgrading to 1.11.0 seems to have resolved the issue.

@wbzdssm can you please confirm?

ocelotl avatar Apr 21 '22 14:04 ocelotl

I am seeing this issue using Python 3.8 and opentelemetry 1.18.0

kwrobert avatar Jun 07 '23 15:06 kwrobert

Same with me. Python 3.8 and opentelemetry 1.18.0

christywald avatar Jun 15 '23 07:06 christywald

I was able to track this down to the fact that the opentelemetry-context entry point was missing from my environment, which is what is used to set up the _RUNTIME_CONTEXT global variable. If the entry point isn't found and the OTEL_PYTHON environment variable is not set, the code that sets up the runtime context will log an error and leave _RUNTIME_CONTEXT set to None, which downstream code does not handle gracefully

kwrobert avatar Jun 15 '23 13:06 kwrobert

Could those experiencing this issue in 3.8 and the latest OpenTelemetry provide a detailed description of the steps that you have taken to reproduce this? Looks like @srikanthccv 's suggestion is a bit outdated so providing an updated repro would be helpful in debugging.

lzchen avatar Jun 15 '23 16:06 lzchen

@kwrobert, any chance you are using some application server like gunicorn/uwsgi in your code? And what is the worker class used?

@lzchen, one way to (non-)deterministically reproduce this is to use gevent, gthread, tornado as worker class for gunicorn. These steps are unrelated to this issue, but the issue is the same, i.e. RUNTIME_CONTEXT is not set sometimes and throws AttributeError.

srikanthccv avatar Jun 16 '23 11:06 srikanthccv

I am facing the same issue on Python 3.10, opentelemetry-sdk==1.20.0 on a python wsgi service. What to set as the value for OTEL_PYTHON_CONTEXT env var ?

amrithajayadev avatar Sep 11 '23 14:09 amrithajayadev

Interesting. Since we already assume the default context is contextvars_context in the api and this is the value we attempt to load, should we simply load the default if there is any exception thrown, since we do rely on the context existing downstream.

@ocelotl @aabmass @srikanthccv wdyt

lzchen avatar Sep 11 '23 18:09 lzchen

should we simply load the default if there is any exception thrown

I think this will be an undesirable thing to do if the given context provider has a different implementation and can't be substituted by default? From what I understood, the contextvars doesn't work or play well with the gevent, tornado, eventlet, etc... and this issue primarily occurs when people use one of them. I maybe wrong but I believe the right fix would be to provide a context implementation (ThreadLocalContext?) that works when these libraries are used.

srikanthccv avatar Sep 14 '23 18:09 srikanthccv

@srikanthccv there is something weird here, this is our current code:

                default_context = "contextvars_context"

                configured_context = environ.get(
                    OTEL_PYTHON_CONTEXT, default_context
                )  # type: str
                try:

                    _RUNTIME_CONTEXT = next(  # type: ignore
                        iter(  # type: ignore
                            entry_points(  # type: ignore
                                group="opentelemetry_context",
                                name=configured_context,
                            )
                        )
                    ).load()()

                except Exception:  # pylint: disable=broad-except
                    logger.exception(
                        "Failed to load context: %s", configured_context
                    )
        return func(*args, **kwargs)  # type: ignore[misc]

    return typing.cast(_F, wrapper)  # type: ignore[misc]

It looks to me that for this error to happen, OTEL_PYTHON_CONTEXT would need to be set to a value for which there is no corresponding entry point. I'm not saying that contextvars works or plays well with gevent, tornado, eventlet, etc. but we would see another kind of error in that case.

BTW, for anyone who can reproduce this issue, please paste the complete error output, not just the traceback for the AttributeError. In this case the exception message from logger.exception is valuable information regarding the original exception that caused this error.

ocelotl avatar Oct 01 '23 12:10 ocelotl

Hello there, I'm also having the same issue when packaging opentelemetry with PyInstaller (latest version 6.4.0). I've been running tutorial for building python application using the Microsoft Graph SDK and trying their example applications, which I would like to distribute to someone else in my team via executable file. Except that upon running the executable on my own machine, I get this full traceback to opentelemetry choking on that missing env var:

$ dist/main/main.exe
Python Graph Tutorial

Failed to load context: contextvars_context
Traceback (most recent call last):
  File "opentelemetry\context\__init__.py", line 60, in wrapper
StopIteration
Traceback (most recent call last):
  File "main.py", line 112, in <module>
    asyncio.run(main())
  File "asyncio\runners.py", line 190, in run
  File "asyncio\runners.py", line 118, in run
  File "asyncio\base_events.py", line 653, in run_until_complete
  File "main.py", line 20, in main
    await greet_user(graph)
  File "main.py", line 58, in greet_user
    user = await graph.get_user()
           ^^^^^^^^^^^^^^^^^^^^^^
  File "graph.py", line 52, in get_user
    user = await self.user_client.me.get(request_configuration=request_config)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "msgraph\generated\users\item\user_item_request_builder.py", line 157, in get
  File "kiota_http\httpx_request_adapter.py", line 167, in send_async
  File "kiota_http\httpx_request_adapter.py", line 494, in get_http_response_message
  File "kiota_http\httpx_request_adapter.py", line 139, in _start_local_tracing_span
  File "opentelemetry\trace\propagation\__init__.py", line 34, in set_span_in_context
  File "opentelemetry\context\__init__.py", line 122, in set_value
  File "opentelemetry\context\__init__.py", line 73, in wrapper
  File "opentelemetry\context\__init__.py", line 137, in get_current
AttributeError: 'NoneType' object has no attribute 'get_current'
[28728] Failed to execute script 'main' due to unhandled exception!

In pure python (eg. python main.py) there is no issue with opentelemetry:

$ python main.py
Python Graph Tutorial

To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code ABCD1234 to authenticate.
Hello, Francois XXX
Email: [email protected]

So what options do I have? What about OTEL_PYTHON_CONTEXT, can I give it a proper value to work this around? I tried to feed it manually a few values with no success.

Thanks for the help!

eeintech avatar Mar 07 '24 14:03 eeintech

@ocelotl Sorry to bug you directly but I would really appreciate some insight on how to solve this bug as I cannot package my application and have not found any workaround 😬

eeintech avatar Mar 19 '24 19:03 eeintech

@eeintech sorry for the late reply, investigating...

ocelotl avatar Mar 20 '24 16:03 ocelotl

@eeintech please try with these changes: #3797

I am trying to find out why the contextvars_context entry point is not being found in your case.

ocelotl avatar Mar 20 '24 17:03 ocelotl

@ocelotl I tried it and running it pure python (no packaging) I now get the same error, here's the full trace:

Windows
sys.version_info(major=3, minor=11, micro=6, releaselevel='final', serial=0)
EntryPoints((EntryPoint(name='contextvars_context', value='opentelemetry.context.contextvars_context:ContextVarsRuntimeContext', group='opentelemetry_context'),))
Failed to load context: contextvars_context
Traceback (most recent call last):
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\opentelemetry\context\__init__.py", line 76, in wrapper
    raise Exception(the_entry_points)
Exception: EntryPoints((EntryPoint(name='contextvars_context', value='opentelemetry.context.contextvars_context:ContextVarsRuntimeContext', group='opentelemetry_context'),))
Traceback (most recent call last):
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\main.py", line 112, in <module>
    asyncio.run(main())
  File "C:\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\main.py", line 20, in main
    await greet_user(graph)
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\main.py", line 58, in greet_user
    user = await graph.get_user()
           ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\graph.py", line 52, in get_user
    user = await self.user_client.me.get(request_configuration=request_config)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\msgraph\generated\users\item\user_item_request_builder.py", line 157, in get
    return await self.request_adapter.send_async(request_info, User, error_mapping)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\kiota_http\httpx_request_adapter.py", line 178, in send_async
    response = await self.get_http_response_message(request_info, parent_span)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\kiota_http\httpx_request_adapter.py", line 513, in get_http_response_message
    _get_http_resp_span = self._start_local_tracing_span(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\kiota_http\httpx_request_adapter.py", line 150, in _start_local_tracing_span
    _context = trace.set_span_in_context(parent_span)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\opentelemetry\trace\propagation\__init__.py", line 34, in set_span_in_context
    ctx = set_value(_SPAN_KEY, span, context=context)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\opentelemetry\context\__init__.py", line 140, in set_value
    context = get_current()
              ^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\opentelemetry\context\__init__.py", line 91, in wrapper
    return func(*args, **kwargs)  # type: ignore[misc]
           ^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\opentelemetry\context\__init__.py", line 155, in get_current
    return _RUNTIME_CONTEXT.get_current()  # type:ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'get_current'

EDIT: This is the traceback when packaging the app.

Windows
sys.version_info(major=3, minor=11, micro=6, releaselevel='final', serial=0)
EntryPoints(())
Failed to load context: contextvars_context
Traceback (most recent call last):
  File "opentelemetry\context\__init__.py", line 76, in wrapper
Exception: EntryPoints(())
Traceback (most recent call last):
  File "main.py", line 112, in <module>
    asyncio.run(main())
  File "asyncio\runners.py", line 190, in run
  File "asyncio\runners.py", line 118, in run
  File "asyncio\base_events.py", line 653, in run_until_complete
  File "main.py", line 20, in main
    await greet_user(graph)
  File "main.py", line 58, in greet_user
    user = await graph.get_user()
           ^^^^^^^^^^^^^^^^^^^^^^
  File "graph.py", line 52, in get_user
    user = await self.user_client.me.get(request_configuration=request_config)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "msgraph\generated\users\item\user_item_request_builder.py", line 157, in get
  File "kiota_http\httpx_request_adapter.py", line 178, in send_async
  File "kiota_http\httpx_request_adapter.py", line 513, in get_http_response_message
  File "kiota_http\httpx_request_adapter.py", line 150, in _start_local_tracing_span
  File "opentelemetry\trace\propagation\__init__.py", line 34, in set_span_in_context
  File "opentelemetry\context\__init__.py", line 140, in set_value
  File "opentelemetry\context\__init__.py", line 91, in wrapper
  File "opentelemetry\context\__init__.py", line 155, in get_current
AttributeError: 'NoneType' object has no attribute 'get_current'
[21844] Failed to execute script 'main' due to unhandled exception!

eeintech avatar Mar 21 '24 12:03 eeintech

Windows
sys.version_info(major=3, minor=11, micro=6, releaselevel='final', serial=0)
EntryPoints(())
Failed to load context: contextvars_context
Traceback (most recent call last):
  File "opentelemetry\context\__init__.py", line 76, in wrapper
Exception: EntryPoints(())
Traceback (most recent call last):
  File "main.py", line 112, in <module>
    asyncio.run(main())
  File "asyncio\runners.py", line 190, in run
  File "asyncio\runners.py", line 118, in run
  File "asyncio\base_events.py", line 653, in run_until_complete
  File "main.py", line 20, in main
    await greet_user(graph)
  File "main.py", line 58, in greet_user
    user = await graph.get_user()
           ^^^^^^^^^^^^^^^^^^^^^^
  File "graph.py", line 52, in get_user
    user = await self.user_client.me.get(request_configuration=request_config)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "msgraph\generated\users\item\user_item_request_builder.py", line 157, in get
  File "kiota_http\httpx_request_adapter.py", line 178, in send_async
  File "kiota_http\httpx_request_adapter.py", line 513, in get_http_response_message
  File "kiota_http\httpx_request_adapter.py", line 150, in _start_local_tracing_span
  File "opentelemetry\trace\propagation\__init__.py", line 34, in set_span_in_context
  File "opentelemetry\context\__init__.py", line 140, in set_value
  File "opentelemetry\context\__init__.py", line 91, in wrapper
  File "opentelemetry\context\__init__.py", line 155, in get_current
AttributeError: 'NoneType' object has no attribute 'get_current'
[21844] Failed to execute script 'main' due to unhandled exception!

This is the problem:

> EntryPoints(())

For some reason, in your packaging environment there is no contextvars_context entry point.

Notice how this is different from the pure python:

> EntryPoints((EntryPoint(name='contextvars_context', value='opentelemetry.context.contextvars_context:ContextVarsRuntimeContext', group='opentelemetry_context'),))

With my changes both should fail because I am intentionally raising an error, but I see that the problem is that the packaging environment does not have any entry points loaded.

ocelotl avatar Mar 21 '24 19:03 ocelotl

Ha yes I was aware of the missing entry point but have no idea how to solve it... Again with raw python my application works but not after being packaged.

eeintech avatar Mar 21 '24 20:03 eeintech

I wonder if this is only happening in Windows.

@wbzdssm @matschaffer @kwrobert @christywald @amrithajayadev

Can you let us know in which OS did this error happen to you?

ocelotl avatar Mar 21 '24 21:03 ocelotl

Also @eeintech can you give us more details about what are you doing when packaging?

ocelotl avatar Mar 21 '24 21:03 ocelotl

Also @eeintech can you give us more details about what are you doing when packaging?

I use Git Bash on Windows 11.

My main script main.py is based on the MS graph tutorial: https://github.com/microsoftgraph/msgraph-training-python/tree/main/user-auth/graphtutorial

Running with python main.py works fine (Python 3.11).

I use PyInstaller 6.4.0 (https://pyinstaller.org/en/stable/) as follow:

$ pyinstaller main.py --clean --onefile
480 INFO: PyInstaller: 6.4.0, contrib hooks: 2024.2
480 INFO: Python: 3.11.6
542 INFO: Platform: Windows-10-10.0.22631-SP0
[ ... ] 
130831 INFO: Building EXE from EXE-00.toc completed successfully.

Then once pyinstaller has finished the packaging, I run it as follow:

$ dist/main.exe
Python Graph Tutorial

Windows
sys.version_info(major=3, minor=11, micro=6, releaselevel='final', serial=0)
EntryPoints(())
Failed to load context: contextvars_context
Traceback (most recent call last):
  File "opentelemetry\context\__init__.py", line 76, in wrapper
Exception: EntryPoints(())
Traceback (most recent call last):
  File "main.py", line 112, in <module>
    asyncio.run(main())
  File "asyncio\runners.py", line 190, in run
  File "asyncio\runners.py", line 118, in run
  File "asyncio\base_events.py", line 653, in run_until_complete
  File "main.py", line 20, in main
    await greet_user(graph)
  File "main.py", line 58, in greet_user
    user = await graph.get_user()
           ^^^^^^^^^^^^^^^^^^^^^^
  File "graph.py", line 52, in get_user
    user = await self.user_client.me.get(request_configuration=request_config)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "msgraph\generated\users\item\user_item_request_builder.py", line 157, in get
  File "kiota_http\httpx_request_adapter.py", line 178, in send_async
  File "kiota_http\httpx_request_adapter.py", line 513, in get_http_response_message
  File "kiota_http\httpx_request_adapter.py", line 150, in _start_local_tracing_span
  File "opentelemetry\trace\propagation\__init__.py", line 34, in set_span_in_context
  File "opentelemetry\context\__init__.py", line 140, in set_value
  File "opentelemetry\context\__init__.py", line 91, in wrapper
  File "opentelemetry\context\__init__.py", line 155, in get_current
AttributeError: 'NoneType' object has no attribute 'get_current'
[14624] Failed to execute script 'main' due to unhandled exception!

while running raw python gives:

$ python main.py
Python Graph Tutorial

Windows
sys.version_info(major=3, minor=11, micro=6, releaselevel='final', serial=0)
EntryPoints((EntryPoint(name='contextvars_context', value='opentelemetry.context.contextvars_context:ContextVarsRuntimeContext', group='opentelemetry_context'),))
Failed to load context: contextvars_context
Traceback (most recent call last):
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\opentelemetry\context\__init__.py", line 76, in wrapper
    raise Exception(the_entry_points)
Exception: EntryPoints((EntryPoint(name='contextvars_context', value='opentelemetry.context.contextvars_context:ContextVarsRuntimeContext', group='opentelemetry_context'),))
Traceback (most recent call last):
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\main.py", line 112, in <module>
    asyncio.run(main())
  File "C:\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\main.py", line 20, in main
    await greet_user(graph)
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\main.py", line 58, in greet_user
    user = await graph.get_user()
           ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\graph.py", line 52, in get_user
    user = await self.user_client.me.get(request_configuration=request_config)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\msgraph\generated\users\item\user_item_request_builder.py", line 157, in get
    return await self.request_adapter.send_async(request_info, User, error_mapping)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\kiota_http\httpx_request_adapter.py", line 178, in send_async
    response = await self.get_http_response_message(request_info, parent_span)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\kiota_http\httpx_request_adapter.py", line 513, in get_http_response_message
    _get_http_resp_span = self._start_local_tracing_span(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\kiota_http\httpx_request_adapter.py", line 150, in _start_local_tracing_span
    _context = trace.set_span_in_context(parent_span)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\opentelemetry\trace\propagation\__init__.py", line 34, in set_span_in_context
    ctx = set_value(_SPAN_KEY, span, context=context)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\opentelemetry\context\__init__.py", line 140, in set_value
    context = get_current()
              ^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\opentelemetry\context\__init__.py", line 91, in wrapper
    return func(*args, **kwargs)  # type: ignore[misc]
           ^^^^^^^^^^^^^^^^^^^^^
  File "C:\development\tests\msgraph-training-python\user-auth\graphtutorial\.env\Lib\site-packages\opentelemetry\context\__init__.py", line 155, in get_current
    return _RUNTIME_CONTEXT.get_current()  # type:ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'get_current'

Note: this is with your proposed changes in https://github.com/open-telemetry/opentelemetry-python/pull/3797

eeintech avatar Mar 22 '24 13:03 eeintech

I'm guessing that PyInstaller is the issue, does it support entry points from dists you install?

If this continue to be an issue, we should consider using the contextvars implementation with a direct import instead of loading it as an entrypoint in the default case (when OTEL_PYTHON_CONTEXT is not set).

The contextvars_context impl is already included in the opentelemetry-api package so I don't think there is any downside to loading it via import instead.

aabmass avatar Mar 25 '24 20:03 aabmass

I am encountering the same issue. My environment is Python 3.11.0 and opentelemetry-sdk 1.23.0.

When packaging my application using PyInstaller on Windows, I am getting the same issue: AttributeError: 'NoneType' object has no attribute 'get_current'

adityawdubey avatar Mar 27 '24 14:03 adityawdubey

Another thing I tried is packaging calling Pyinstaller on Powershell but I still had the same error...

Now my "working patch" is as follow:

  • In https://github.com/open-telemetry/opentelemetry-python/blob/main/opentelemetry-api/src/opentelemetry/context/init.py
    • In _load_runtime_context method, add return at the beginning https://github.com/open-telemetry/opentelemetry-python/blob/29c293fbb120ff8b760519a25e0530b5ab05af83/opentelemetry-api/src/opentelemetry/context/init.py#L46C9-L46C32
def _load_runtime_context(func: _F) -> _F:
    """A decorator used to initialize the global RuntimeContext

    Returns:
        A wrapper of the decorated method.
    """

    @wraps(func)  # type: ignore[misc]
    def wrapper(  # type: ignore[misc]
        *args: typing.Tuple[typing.Any, typing.Any],
        **kwargs: typing.Dict[typing.Any, typing.Any],
    ) -> typing.Optional[typing.Any]:
        global _RUNTIME_CONTEXT  # pylint: disable=global-statement
        return
  • In set_value method, comment out line 121 to 124: https://github.com/open-telemetry/opentelemetry-python/blob/29c293fbb120ff8b760519a25e0530b5ab05af83/opentelemetry-api/src/opentelemetry/context/init.py#L121
  • Add new_values = {} line
def set_value(
    key: str, value: "object", context: typing.Optional[Context] = None
) -> Context:
    """To record the local state of a cross-cutting concern, the
    RuntimeContext API provides a function which takes a context, a
    key, and a value as input, and returns an updated context
    which contains the new value.

    Args:
        key: The key of the entry to set.
        value: The value of the entry to set.
        context: The context to copy, if None, the current context is used.

    Returns:
        A new `Context` containing the value set.
    """
    # if context is None:
    #     context = get_current()
    # new_values = context.copy()
    # new_values[key] = value
    new_values = {}
    return Context(new_values)

It works fine in raw python and also works after packaging using Pyinstaller.

eeintech avatar Mar 27 '24 15:03 eeintech

FYI, this PR in PyInstaller addresses this issue: https://github.com/pyinstaller/pyinstaller-hooks-contrib/pull/725

uellue avatar Apr 18 '24 07:04 uellue

Seems to be a Pyinstaller issue, closing. Please reopen if this issue persists after @uellue fix has been merged in Pyinstaller.

ocelotl avatar Apr 19 '24 19:04 ocelotl

Hi guys, I have a persisting issue with the latest version of pyinstaller and opentelemetry, I developed a local AI app that runs perfectly on python but once I created its exe it keeps sending the same errors while executing:

Traceback (most recent call last): File "langchain_community\vectorstores\chroma.py", line 81, in init File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module File "chromadb_init_.py", line 5, in File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module File "chromadb\auth\token_init_.py", line 26, in File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module File "chromadb\telemetry\opentelemetry_init_.py", line 6, in File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module File "opentelemetry\sdk\resources_init_.py", line 144, in File "importlib_metadata_init_.py", line 900, in version File "importlib_metadata_init_.py", line 873, in distribution File "importlib_metadata_init_.py", line 391, in from_name importlib_metadata.PackageNotFoundError: No package metadata was found for opentelemetry-sdk

Could anyone help me if possible? Thank you!

Aybfr avatar May 02 '24 13:05 Aybfr

@Aybfr If you're using Pyinstaller v6.6 it won't work yet, the PR will most likely make it to the next version.

eeintech avatar May 02 '24 14:05 eeintech

@Aybfr Hi! Can you try this for your error?

# pyinstaller options
# ...
f"--copy-metadata=opentelemetry_sdk",

Floodnut avatar May 09 '24 02:05 Floodnut