Skip to content

Commit 55e0c06

Browse files
emmettbutlerwantsuijuanjux
authored
docs: add writeup of how autoinstrumentation works [LANGPLAT-352] (#13640)
This change adds a written description of the technical design of autoinstrumentation, for the purpose of making it easier to contribute changes to the library. The new writing is in `contributing-design.rst`. ## Checklist - [x] PR author has checked that all the criteria below are met - The PR description includes an overview of the change - The PR description articulates the motivation for the change - The change includes tests OR the PR description describes a testing strategy - The PR description notes risks associated with the change, if any - Newly-added code is easy to change - The change follows the [library release note guidelines](https://ddtrace.readthedocs.io/en/stable/releasenotes.html) - The change includes or references documentation updates if necessary - Backport labels are set (if [applicable](https://ddtrace.readthedocs.io/en/latest/contributing.html#backporting)) ## Reviewer Checklist - [x] Reviewer has checked that all the criteria below are met - Title is accurate - All changes are related to the pull request's stated goal - Avoids breaking [API](https://ddtrace.readthedocs.io/en/stable/versioning.html#interfaces) changes - Testing strategy adequately addresses listed risks - Newly-added code is easy to change - Release note makes sense to a user of the library - If necessary, author has acknowledged and discussed the performance implications of this PR as reported in the benchmarks PR comment - Backport labels are set in a manner that is consistent with the [release branch maintenance policy](https://ddtrace.readthedocs.io/en/latest/contributing.html#backporting) --------- Co-authored-by: wantsui <wan.tsui@datadoghq.com> Co-authored-by: Juanjo Alvarez Martinez <juanjo.alvarezmartinez@datadoghq.com>
1 parent 1b249e1 commit 55e0c06

File tree

3 files changed

+117
-30
lines changed

3 files changed

+117
-30
lines changed

docs/contributing-design.rst

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
The Design of dd-trace-py
2+
=========================
3+
4+
Parts of the Library
5+
--------------------
6+
7+
When designing a change, one of the first decisions to make is where it should be made. This is an overview
8+
of the main functional areas of the library.
9+
10+
A **product** is a unit of code within the library that implements functionality specific to a small set of
11+
customer-facing Datadog products. Examples include the `appsec module <https://github.com/DataDog/dd-trace-py/tree/1.x/ddtrace/appsec>`_
12+
implementing functionality for `App and API Protection <https://www.datadoghq.com/product/application-security-management/>`_
13+
and the `profiling <https://github.com/DataDog/dd-trace-py/tree/1.x/ddtrace/profiling>`_ module implementing
14+
functionality for `Continuous Profiling <https://docs.datadoghq.com/profiler/>`_. Ideally it only contains code
15+
that is specific to the Datadog product being supported, and no code related to Integrations.
16+
17+
An **integration** is one of the modules in the `contrib <https://github.com/DataDog/dd-trace-py/tree/f26a526a6f79870e6e6a21d281f4796a434616bb/ddtrace/contrib>`_
18+
directory, hooking our code into the internal logic of a given Python library. Ideally it only contains code
19+
that is specific to the library being integrated with, and no code related to Products.
20+
21+
The **core** of the library is the abstraction layer that allows Products and Integrations to keep their concerns
22+
separate. It is implemented in the Python files in the `top level of ddtracepy <https://github.com/DataDog/dd-trace-py/tree/main/ddtrace>`_
23+
and in the `internal` module. As an implementation detail, the core logic also happens to directly support
24+
`Application Performance Monitoring <https://docs.datadoghq.com/tracing/>`_.
25+
26+
Be mindful and intentional about which of these categories your change fits into, and avoid mixing concerns between
27+
categories. If doing so requires more foundational refactoring or additional layers of abstraction, consider
28+
opening an issue describing the limitations of the current design.
29+
30+
31+
How Autoinstrumentation Works
32+
-----------------------------
33+
34+
Autoinstrumentation is the feature of dd-trace-py that hooks into application code to facilitate application-level
35+
product functionality, for example the detailed traces visible in Datadog Application Monitoring. This is an
36+
overview of the technical implementation of this hooking functionality.
37+
38+
This is the series of steps involved in autoinstrumentation:
39+
40+
1. import bootstrap.sitecustomize, preload, clean up loaded modules, execute preexisting sitecustomizes
41+
2. start products
42+
3. set up an import hook for each integration
43+
4. when an integrated-with module is imported, the import hook calls the contrib's patch(). patch() replaces important functions in the module with transparent wrappers.
44+
5. These wrappers use the core API to create a tree of ExecutionContext objects. The context tree is traversed
45+
to generate the data to send to product intake.
46+
47+
Step 1: Bootstrap
48+
-----------------
49+
50+
The autoinstrumentation entrypoint is `import ddtrace.bootstrap.sitecustomize`. This can be done in user code, either directly or via
51+
`import ddtrace.auto`, or behind the scenes by `ddtrace-run`.
52+
53+
ddtrace's sitecustomize script's basic goal is to start the Products that the library implements.
54+
These are subpackages like `_trace`, `profiling`, `debugging`, `appsec`, et cetera. Before starting these Products,
55+
some setup has to happen, especially the execution of preexisting PEP648 `sitecustomize` scripts to maintain
56+
user-facing guarantees about the runtime environment in which the application will execute. ddtrace's sitecustomize
57+
also attempts to "leave no trace" on the runtime environment, especially by unloading all of the modules it has
58+
used in the course of its setup phases. This helps reduce the possibility that ddtrace will use the same copy of
59+
an integrated-with module that the application uses, which can lead to undefined behavior.
60+
61+
Step 2: Start Products
62+
----------------------
63+
64+
The Products implemented by the library conform to a Product Manager Protocol, which controls common functionality
65+
like setup, start, and stop. Each enabled Product module is loaded into the Manager instance on import, which happens in
66+
sitecustomize. In turn, sitecustomize runs the Protocol with `manager.run_protocol()` and later runs additional Product
67+
setup steps via `preload.post_preload`. Together, these calls comprise the setup of Products that will operate during the
68+
application's lifetime.
69+
70+
Step 3: Set Up Import Hooks
71+
---------------------------
72+
73+
The core functionality set up during step 2 is autoinstrumentation, which is a prerequisite for many of the other Products.
74+
75+
Autoinstrumentation setup involves registering hooks that will execute when a particular module is imported. The list of
76+
modules whose imports trigger this registration is defined in `_monkey.py`. During this step, each of these modules has an
77+
import hook registered for it. In the rest of this document, these modules are called "Instrumented Modules".
78+
79+
Note that as of this writing, autoinstrumentation is implemented as a side effect of the `_trace` Product's setup phase.
80+
In a more abstract sense, autoinstrumentation can function as its own Product, and in the future may be refactored as such.
81+
82+
Step 4: Import Occurs
83+
---------------------
84+
85+
The next step of autoinstrumentation happens when the application imports an Instrumented Module. The import triggers the
86+
import hook that was registered in step 3. The function that the hook executes has the primary goal of calling the `patch()`
87+
function of the integration module located at `ddtrace.contrib.<integration-name>.patch`.
88+
89+
The goal of an integration's `patch()` function is to invisibly wrap the Instrumented Module with logic that generates the
90+
data about the module that's necessary for any relevant Products. The most commonly used wrapping approach is based on the
91+
`wrapt` library, which is included as a vendored dependency in `ddtrace`. Another approach, employed by certain components of the appsec product, involves decompiling the imported module into its abstract syntax tree, modifying it, and then recompiling the module. Inside of the wrappers, it's common for
92+
integrations to build trees of `core.ExecutionContext` objects that store information about the running application's
93+
call stack.
94+
95+
Whatever approach is taken, this step only sets up logic that will run later.
96+
97+
Step 5: Application Logic Runs
98+
------------------------------
99+
100+
When the application uses the Instrumented Module after importing it, the wrappers created in step 4 are executed. This causes
101+
data about the running application to be collected in memory, often as a tree of `ExecutionContext` objects. Any Product
102+
that was started in step 2 may access these data and use them to build a payload to send to the relevant intake endpoints.
103+
The classic example is the `_trace` Product, which periodically traverses the context tree for the purpose of creating a `Trace`
104+
object that is subsequently serialized and sent to Datadog to power a flamegraph in the Application Observability product.

docs/contributing.rst

Lines changed: 3 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ Before working on the library, install `docker <https://www.docker.com/products/
1414

1515
If you're trying to set up a local development environment, read `this <https://github.com/DataDog/dd-trace-py/tree/main/docs/contributing-testing.rst>`_.
1616

17+
`Library design documentation for contributors <https://github.com/DataDog/dd-trace-py/tree/main/docs/contributing-design.rst>`_.
18+
1719
Thanks for working with us!
1820

1921
.. _change_process:
@@ -69,35 +71,6 @@ Each minor version has its own branch.
6971
If your pull request is a ``fix`` or ``ci`` change, apply the backport labels corresponding to the minor
7072
versions that need the change.
7173

72-
Implementation Guidelines
73-
=========================
74-
75-
Parts of the Library
76-
--------------------
77-
78-
When designing a change, one of the first decisions to make is where it should be made. This is an overview
79-
of the main functional areas of the library.
80-
81-
A **product** is a unit of code within the library that implements functionality specific to a small set of
82-
customer-facing Datadog products. Examples include the `appsec module <https://github.com/DataDog/dd-trace-py/tree/1.x/ddtrace/appsec>`_
83-
implementing functionality for `Application Security Management <https://www.datadoghq.com/product/application-security-management/>`_
84-
and the `profiling <https://github.com/DataDog/dd-trace-py/tree/1.x/ddtrace/profiling>`_ module implementing
85-
functionality for `Continuous Profiling <https://docs.datadoghq.com/profiler/>`_. Ideally it only contains code
86-
that is specific to the Datadog product being supported, and no code related to Integrations.
87-
88-
An **integration** is one of the modules in the `contrib <https://github.com/DataDog/dd-trace-py/tree/f26a526a6f79870e6e6a21d281f4796a434616bb/ddtrace/contrib>`_
89-
directory, hooking our code into the internal logic of a given Python library. Ideally it only contains code
90-
that is specific to the library being integrated with, and no code related to Products.
91-
92-
The **core** of the library is the abstraction layer that allows Products and Integrations to keep their concerns
93-
separate. It is implemented in the Python files in the `top level of ddtracepy <https://github.com/DataDog/dd-trace-py/tree/main/ddtrace>`_
94-
and in the `internal` module. As an implementation detail, the core logic also happens to directly support
95-
`Application Performance Monitoring <https://docs.datadoghq.com/tracing/>`_.
96-
97-
Be mindful and intentional about which of these categories your change fits into, and avoid mixing concerns between
98-
categories. If doing so requires more foundational refactoring or additional layers of abstraction, consider
99-
opening an issue describing the limitations of the current design.
100-
10174
Tests
10275
-----
10376

@@ -137,6 +110,7 @@ Keep the following in mind when writing logging code:
137110
.. toctree::
138111
:hidden:
139112

113+
contributing-design
140114
contributing-integrations
141115
contributing-testing
142116
contributing-tracing

docs/spelling_wordlist.txt

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ asyncio
2727
asyncpg
2828
attrs
2929
autodetected
30+
autoinstrumentation
31+
Autoinstrumentation
3032
autopatching
3133
autoreload
3234
autoreloading
@@ -48,6 +50,7 @@ boto
4850
botocore
4951
cassandra
5052
cattrs
53+
cetera
5154
CGroup
5255
cgroups
5356
cherrypy
@@ -76,6 +79,7 @@ datastores
7679
dbapi
7780
ddtrace
7881
deallocating
82+
decompiling
7983
deprecations
8084
DES
8185
deserializing
@@ -106,6 +110,7 @@ exec
106110
Fargate
107111
fastapi
108112
Firehose
113+
flamegraph
109114
fnmatch
110115
formatter
111116
freezegun
@@ -213,6 +218,7 @@ posix
213218
postgres
214219
pre
215220
preconfigured
221+
preload
216222
prepend
217223
prepended
218224
profiler
@@ -259,6 +265,8 @@ serializable
259265
serverless
260266
Serverless
261267
sha
268+
sitecustomize
269+
sitecustomizes
262270
sns
263271
SpanContext
264272
sql
@@ -278,6 +286,7 @@ subdirectory
278286
subdomains
279287
submodule
280288
submodules
289+
subpackages
281290
Subprocess
282291
substring
283292
suitespec
@@ -326,4 +335,4 @@ Wrapt
326335
wsgi
327336
xfail
328337
yaaredis
329-
openai-agents
338+
openai-agents

0 commit comments

Comments
 (0)