diff --git a/.github/component_owners.yml b/.github/component_owners.yml index 5cbb6aa402..81a9647788 100644 --- a/.github/component_owners.yml +++ b/.github/component_owners.yml @@ -61,6 +61,9 @@ components: instrumentation/opentelemetry-instrumentation-psycopg: - federicobond + instrumentation/opentelemetry-instrumentation-pymssql: + - guillaumep + instrumentation/opentelemetry-instrumentation-aiokafka: - dimastbk diff --git a/.github/workflows/core_contrib_test_0.yml b/.github/workflows/core_contrib_test_0.yml index 6a70ce8380..a8336e093f 100644 --- a/.github/workflows/core_contrib_test_0.yml +++ b/.github/workflows/core_contrib_test_0.yml @@ -1273,6 +1273,28 @@ jobs: - name: Run tests run: tox -e py38-test-instrumentation-pymysql -- -ra + py38-test-instrumentation-pymssql: + name: instrumentation-pymssql + runs-on: ubuntu-latest + steps: + - name: Checkout contrib repo @ SHA - ${{ env.CONTRIB_REPO_SHA }} + uses: actions/checkout@v4 + with: + repository: open-telemetry/opentelemetry-python-contrib + ref: ${{ env.CONTRIB_REPO_SHA }} + + - name: Set up Python 3.8 + uses: actions/setup-python@v5 + with: + python-version: "3.8" + architecture: "x64" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py38-test-instrumentation-pymssql -- -ra + py38-test-instrumentation-pyramid: name: instrumentation-pyramid runs-on: ubuntu-latest diff --git a/.github/workflows/lint_0.yml b/.github/workflows/lint_0.yml index 34db823570..cc7cfd536f 100644 --- a/.github/workflows/lint_0.yml +++ b/.github/workflows/lint_0.yml @@ -664,6 +664,24 @@ jobs: - name: Run tests run: tox -e lint-instrumentation-pymysql + lint-instrumentation-pymssql: + name: instrumentation-pymssql + runs-on: ubuntu-latest + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.13 + uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e lint-instrumentation-pymssql + lint-instrumentation-pyramid: name: instrumentation-pyramid runs-on: ubuntu-latest diff --git a/.github/workflows/test_1.yml b/.github/workflows/test_1.yml index b27fe28466..f2686cfe91 100644 --- a/.github/workflows/test_1.yml +++ b/.github/workflows/test_1.yml @@ -2338,6 +2338,114 @@ jobs: - name: Run tests run: tox -e pypy3-test-instrumentation-pymysql -- -ra + py38-test-instrumentation-pymssql_ubuntu-latest: + name: instrumentation-pymssql 3.8 Ubuntu + runs-on: ubuntu-latest + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.8 + uses: actions/setup-python@v5 + with: + python-version: "3.8" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py38-test-instrumentation-pymssql -- -ra + + py39-test-instrumentation-pymssql_ubuntu-latest: + name: instrumentation-pymssql 3.9 Ubuntu + runs-on: ubuntu-latest + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.9 + uses: actions/setup-python@v5 + with: + python-version: "3.9" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py39-test-instrumentation-pymssql -- -ra + + py310-test-instrumentation-pymssql_ubuntu-latest: + name: instrumentation-pymssql 3.10 Ubuntu + runs-on: ubuntu-latest + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.10 + uses: actions/setup-python@v5 + with: + python-version: "3.10" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py310-test-instrumentation-pymssql -- -ra + + py311-test-instrumentation-pymssql_ubuntu-latest: + name: instrumentation-pymssql 3.11 Ubuntu + runs-on: ubuntu-latest + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.11 + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py311-test-instrumentation-pymssql -- -ra + + py312-test-instrumentation-pymssql_ubuntu-latest: + name: instrumentation-pymssql 3.12 Ubuntu + runs-on: ubuntu-latest + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py312-test-instrumentation-pymssql -- -ra + + py313-test-instrumentation-pymssql_ubuntu-latest: + name: instrumentation-pymssql 3.13 Ubuntu + runs-on: ubuntu-latest + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.13 + uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py313-test-instrumentation-pymssql -- -ra + py38-test-instrumentation-pyramid_ubuntu-latest: name: instrumentation-pyramid 3.8 Ubuntu runs-on: ubuntu-latest @@ -4407,111 +4515,3 @@ jobs: - name: Run tests run: tox -e py311-test-instrumentation-httpx-1 -- -ra - - py312-test-instrumentation-httpx-0_ubuntu-latest: - name: instrumentation-httpx-0 3.12 Ubuntu - runs-on: ubuntu-latest - steps: - - name: Checkout repo @ SHA - ${{ github.sha }} - uses: actions/checkout@v4 - - - name: Set up Python 3.12 - uses: actions/setup-python@v5 - with: - python-version: "3.12" - - - name: Install tox - run: pip install tox-uv - - - name: Run tests - run: tox -e py312-test-instrumentation-httpx-0 -- -ra - - py312-test-instrumentation-httpx-1_ubuntu-latest: - name: instrumentation-httpx-1 3.12 Ubuntu - runs-on: ubuntu-latest - steps: - - name: Checkout repo @ SHA - ${{ github.sha }} - uses: actions/checkout@v4 - - - name: Set up Python 3.12 - uses: actions/setup-python@v5 - with: - python-version: "3.12" - - - name: Install tox - run: pip install tox-uv - - - name: Run tests - run: tox -e py312-test-instrumentation-httpx-1 -- -ra - - py313-test-instrumentation-httpx-1_ubuntu-latest: - name: instrumentation-httpx-1 3.13 Ubuntu - runs-on: ubuntu-latest - steps: - - name: Checkout repo @ SHA - ${{ github.sha }} - uses: actions/checkout@v4 - - - name: Set up Python 3.13 - uses: actions/setup-python@v5 - with: - python-version: "3.13" - - - name: Install tox - run: pip install tox-uv - - - name: Run tests - run: tox -e py313-test-instrumentation-httpx-1 -- -ra - - pypy3-test-instrumentation-httpx-0_ubuntu-latest: - name: instrumentation-httpx-0 pypy-3.8 Ubuntu - runs-on: ubuntu-latest - steps: - - name: Checkout repo @ SHA - ${{ github.sha }} - uses: actions/checkout@v4 - - - name: Set up Python pypy-3.8 - uses: actions/setup-python@v5 - with: - python-version: "pypy-3.8" - - - name: Install tox - run: pip install tox-uv - - - name: Run tests - run: tox -e pypy3-test-instrumentation-httpx-0 -- -ra - - pypy3-test-instrumentation-httpx-1_ubuntu-latest: - name: instrumentation-httpx-1 pypy-3.8 Ubuntu - runs-on: ubuntu-latest - steps: - - name: Checkout repo @ SHA - ${{ github.sha }} - uses: actions/checkout@v4 - - - name: Set up Python pypy-3.8 - uses: actions/setup-python@v5 - with: - python-version: "pypy-3.8" - - - name: Install tox - run: pip install tox-uv - - - name: Run tests - run: tox -e pypy3-test-instrumentation-httpx-1 -- -ra - - py38-test-util-http_ubuntu-latest: - name: util-http 3.8 Ubuntu - runs-on: ubuntu-latest - steps: - - name: Checkout repo @ SHA - ${{ github.sha }} - uses: actions/checkout@v4 - - - name: Set up Python 3.8 - uses: actions/setup-python@v5 - with: - python-version: "3.8" - - - name: Install tox - run: pip install tox-uv - - - name: Run tests - run: tox -e py38-test-util-http -- -ra diff --git a/.github/workflows/test_2.yml b/.github/workflows/test_2.yml index d9b622c5c3..96ebfba82a 100644 --- a/.github/workflows/test_2.yml +++ b/.github/workflows/test_2.yml @@ -16,6 +16,114 @@ env: jobs: + py312-test-instrumentation-httpx-0_ubuntu-latest: + name: instrumentation-httpx-0 3.12 Ubuntu + runs-on: ubuntu-latest + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py312-test-instrumentation-httpx-0 -- -ra + + py312-test-instrumentation-httpx-1_ubuntu-latest: + name: instrumentation-httpx-1 3.12 Ubuntu + runs-on: ubuntu-latest + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py312-test-instrumentation-httpx-1 -- -ra + + py313-test-instrumentation-httpx-1_ubuntu-latest: + name: instrumentation-httpx-1 3.13 Ubuntu + runs-on: ubuntu-latest + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.13 + uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py313-test-instrumentation-httpx-1 -- -ra + + pypy3-test-instrumentation-httpx-0_ubuntu-latest: + name: instrumentation-httpx-0 pypy-3.8 Ubuntu + runs-on: ubuntu-latest + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python pypy-3.8 + uses: actions/setup-python@v5 + with: + python-version: "pypy-3.8" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e pypy3-test-instrumentation-httpx-0 -- -ra + + pypy3-test-instrumentation-httpx-1_ubuntu-latest: + name: instrumentation-httpx-1 pypy-3.8 Ubuntu + runs-on: ubuntu-latest + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python pypy-3.8 + uses: actions/setup-python@v5 + with: + python-version: "pypy-3.8" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e pypy3-test-instrumentation-httpx-1 -- -ra + + py38-test-util-http_ubuntu-latest: + name: util-http 3.8 Ubuntu + runs-on: ubuntu-latest + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.8 + uses: actions/setup-python@v5 + with: + python-version: "3.8" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py38-test-util-http -- -ra + py39-test-util-http_ubuntu-latest: name: util-http 3.9 Ubuntu runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index 80da336aee..8f78a8d50f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ([#3200](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3200)) - `opentelemetry-opentelemetry-botocore` Add basic support for GenAI attributes for AWS Bedrock ConverseStream API ([#3204](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3204)) +- `opentelemetry-instrumentation-pymssql` Add pymssql instrumentation + ([#394](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/394)) ### Fixed @@ -69,7 +71,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `opentelemetry-instrumentation-dbapi` including sqlcomment in `db.statement` span attribute value is now opt-in ([#3115](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3115)) - ### Breaking changes - `opentelemetry-instrumentation-dbapi` including sqlcomment in `db.statement` span attribute value is now opt-in @@ -77,7 +78,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `opentelemetry-instrumentation-psycopg2`, `opentelemetry-instrumentation-psycopg`, `opentelemetry-instrumentation-mysqlclient`, `opentelemetry-instrumentation-pymysql`: including sqlcomment in `db.statement` span attribute value is now opt-in ([#3121](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3121)) - ## Version 1.29.0/0.50b0 (2024-12-11) ### Added diff --git a/docs-requirements.txt b/docs-requirements.txt index d547e806a3..0e36426fe3 100644 --- a/docs-requirements.txt +++ b/docs-requirements.txt @@ -35,6 +35,7 @@ psycopg~=3.1.17 pika>=0.12.0 pymongo~=4.6.3 PyMySQL~=1.1.1 +pymssql~=2.3.2 pyramid>=1.7 redis>=2.6 remoulade>=0.50 diff --git a/docs/instrumentation/pymssql/pymssql.rst b/docs/instrumentation/pymssql/pymssql.rst new file mode 100644 index 0000000000..0b1b589cb9 --- /dev/null +++ b/docs/instrumentation/pymssql/pymssql.rst @@ -0,0 +1,7 @@ +OpenTelemetry pymssql Instrumentation +===================================== + +.. automodule:: opentelemetry.instrumentation.pymssql + :members: + :undoc-members: + :show-inheritance: diff --git a/instrumentation/README.md b/instrumentation/README.md index a229951b4b..dcfcf46edd 100644 --- a/instrumentation/README.md +++ b/instrumentation/README.md @@ -35,6 +35,7 @@ | [opentelemetry-instrumentation-psycopg2](./opentelemetry-instrumentation-psycopg2) | psycopg2 >= 2.7.3.1,psycopg2-binary >= 2.7.3.1 | No | experimental | [opentelemetry-instrumentation-pymemcache](./opentelemetry-instrumentation-pymemcache) | pymemcache >= 1.3.5, < 5 | No | experimental | [opentelemetry-instrumentation-pymongo](./opentelemetry-instrumentation-pymongo) | pymongo >= 3.1, < 5.0 | No | experimental +| [opentelemetry-instrumentation-pymssql](./opentelemetry-instrumentation-pymssql) | pymssql >= 2.1.5, < 3 | No | experimental | [opentelemetry-instrumentation-pymysql](./opentelemetry-instrumentation-pymysql) | PyMySQL < 2 | No | experimental | [opentelemetry-instrumentation-pyramid](./opentelemetry-instrumentation-pyramid) | pyramid >= 1.7 | Yes | experimental | [opentelemetry-instrumentation-redis](./opentelemetry-instrumentation-redis) | redis >= 2.6 | No | experimental diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py index 27aafc7308..c7b1dee3b2 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/src/opentelemetry/instrumentation/dbapi/__init__.py @@ -204,10 +204,12 @@ def instrument_connection( commenter_options: dict[str, Any] | None = None, connect_module: Callable[..., Any] | None = None, enable_attribute_commenter: bool = False, + db_api_integration_factory: type[DatabaseApiIntegration] | None = None, ) -> TracedConnectionProxy[ConnectionT]: """Enable instrumentation in a database connection. Args: + name: The instrumentation module name. connection: The connection to instrument. database_system: An identifier for the database management system (DBMS) product being used. @@ -220,6 +222,10 @@ def instrument_connection( commenter_options: Configurations for tags to be appended at the sql query. connect_module: Module name where connect method is available. enable_attribute_commenter: Flag to enable/disable sqlcomment inclusion in `db.statement` span attribute. Only available if enable_commenter=True. + db_api_integration_factory: A class or factory function to use as a + replacement for :class:`DatabaseApiIntegration`. Can be used to + obtain connection attributes from the connect method instead of + from the connection itself (as done by the pymssql intrumentor). Returns: An instrumented connection. @@ -228,7 +234,11 @@ def instrument_connection( _logger.warning("Connection already instrumented") return connection - db_integration = DatabaseApiIntegration( + db_api_integration_factory = ( + db_api_integration_factory or DatabaseApiIntegration + ) + + db_integration = db_api_integration_factory( name, database_system, connection_attributes=connection_attributes, diff --git a/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py b/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py index 3d531fb791..97d53f33ec 100644 --- a/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py +++ b/instrumentation/opentelemetry-instrumentation-dbapi/tests/test_dbapi_integration.py @@ -46,7 +46,9 @@ def test_span_succeeded(self): "user": "user", } db_integration = dbapi.DatabaseApiIntegration( - "testname", "testcomponent", connection_attributes + "instrumenting_module_test_name", + "testcomponent", + connection_attributes, ) mock_connection = db_integration.wrapped_connection( mock_connect, {}, connection_props @@ -78,7 +80,7 @@ def test_span_succeeded(self): def test_span_name(self): db_integration = dbapi.DatabaseApiIntegration( - "testname", "testcomponent", {} + "instrumenting_module_test_name", "testcomponent", {} ) mock_connection = db_integration.wrapped_connection( mock_connect, {}, {} @@ -117,7 +119,7 @@ def test_span_succeeded_with_capture_of_statement_parameters(self): "user": "user", } db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "testcomponent", connection_attributes, capture_parameters=True, @@ -169,7 +171,9 @@ def test_span_not_recording(self): mock_span = mock.Mock() mock_span.is_recording.return_value = False db_integration = dbapi.DatabaseApiIntegration( - "testname", "testcomponent", connection_attributes + "instrumenting_module_test_name", + "testcomponent", + connection_attributes, ) mock_connection = db_integration.wrapped_connection( mock_connect, {}, connection_props @@ -183,7 +187,7 @@ def test_span_not_recording(self): def test_span_failed(self): db_integration = dbapi.DatabaseApiIntegration( - self.tracer, "testcomponent" + "instrumenting_module_test_name", "testcomponent" ) mock_connection = db_integration.wrapped_connection( mock_connect, {}, {} @@ -207,7 +211,9 @@ def test_custom_tracer_provider_dbapi(self): tracer_provider, exporter = result db_integration = dbapi.DatabaseApiIntegration( - self.tracer, "testcomponent", tracer_provider=tracer_provider + "instrumenting_module_test_name", + "testcomponent", + tracer_provider=tracer_provider, ) mock_connection = db_integration.wrapped_connection( mock_connect, {}, {} @@ -224,7 +230,7 @@ def test_custom_tracer_provider_dbapi(self): def test_no_op_tracer_provider(self): db_integration = dbapi.DatabaseApiIntegration( - self.tracer, + "instrumenting_module_test_name", "testcomponent", tracer_provider=trace_api.NoOpTracerProvider(), ) @@ -239,7 +245,7 @@ def test_no_op_tracer_provider(self): def test_executemany(self): db_integration = dbapi.DatabaseApiIntegration( - "testname", "testcomponent" + "instrumenting_module_test_name", "testcomponent" ) mock_connection = db_integration.wrapped_connection( mock_connect, {}, {} @@ -263,7 +269,7 @@ def test_executemany_comment(self): connect_module.paramstyle = "test" db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "postgresql", enable_commenter=True, commenter_options={"db_driver": False, "dbapi_level": False}, @@ -296,7 +302,7 @@ def test_executemany_comment_stmt_enabled(self): connect_module.paramstyle = "test" db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "postgresql", enable_commenter=True, commenter_options={"db_driver": False, "dbapi_level": False}, @@ -333,7 +339,7 @@ def __getattr__(self, name): connect_module = MockConnectModule() db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "postgresql", enable_commenter=True, connect_module=connect_module, @@ -369,7 +375,7 @@ def __getattr__(self, name): connect_module = MockConnectModule() db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "postgresql", enable_commenter=True, connect_module=connect_module, @@ -404,7 +410,7 @@ def test_executemany_comment_stmt_enabled_matches_db_statement_attribute( connect_module.paramstyle = "test" db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "postgresql", enable_commenter=True, commenter_options={"db_driver": False, "dbapi_level": False}, @@ -445,7 +451,7 @@ def test_compatible_build_version_psycopg_psycopg2_libpq(self): connect_module.paramstyle = "test" db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "postgresql", enable_commenter=True, commenter_options={"db_driver": False, "dbapi_level": False}, @@ -481,7 +487,7 @@ def test_compatible_build_version_psycopg_psycopg2_libpq_stmt_enabled( connect_module.paramstyle = "test" db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "postgresql", enable_commenter=True, commenter_options={"db_driver": False, "dbapi_level": False}, @@ -515,7 +521,7 @@ def test_executemany_psycopg2_integration_comment(self): connect_module.paramstyle = "test" db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "postgresql", enable_commenter=True, commenter_options={"db_driver": True, "dbapi_level": False}, @@ -548,7 +554,7 @@ def test_executemany_psycopg2_integration_comment_stmt_enabled(self): connect_module.paramstyle = "test" db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "postgresql", enable_commenter=True, commenter_options={"db_driver": True, "dbapi_level": False}, @@ -583,7 +589,7 @@ def test_executemany_psycopg_integration_comment(self): connect_module.paramstyle = "test" db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "postgresql", enable_commenter=True, commenter_options={"db_driver": True, "dbapi_level": False}, @@ -617,7 +623,7 @@ def test_executemany_psycopg_integration_comment_stmt_enabled(self): connect_module.paramstyle = "test" db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "postgresql", enable_commenter=True, commenter_options={"db_driver": True, "dbapi_level": False}, @@ -650,7 +656,7 @@ def test_executemany_mysqlconnector_integration_comment(self): connect_module.paramstyle = "test" db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "mysql", enable_commenter=True, commenter_options={"db_driver": True, "dbapi_level": False}, @@ -683,7 +689,7 @@ def test_executemany_mysqlconnector_integration_comment_stmt_enabled(self): connect_module.paramstyle = "test" db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "mysql", enable_commenter=True, commenter_options={"db_driver": True, "dbapi_level": False}, @@ -726,7 +732,7 @@ def test_executemany_mysqlclient_integration_comment( ) db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "mysql", enable_commenter=True, commenter_options={"db_driver": True, "dbapi_level": False}, @@ -768,7 +774,7 @@ def test_executemany_mysqlclient_integration_comment_stmt_enabled( ) db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "mysql", enable_commenter=True, commenter_options={"db_driver": True, "dbapi_level": False}, @@ -803,7 +809,7 @@ def test_executemany_pymysql_integration_comment(self): connect_module.get_client_info = mock.MagicMock(return_value="123") db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "mysql", enable_commenter=True, commenter_options={"db_driver": True, "dbapi_level": False}, @@ -837,7 +843,7 @@ def test_executemany_pymysql_integration_comment_stmt_enabled(self): connect_module.get_client_info = mock.MagicMock(return_value="123") db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "mysql", enable_commenter=True, commenter_options={"db_driver": True, "dbapi_level": False}, @@ -872,7 +878,7 @@ def test_executemany_flask_integration_comment(self): connect_module.paramstyle = "test" db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "postgresql", enable_commenter=True, commenter_options={"db_driver": False, "dbapi_level": False}, @@ -916,7 +922,7 @@ def test_executemany_flask_integration_comment_stmt_enabled(self): connect_module.paramstyle = "test" db_integration = dbapi.DatabaseApiIntegration( - "testname", + "instrumenting_module_test_name", "postgresql", enable_commenter=True, commenter_options={"db_driver": False, "dbapi_level": False}, @@ -953,7 +959,7 @@ def test_executemany_flask_integration_comment_stmt_enabled(self): def test_callproc(self): db_integration = dbapi.DatabaseApiIntegration( - "testname", "testcomponent" + "instrumenting_module_test_name", "testcomponent" ) mock_connection = db_integration.wrapped_connection( mock_connect, {}, {} @@ -987,15 +993,19 @@ def test_unwrap_connect(self, mock_dbapi): self.assertIsInstance(connection, mock.Mock) def test_instrument_connection(self): - connection = mock.Mock() + mocked_conn = MockConnection("dbname", "999", "dbhost", "dbuser") # Avoid get_attributes failing because can't concatenate mock - connection.database = "-" - connection2 = dbapi.instrument_connection(self.tracer, connection, "-") - self.assertIs(connection2.__wrapped__, connection) + connection2 = dbapi.instrument_connection( + "instrumenting_module_test_name", mocked_conn, "dbname" + ) + self.assertIs(connection2.__wrapped__, mocked_conn) @mock.patch("opentelemetry.instrumentation.dbapi.DatabaseApiIntegration") def test_instrument_connection_kwargs_defaults(self, mock_dbapiint): - dbapi.instrument_connection(self.tracer, mock.Mock(), "foo") + mocked_conn = MockConnection("dbname", "999", "dbhost", "dbuser") + dbapi.instrument_connection( + "instrumenting_module_test_name", mocked_conn, "foo" + ) kwargs = mock_dbapiint.call_args[1] self.assertEqual(kwargs["connection_attributes"], None) self.assertEqual(kwargs["version"], "") @@ -1008,11 +1018,12 @@ def test_instrument_connection_kwargs_defaults(self, mock_dbapiint): @mock.patch("opentelemetry.instrumentation.dbapi.DatabaseApiIntegration") def test_instrument_connection_kwargs_provided(self, mock_dbapiint): + mocked_conn = MockConnection("dbname", "999", "dbhost", "dbuser") mock_tracer_provider = mock.MagicMock() mock_connect_module = mock.MagicMock() dbapi.instrument_connection( - self.tracer, - mock.Mock(), + "instrumenting_module_test_name", + mocked_conn, "foo", connection_attributes={"foo": "bar"}, version="test", @@ -1033,20 +1044,35 @@ def test_instrument_connection_kwargs_provided(self, mock_dbapiint): self.assertIs(kwargs["connect_module"], mock_connect_module) self.assertEqual(kwargs["enable_attribute_commenter"], True) + def test_instrument_connection_db_api_integration_factory(self): + mocked_conn = MockConnection("dbname", "999", "dbhost", "dbuser") + + class DBApiIntegrationTestClass(dbapi.DatabaseApiIntegration): + pass + + conn = dbapi.instrument_connection( + "instrumenting_module_test_name", + mocked_conn, + "dbsystem", + db_api_integration_factory=DBApiIntegrationTestClass, + ) + self.assertIsInstance( + conn._self_db_api_integration, DBApiIntegrationTestClass + ) + def test_uninstrument_connection(self): - connection = mock.Mock() - # Set connection.database to avoid a failure because mock can't - # be concatenated - connection.database = "-" - connection2 = dbapi.instrument_connection(self.tracer, connection, "-") - self.assertIs(connection2.__wrapped__, connection) + mocked_conn = MockConnection("dbname", "999", "dbhost", "dbuser") + connection2 = dbapi.instrument_connection( + "instrumenting_module_test_name", mocked_conn, "-" + ) + self.assertIs(connection2.__wrapped__, mocked_conn) connection3 = dbapi.uninstrument_connection(connection2) - self.assertIs(connection3, connection) + self.assertIs(connection3, mocked_conn) with self.assertLogs(level=logging.WARNING): - connection4 = dbapi.uninstrument_connection(connection) - self.assertIs(connection4, connection) + connection4 = dbapi.uninstrument_connection(mocked_conn) + self.assertIs(connection4, mocked_conn) # pylint: disable=unused-argument diff --git a/instrumentation/opentelemetry-instrumentation-pymssql/LICENSE b/instrumentation/opentelemetry-instrumentation-pymssql/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-pymssql/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/instrumentation/opentelemetry-instrumentation-pymssql/README.rst b/instrumentation/opentelemetry-instrumentation-pymssql/README.rst new file mode 100644 index 0000000000..b885d6b5c5 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-pymssql/README.rst @@ -0,0 +1,21 @@ +OpenTelemetry pymssql Instrumentation +===================================== + +|pypi| + +.. |pypi| image:: https://badge.fury.io/py/opentelemetry-instrumentation-pymssql.svg + :target: https://pypi.org/project/opentelemetry-instrumentation-pymssql/ + +Installation +------------ + +:: + + pip install opentelemetry-instrumentation-pymssql + + +References +---------- +* `OpenTelemetry pymssql Instrumentation `_ +* `OpenTelemetry Project `_ +* `OpenTelemetry Python Examples `_ diff --git a/instrumentation/opentelemetry-instrumentation-pymssql/pyproject.toml b/instrumentation/opentelemetry-instrumentation-pymssql/pyproject.toml new file mode 100644 index 0000000000..5360007a5c --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-pymssql/pyproject.toml @@ -0,0 +1,56 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "opentelemetry-instrumentation-pymssql" +dynamic = ["version"] +description = "OpenTelemetry pymssql instrumentation" +readme = "README.rst" +license = "Apache-2.0" +requires-python = ">=3.8" +authors = [ + { name = "OpenTelemetry Authors", email = "cncf-opentelemetry-contributors@lists.cncf.io" }, +] +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +dependencies = [ + "opentelemetry-api ~= 1.12", + "opentelemetry-instrumentation == 0.51b0.dev", + "opentelemetry-instrumentation-dbapi == 0.51b0.dev", +] + +[project.optional-dependencies] +instruments = [ + "pymssql >= 2.1.5, < 3", +] + +[project.entry-points.opentelemetry_instrumentor] +pymssql = "opentelemetry.instrumentation.pymssql:pymssqlInstrumentor" + +[project.urls] +Homepage = "https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-pymssql" +Repository = "https://github.com/open-telemetry/opentelemetry-python-contrib" + +[tool.hatch.version] +path = "src/opentelemetry/instrumentation/pymssql/version.py" + +[tool.hatch.build.targets.sdist] +include = [ + "/src", + "/tests", +] + +[tool.hatch.build.targets.wheel] +packages = ["src/opentelemetry"] diff --git a/instrumentation/opentelemetry-instrumentation-pymssql/src/opentelemetry/instrumentation/pymssql/__init__.py b/instrumentation/opentelemetry-instrumentation-pymssql/src/opentelemetry/instrumentation/pymssql/__init__.py new file mode 100644 index 0000000000..2f2ca5f4a2 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-pymssql/src/opentelemetry/instrumentation/pymssql/__init__.py @@ -0,0 +1,208 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +The integration with pymssql supports the `pymssql`_ library and can be enabled +by using ``PyMSSQLInstrumentor``. + +.. _pymssql: https://pypi.org/project/pymssql/ + +Usage +----- + +.. code:: python + + import pymssql + from opentelemetry.instrumentation.pymssql import PyMSSQLInstrumentor + + PyMSSQLInstrumentor().instrument() + + cnx = pymssql.connect(database="MSSQL_Database") + cursor = cnx.cursor() + cursor.execute("INSERT INTO test (testField) VALUES (123)" + cnx.commit() + cursor.close() + cnx.close() + +.. code:: python + + import pymssql + from opentelemetry.instrumentation.pymssql import PyMSSQLInstrumentor + + # Alternatively, use instrument_connection for an individual connection + cnx = pymssql.connect(database="MSSQL_Database") + instrumented_cnx = PyMSSQLInstrumentor().instrument_connection(cnx) + cursor = instrumented_cnx.cursor() + cursor.execute("INSERT INTO test (testField) VALUES (123)" + instrumented_cnx.commit() + cursor.close() + instrumented_cnx.close() + +API +--- +The `instrument` method accepts the following keyword args: + +tracer_provider (TracerProvider) - an optional tracer provider + +For example: + +.. code: python + + import pymssql + from opentelemetry.instrumentation.pymssql import PyMSSQLInstrumentor + from opentelemetry.trace import NoOpTracerProvider + + PyMSSQLInstrumentor().instrument(tracer_provider=NoOpTracerProvider()) +""" + +from __future__ import annotations + +from typing import Any, Callable, Collection, NamedTuple + +import pymssql + +from opentelemetry.instrumentation import dbapi +from opentelemetry.instrumentation.instrumentor import BaseInstrumentor +from opentelemetry.instrumentation.pymssql.package import _instruments +from opentelemetry.instrumentation.pymssql.version import __version__ + +_DATABASE_SYSTEM = "mssql" + + +class _PyMSSQLConnectMethodArgsTuple(NamedTuple): + server: str | None = None + user: str | None = None + password: str | None = None + database: str | None = None + timeout: int | None = None + login_timeout: int | None = None + charset: str | None = None + as_dict: bool | None = None + host: str | None = None + appname: str | None = None + port: str | None = None + conn_properties: str | None = None + autocommit: bool | None = None + tds_version: str | None = None + + +class _PyMSSQLDatabaseApiIntegration(dbapi.DatabaseApiIntegration): + def wrapped_connection( + self, + connect_method: Callable[..., Any], + args: tuple[Any, Any], + kwargs: dict[Any, Any], + ): + """Add object proxy to connection object.""" + connection = connect_method(*args, **kwargs) + connect_method_args = _PyMSSQLConnectMethodArgsTuple(*args) + + self.name = self.database_system + self.database = kwargs.get("database") or connect_method_args.database + + user = kwargs.get("user") or connect_method_args.user + if user is not None: + self.span_attributes["db.user"] = user + + port = kwargs.get("port") or connect_method_args.port + host = kwargs.get("server") or connect_method_args.server + if host is None: + host = kwargs.get("host") or connect_method_args.host + if host is not None: + # The host string can include the port, separated by either a coma or + # a column + for sep in (":", ","): + if sep in host: + tokens = host.rsplit(sep) + host = tokens[0] + if len(tokens) > 1: + port = tokens[1] + if host is not None: + self.span_attributes["net.peer.name"] = host + if port is not None: + self.span_attributes["net.peer.port"] = port + + charset = kwargs.get("charset") or connect_method_args.charset + if charset is not None: + self.span_attributes["db.charset"] = charset + + tds_version = ( + kwargs.get("tds_version") or connect_method_args.tds_version + ) + if tds_version is not None: + self.span_attributes["db.protocol.tds.version"] = tds_version + + return dbapi.get_traced_connection_proxy(connection, self) + + +class PyMSSQLInstrumentor(BaseInstrumentor): + def instrumentation_dependencies(self) -> Collection[str]: + return _instruments + + def _instrument(self, **kwargs): + """Integrate with the pymssql library. + https://github.com/pymssql/pymssql/ + """ + tracer_provider = kwargs.get("tracer_provider") + + dbapi.wrap_connect( + __name__, + pymssql, + "connect", + _DATABASE_SYSTEM, + version=__version__, + tracer_provider=tracer_provider, + # pymssql does not keep the connection attributes in its connection object; + # instead, we get the attributes from the connect method (which is done + # via PyMSSQLDatabaseApiIntegration.wrapped_connection) + db_api_integration_factory=_PyMSSQLDatabaseApiIntegration, + ) + + def _uninstrument(self, **kwargs): + """ "Disable pymssql instrumentation""" + dbapi.unwrap_connect(pymssql, "connect") + + @staticmethod + def instrument_connection(connection, tracer_provider=None): + """Enable instrumentation in a pymssql connection. + + Args: + connection: The connection to instrument. + tracer_provider: The optional tracer provider to use. If omitted + the current globally configured one is used. + + Returns: + An instrumented connection. + """ + + return dbapi.instrument_connection( + __name__, + connection, + _DATABASE_SYSTEM, + version=__version__, + tracer_provider=tracer_provider, + db_api_integration_factory=_PyMSSQLDatabaseApiIntegration, + ) + + @staticmethod + def uninstrument_connection(connection): + """Disable instrumentation in a pymssql connection. + + Args: + connection: The connection to uninstrument. + + Returns: + An uninstrumented connection. + """ + return dbapi.uninstrument_connection(connection) diff --git a/instrumentation/opentelemetry-instrumentation-pymssql/src/opentelemetry/instrumentation/pymssql/package.py b/instrumentation/opentelemetry-instrumentation-pymssql/src/opentelemetry/instrumentation/pymssql/package.py new file mode 100644 index 0000000000..92bc9e0193 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-pymssql/src/opentelemetry/instrumentation/pymssql/package.py @@ -0,0 +1,16 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +_instruments = ("pymssql >= 2.1.5, < 3",) diff --git a/instrumentation/opentelemetry-instrumentation-pymssql/src/opentelemetry/instrumentation/pymssql/version.py b/instrumentation/opentelemetry-instrumentation-pymssql/src/opentelemetry/instrumentation/pymssql/version.py new file mode 100644 index 0000000000..6e2923f0db --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-pymssql/src/opentelemetry/instrumentation/pymssql/version.py @@ -0,0 +1,15 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +__version__ = "0.51b0.dev" diff --git a/instrumentation/opentelemetry-instrumentation-pymssql/test-requirements.txt b/instrumentation/opentelemetry-instrumentation-pymssql/test-requirements.txt new file mode 100644 index 0000000000..19e4bb3e3f --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-pymssql/test-requirements.txt @@ -0,0 +1,10 @@ +exceptiongroup==1.2.2 +iniconfig==2.0.0 +packaging==24.2 +pluggy==1.5.0 +pymssql==2.3.1 +pytest==7.4.4 +tomli==2.2.1 +-e opentelemetry-instrumentation +-e instrumentation/opentelemetry-instrumentation-dbapi +-e instrumentation/opentelemetry-instrumentation-pymssql diff --git a/instrumentation/opentelemetry-instrumentation-pymssql/tests/__init__.py b/instrumentation/opentelemetry-instrumentation-pymssql/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/instrumentation/opentelemetry-instrumentation-pymssql/tests/test_pymssql_integration.py b/instrumentation/opentelemetry-instrumentation-pymssql/tests/test_pymssql_integration.py new file mode 100644 index 0000000000..ccd522b165 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-pymssql/tests/test_pymssql_integration.py @@ -0,0 +1,184 @@ +# Copyright The OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest.mock import Mock, patch + +import pymssql # type: ignore + +import opentelemetry.instrumentation.pymssql +from opentelemetry.instrumentation.pymssql import PyMSSQLInstrumentor +from opentelemetry.sdk import resources +from opentelemetry.test.test_base import TestBase + + +def mock_connect(*args, **kwargs): + class MockConnection: + def cursor(self): + # pylint: disable=no-self-use + return Mock() + + return MockConnection() + + +class TestPyMSSQLIntegration(TestBase): + def tearDown(self): + super().tearDown() + with self.disable_logging(): + PyMSSQLInstrumentor().uninstrument() + + def _execute_query_and_get_span(self, cnx): + cursor = cnx.cursor() + query = "SELECT * FROM test" + cursor.execute(query) + + spans_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans_list), 1) + span = spans_list[0] + + # Check version and name in span's instrumentation info + self.assertEqualSpanInstrumentationScope( + span, opentelemetry.instrumentation.pymssql + ) + return span + + @patch("pymssql.connect", new=mock_connect) + # pylint: disable=unused-argument + def test_instrumentor(self): + PyMSSQLInstrumentor().instrument() + + cnx = pymssql.connect( # pylint: disable=no-member + host="dbserver.local:1433", + database="testdb", + user="dbuser", + password="dbpassw0rd", + charset="UTF-8", + tds_version="7.1", + ) + span = self._execute_query_and_get_span(cnx) + + self.assertEqual(span.attributes["db.system"], "mssql") + self.assertEqual(span.attributes["db.name"], "testdb") + self.assertEqual(span.attributes["db.statement"], "SELECT * FROM test") + self.assertEqual(span.attributes["db.user"], "dbuser") + self.assertEqual(span.attributes["net.peer.name"], "dbserver.local") + self.assertEqual(span.attributes["net.peer.port"], "1433") + self.assertEqual(span.attributes["db.charset"], "UTF-8") + self.assertEqual(span.attributes["db.protocol.tds.version"], "7.1") + + # check that no spans are generated after uninstrument + PyMSSQLInstrumentor().uninstrument() + + cnx = pymssql.connect(database="test") # pylint: disable=no-member + cursor = cnx.cursor() + query = "SELECT * FROM test" + cursor.execute(query) + + spans_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans_list), 1) + + @patch("pymssql.connect", new=mock_connect) + # pylint: disable=unused-argument + def test_instrumentor_server_param(self): + PyMSSQLInstrumentor().instrument() + + # `server` can be used instead of `host` + cnx = pymssql.connect(server="dbserver.local:1433", database="testdb") # pylint: disable=no-member + span = self._execute_query_and_get_span(cnx) + + self.assertEqual(span.attributes["net.peer.name"], "dbserver.local") + self.assertEqual(span.attributes["net.peer.port"], "1433") + + @patch("pymssql.connect", new=mock_connect) + # pylint: disable=unused-argument + def test_instrumentor_port_param(self): + PyMSSQLInstrumentor().instrument() + + # port can be specified as a parameter + cnx = pymssql.connect( # pylint: disable=no-member + server="dbserver.local", port="1433", database="testdb" + ) + span = self._execute_query_and_get_span(cnx) + + self.assertEqual(span.attributes["net.peer.name"], "dbserver.local") + self.assertEqual(span.attributes["net.peer.port"], "1433") + + @patch("pymssql.connect", new=mock_connect) + # pylint: disable=unused-argument + def test_instrumentor_windows_server(self): + PyMSSQLInstrumentor().instrument() + + # Windows server names can include special characters + cnx = pymssql.connect(server=r"(local)\SQLEXPRESS", database="testdb") # pylint: disable=no-member + span = self._execute_query_and_get_span(cnx) + + self.assertEqual( + span.attributes["net.peer.name"], r"(local)\SQLEXPRESS" + ) + + @patch("pymssql.connect", new=mock_connect) + # pylint: disable=unused-argument + def test_custom_tracer_provider(self): + resource = resources.Resource.create({}) + result = self.create_tracer_provider(resource=resource) + tracer_provider, exporter = result + + PyMSSQLInstrumentor().instrument(tracer_provider=tracer_provider) + + cnx = pymssql.connect(database="test") # pylint: disable=no-member + cursor = cnx.cursor() + query = "SELECT * FROM test" + cursor.execute(query) + + spans_list = exporter.get_finished_spans() + self.assertEqual(len(spans_list), 1) + span = spans_list[0] + + self.assertIs(span.resource, resource) + + @patch("pymssql.connect", new=mock_connect) + # pylint: disable=unused-argument + def test_instrument_connection(self): + cnx = pymssql.connect(database="test") # pylint: disable=no-member + query = "SELECT * FROM test" + cursor = cnx.cursor() + cursor.execute(query) + + spans_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans_list), 0) + + cnx = PyMSSQLInstrumentor().instrument_connection(cnx) + cursor = cnx.cursor() + cursor.execute(query) + + spans_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans_list), 1) + + @patch("pymssql.connect", new=mock_connect) + # pylint: disable=unused-argument + def test_uninstrument_connection(self): + PyMSSQLInstrumentor().instrument() + cnx = pymssql.connect(database="test") # pylint: disable=no-member + query = "SELECT * FROM test" + cursor = cnx.cursor() + cursor.execute(query) + + spans_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans_list), 1) + + cnx = PyMSSQLInstrumentor().uninstrument_connection(cnx) + cursor = cnx.cursor() + cursor.execute(query) + + spans_list = self.memory_exporter.get_finished_spans() + self.assertEqual(len(spans_list), 1) diff --git a/opentelemetry-contrib-instrumentations/pyproject.toml b/opentelemetry-contrib-instrumentations/pyproject.toml index e19c0d69d8..9c0ab886d5 100644 --- a/opentelemetry-contrib-instrumentations/pyproject.toml +++ b/opentelemetry-contrib-instrumentations/pyproject.toml @@ -64,6 +64,7 @@ dependencies = [ "opentelemetry-instrumentation-psycopg2==0.51b0.dev", "opentelemetry-instrumentation-pymemcache==0.51b0.dev", "opentelemetry-instrumentation-pymongo==0.51b0.dev", + "opentelemetry-instrumentation-pymssql==0.51b0.dev", "opentelemetry-instrumentation-pymysql==0.51b0.dev", "opentelemetry-instrumentation-pyramid==0.51b0.dev", "opentelemetry-instrumentation-redis==0.51b0.dev", diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py index cea9e3e11f..f28ebfb41b 100644 --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py @@ -156,6 +156,10 @@ "library": "pymongo >= 3.1, < 5.0", "instrumentation": "opentelemetry-instrumentation-pymongo==0.51b0.dev", }, + { + "library": "pymssql >= 2.1.5, < 3", + "instrumentation": "opentelemetry-instrumentation-pymssql==0.51b0.dev", + }, { "library": "PyMySQL < 2", "instrumentation": "opentelemetry-instrumentation-pymysql==0.51b0.dev", diff --git a/tox.ini b/tox.ini index 22e56a835f..b45b6b4d4c 100644 --- a/tox.ini +++ b/tox.ini @@ -243,6 +243,12 @@ envlist = pypy3-test-instrumentation-pymysql lint-instrumentation-pymysql + ; opentelemetry-instrumentation-pymssql + py3{8,9,10,11,12,13}-test-instrumentation-pymssql + ; pymssql has no support for pypy: see https://github.com/pymssql/pymssql/pull/517 + ; pypy3-test-instrumentation-pymssql + lint-instrumentation-pymssql + ; opentelemetry-instrumentation-pyramid ; TODO: add py313 when supported by pyramid py3{8,9,10,11,12}-test-instrumentation-pyramid @@ -581,6 +587,9 @@ deps = pymysql: {[testenv]test_deps} pymysql: -r {toxinidir}/instrumentation/opentelemetry-instrumentation-pymysql/test-requirements.txt + pymssql: {[testenv]test_deps} + pymssql: -r {toxinidir}/instrumentation/opentelemetry-instrumentation-pymssql/test-requirements.txt + pyramid: {[testenv]test_deps} pyramid: -r {toxinidir}/instrumentation/opentelemetry-instrumentation-pyramid/test-requirements.txt @@ -829,6 +838,9 @@ commands = test-instrumentation-pymysql: pytest {toxinidir}/instrumentation/opentelemetry-instrumentation-pymysql/tests {posargs} lint-instrumentation-pymysql: sh -c "cd instrumentation && pylint --rcfile ../.pylintrc opentelemetry-instrumentation-pymysql" + test-instrumentation-pymssql: pytest {toxinidir}/instrumentation/opentelemetry-instrumentation-pymssql/tests {posargs} + lint-instrumentation-pymssql: sh -c "cd instrumentation && pylint --rcfile ../.pylintrc opentelemetry-instrumentation-pymssql" + test-instrumentation-pyramid: pytest {toxinidir}/instrumentation/opentelemetry-instrumentation-pyramid/tests {posargs} lint-instrumentation-pyramid: sh -c "cd instrumentation && pylint --rcfile ../.pylintrc opentelemetry-instrumentation-pyramid" @@ -944,6 +956,7 @@ deps = -e {toxinidir}/instrumentation/opentelemetry-instrumentation-psycopg2 -e {toxinidir}/instrumentation/opentelemetry-instrumentation-pymongo -e {toxinidir}/instrumentation/opentelemetry-instrumentation-pymysql + -e {toxinidir}/instrumentation/opentelemetry-instrumentation-pymssql -e {toxinidir}/instrumentation/opentelemetry-instrumentation-sqlalchemy -e {toxinidir}/instrumentation/opentelemetry-instrumentation-aiopg -e {toxinidir}/instrumentation/opentelemetry-instrumentation-redis