Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
wbzdssm opened this issue Nov 24, 2021 · 31 comments
Closed

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

wbzdssm opened this issue Nov 24, 2021 · 31 comments
Labels
bug Something isn't working triaged

Comments

@wbzdssm
Copy link

wbzdssm commented Nov 24, 2021

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 wbzdssm added the bug Something isn't working label Nov 24, 2021
@srikanthccv
Copy link
Member

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?

@matschaffer
Copy link

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.

@ocelotl
Copy link
Contributor

ocelotl commented Apr 21, 2022

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?

v1v added a commit to andrewkroh/beats that referenced this issue Aug 22, 2022
v1v added a commit to andrewkroh/beats that referenced this issue Aug 23, 2022
andrewkroh added a commit to elastic/beats that referenced this issue Aug 24, 2022
* Use 'go install' in Github Action setup

As of Go 1.18, "go get no longer builds or installs packages in module-aware mode."

* opentelemetry: pin dependencies for the otel

as stated in open-telemetry/opentelemetry-python#2288

* action: force python version 3.9

workaround the issue with open-telemetry/opentelemetry-python#2288

Co-authored-by: Victor Martinez <[email protected]>
mergify bot pushed a commit to elastic/beats that referenced this issue Oct 14, 2022
* Use 'go install' in Github Action setup

As of Go 1.18, "go get no longer builds or installs packages in module-aware mode."

* opentelemetry: pin dependencies for the otel

as stated in open-telemetry/opentelemetry-python#2288

* action: force python version 3.9

workaround the issue with open-telemetry/opentelemetry-python#2288

Co-authored-by: Victor Martinez <[email protected]>
(cherry picked from commit 6413e46)

# Conflicts:
#	libbeat/tests/system/requirements_aix.txt
rdner pushed a commit to elastic/beats that referenced this issue Oct 14, 2022
* Use 'go install' in Github Action setup

As of Go 1.18, "go get no longer builds or installs packages in module-aware mode."

* opentelemetry: pin dependencies for the otel

as stated in open-telemetry/opentelemetry-python#2288

* action: force python version 3.9

workaround the issue with open-telemetry/opentelemetry-python#2288

Co-authored-by: Victor Martinez <[email protected]>
(cherry picked from commit 6413e46)

# Conflicts:
#	libbeat/tests/system/requirements_aix.txt

Co-authored-by: Andrew Kroh <[email protected]>
chrisberkhout pushed a commit to elastic/beats that referenced this issue Jun 1, 2023
* Use 'go install' in Github Action setup

As of Go 1.18, "go get no longer builds or installs packages in module-aware mode."

* opentelemetry: pin dependencies for the otel

as stated in open-telemetry/opentelemetry-python#2288

* action: force python version 3.9

workaround the issue with open-telemetry/opentelemetry-python#2288

Co-authored-by: Victor Martinez <[email protected]>
@kwrobert
Copy link

kwrobert commented Jun 7, 2023

I am seeing this issue using Python 3.8 and opentelemetry 1.18.0

@christywald
Copy link

Same with me. Python 3.8 and opentelemetry 1.18.0

@kwrobert
Copy link

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

@lzchen
Copy link
Contributor

lzchen commented Jun 15, 2023

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.

@srikanthccv
Copy link
Member

@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.

@amrithajayadev
Copy link

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 ?

@lzchen
Copy link
Contributor

lzchen commented Sep 11, 2023

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

@srikanthccv
Copy link
Member

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.

@ocelotl
Copy link
Contributor

ocelotl commented Oct 1, 2023

@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.

@eeintech
Copy link

eeintech commented Mar 7, 2024

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
Copy link

@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 😬

@ocelotl
Copy link
Contributor

ocelotl commented Mar 20, 2024

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

@ocelotl ocelotl mentioned this issue Mar 20, 2024
@ocelotl
Copy link
Contributor

ocelotl commented Mar 20, 2024

@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.

@eeintech
Copy link

eeintech commented Mar 21, 2024

@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!

@ocelotl
Copy link
Contributor

ocelotl commented Mar 21, 2024

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.

@eeintech
Copy link

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.

@ocelotl
Copy link
Contributor

ocelotl commented Mar 21, 2024

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
Copy link
Contributor

ocelotl commented Mar 21, 2024

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

@eeintech
Copy link

eeintech commented Mar 22, 2024

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 #3797

@aabmass
Copy link
Member

aabmass commented Mar 25, 2024

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.

@adityawdubey
Copy link

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'

@eeintech
Copy link

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

Now my "working patch" is as follow:

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
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.

@uellue
Copy link

uellue commented Apr 18, 2024

FYI, this PR in PyInstaller addresses this issue: pyinstaller/pyinstaller-hooks-contrib#725

@ocelotl
Copy link
Contributor

ocelotl commented Apr 19, 2024

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

@ocelotl ocelotl closed this as completed Apr 19, 2024
@Aybfr
Copy link

Aybfr commented May 2, 2024

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!

@eeintech
Copy link

eeintech commented May 2, 2024

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

@Floodnut
Copy link

Floodnut commented May 9, 2024

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

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

@eeintech
Copy link

FYI I believe that with Pyinstaller == 6.7.0 and pyinstaller-hooks-contrib == 2024.6, this issue is no more! It works for me 😃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working triaged
Projects
None yet
Development

No branches or pull requests