Debian Codegraph @

docs/rfcs/processing.md

raw
1 # OpenTelemetry Collector Processor Exploration
2
3 **Status:** *Draft*
4
5 ## Objective
6
7 To describe a user experience and strategies for configuring processors in the OpenTelemetry collector.
8
9 This work is being prototyped in opentelemetry-collector-contrib, the design doc is here for broader discussion.
10
11 ## Summary
12
13 The OpenTelemetry (OTel) collector is a tool to set up pipelines to receive telemetry from an application and export it
14 to an observability backend. Part of the pipeline can include processing stages, which executes various business logic
15 on incoming telemetry before it is exported.
16
17 Over time, the collector has added various processors to satisfy different use cases, generally in an ad-hoc way to
18 support each feature independently. We can improve the experience for users of the collector by consolidating processing
19 patterns in terms of user experience, and this can be supported by defining a querying model for processors
20 within the collector core, and likely also for use in SDKs, to simplify implementation and promote the consistent user
21 experience and best practices.
22
23 ## Goals and non-goals
24
25 Goals:
26 - List out use cases for processing within the collector
27 - Consider what could be an ideal configuration experience for users
28
29 Non-Goals:
30 - Merge every processor into one. Many use cases overlap and generalize, but not all of them
31 - Technical design or implementation of configuration experience. Currently focused on user experience.
32
33 ## Use cases for processing
34
35 ### Telemetry mutation
36
37 Processors can be used to mutate the telemetry in the collector pipeline. OpenTelemetry SDKs collect detailed telemetry
38 from applications, and it is common to have to mutate this into a way that is appropriate for an individual use case.
39
40 Some types of mutation include
41
42 - Remove a forbidden attribute such as `http.request.header.authorization`
43 - Reduce cardinality of an attribute such as translating `http.target` value of `/user/123451/profile` to `/user/{userId}/profile`
44 - Decrease the size of the telemetry payload by removing large resource attributes such as `process.command_line`
45 - Filtering out signals such as by removing all telemetry with a `http.target` of `/health`
46 - Attach information from resource into telemetry, for example adding certain resource fields as metric dimensions
47
48 The processors implementing this use case are `attributesprocessor`, `filterprocessor`, `metricstransformprocessor`,
49 `resourceprocessor`, `spanprocessor`.
50
51 ### Metric generation
52
53 The collector may generate new metrics based on incoming telemetry. This can be for covering gaps in SDK coverage of
54 metrics vs spans, or to create new metrics based on existing ones to model the data better for backend-specific
55 expectations.
56
57 - Create new metrics based on information in spans, for example to create a duration metric that is not implemented in the SDK yet
58 - Apply arithmetic between multiple incoming metrics to produce an output one, for example divide an `amount` and a `capacity` to create a `utilization` metric
59
60 The components implementing this use case are `metricsgenerationprocessor` and the former `spanmetricsprocessor` (now `spanmetricsconnector`).
61
62 ### Grouping
63
64 Some processors are stateful, grouping telemetry over a window of time based on either a trace ID or an attribute value,
65 or just general batching.
66
67 - Batch incoming telemetry before sending to exporters to reduce export requests
68 - Group spans by trace ID to allow doing tail sampling
69 - Group telemetry for the same path
70
71 The processors implementing this use case are `batchprocessor`, `groupbyattrprocessor`, `groupbytraceprocessor`.
72
73 ### Metric temporality
74
75 Two processors convert between the two types of temporality, cumulative and delta. The conversion is generally expected
76 to happen as close to the source data as possible, for example within receivers themselves. The same configuration
77 mechanism could be used for selecting metrics for temporality conversion as other cases, but it is expected that in
78 practice configuration will be limited.
79
80 The processors implementing this use case are `cumulativetodeltaprocessor`.
81
82 ### Telemetry enrichment
83
84 OpenTelemetry SDKs focus on collecting application specific data. They also may include resource detectors to populate
85 environment specific data but the collector is commonly used to fill gaps in coverage of environment specific data.
86
87 - Add environment about a cloud provider to `Resource` of all incoming telemetry
88
89 The processors implementing this use case are `k8sattributesprocessor`, `resourcedetectionprocessor`.
90
91 ## OpenTelemetry Transformation Language
92
93 When looking at the use cases, there are certain common features for telemetry mutation and metric generation.
94
95 - Identify the type of signal (`span`, `metric`, `log`).
96 - Navigate to a path within the telemetry to operate on it
97 - Define an operation, and possibly operation arguments
98
99 We can try to model these into a transformation language, in particular allowing the first two points to be shared among all
100 processing operations, and only have implementation of individual types of processing need to implement operators that
101 the user can use within an expression.
102
103 Telemetry is modeled in the collector as [`pdata`](https://github.com/open-telemetry/opentelemetry-collector/tree/main/pdata)
104 which is roughly a 1:1 mapping of the [OTLP protocol](https://github.com/open-telemetry/opentelemetry-proto/tree/main/opentelemetry/proto).
105 This data can be navigated using field expressions, which are fields within the protocol separated by dots. For example,
106 the status message of a span is `status.message`. A map lookup can include the key as a string, for example `attributes["http.status_code"]`.
107
108 Operations are scoped to the type of a signal (`span`, `metric`, `log`), with all of the flattened points of that
109 signal being part of a transformation space. Virtual fields are added to access data from a higher level before flattening, for
110 `resource`, `library_info`. For metrics, the structure presented for processing is actual data points, e.g. `NumberDataPoint`,
111 `HistogramDataPoint`, with the information from higher levels like `Metric` or the data type available as virtual fields.
112
113 Virtual fields for all signals: `resource`, `library_info`.
114 Virtual fields for metrics: `metric`, which contains `name`, `description`, `unit`, `type`, `aggregation_temporality`, and `is_monotonic`.
115
116 Navigation can then be used with a simple expression language for identifying telemetry to operate on.
117
118 ```
119 ... where name = "GET /cats"
120 ```
121 ```
122 ... from span where attributes["http.target"] = "/health"
123 ```
124 ```
125 ... where resource.attributes["deployment"] = "canary"
126 ```
127 ```
128 ... from metric where metric.type = gauge
129 ```
130 ```
131 ... from metric where metric.name = "http.active_requests"
132 ```
133
134 Fields should always be fully specified - for example `attributes` refers to the `attributes` field in the telemetry, not
135 the `resource`. In the future, we may allow shorthand for accessing scoped information that is not ambiguous.
136
137 Having selected telemetry to operate on, any needed operations can be defined as functions. Known useful functions should
138 be implemented within the collector itself, provide registration from extension modules to allow customization with
139 contrib components, and in the future can even allow user plugins possibly through WASM, similar to work in
140 [HTTP proxies](https://github.com/proxy-wasm/spec). The arguments to operations will primarily be field expressions,
141 allowing the operation to mutate telemetry as needed.
142
143 There are times when the transformation language input and the underlying telemetry model do not translate cleanly. For example, a span ID is represented in pdata as a SpanID struct, but in the transformation language it is more natural to represent the span ID as a string or a byte array. The solution to this problem is Factories. Factories are functions that help translate between the transformation language input into the underlying pdata structure. These types of functions do not change the telemetry in any way. Instead, they manipulate the transformation language input into a form that will make working with the telemetry easier or more efficient.
144
145 ### Examples
146
147 These examples contain a SQL-like declarative language. Applied statements interact with only one signal, but statements can be declared across multiple signals.
148
149 Remove a forbidden attribute such as `http.request.header.authorization` from spans only
150
151 ```
152 traces:
153 delete(attributes["http.request.header.authorization"])
154 metrics:
155 delete(attributes["http.request.header.authorization"])
156 logs:
157 delete(attributes["http.request.header.authorization"])
158 ```
159
160 Remove all attributes except for some
161
162 ```
163 traces:
164 keep_keys(attributes, "http.method", "http.status_code")
165 metrics:
166 keep_keys(attributes, "http.method", "http.status_code")
167 logs:
168 keep_keys(attributes, "http.method", "http.status_code")
169 ```
170
171 Reduce cardinality of an attribute
172
173 ```
174 traces:
175 replace_match(attributes["http.target"], "/user/*/list/*", "/user/{userId}/list/{listId}")
176 ```
177
178 Reduce cardinality of a span name
179
180 ```
181 traces:
182 replace_match(name, "GET /user/*/list/*", "GET /user/{userId}/list/{listId}")
183 ```
184
185 Reduce cardinality of any matching attribute
186
187 ```
188 traces:
189 replace_all_matches(attributes, "/user/*/list/*", "/user/{userId}/list/{listId}")
190 ```
191
192 Decrease the size of the telemetry payload by removing large resource attributes
193
194 ```
195 traces:
196 delete(resource.attributes["process.command_line"])
197 metrics:
198 delete(resource.attributes["process.command_line"])
199 logs:
200 delete(resource.attributes["process.command_line"])
201 ```
202
203 Filtering out signals such as by removing all metrics with a `http.target` of `/health`
204
205 ```
206 metrics:
207 drop() where attributes["http.target"] = "/health"
208 ```
209
210 Attach information from resource into telemetry, for example adding certain resource fields as metric attributes
211
212 ```
213 metrics:
214 set(attributes["k8s_pod"], resource.attributes["k8s.pod.name"])
215 ```
216
217 Group spans by trace ID
218
219 ```
220 traces:
221 group_by(trace_id, 2m)
222 ```
223
224
225 Update a spans ID
226
227 ```
228 logs:
229 set(span_id, SpanID(0x0000000000000000))
230 traces:
231 set(span_id, SpanID(0x0000000000000000))
232 ```
233
234 Create utilization metric from base metrics. Because navigation expressions only operate on a single piece of telemetry,
235 helper functions for reading values from other metrics need to be provided.
236
237 ```
238 metrics:
239 create_gauge("pod.cpu.utilized", read_gauge("pod.cpu.usage") / read_gauge("node.cpu.limit")
240 ```
241
242 A lot of processing. Queries are executed in order. While initially performance may degrade compared to more specialized
243 processors, the expectation is that over time, the transform processor's engine would improve to be able to apply optimizations
244 across queries, compile into machine code, etc.
245
246 ```yaml
247 receivers:
248 otlp:
249
250 exporters:
251 otlp:
252
253 processors:
254 transform:
255 # Assuming group_by is defined in a contrib extension module, not baked into the "transform" processor
256 extensions: [group_by]
257 traces:
258 queries:
259 - drop() where attributes["http.target"] = "/health"
260 - delete(attributes["http.request.header.authorization"])
261 - replace_wildcards("/user/*/list/*", "/user/{userId}/list/{listId}", attributes["http.target"])
262 - group_by(trace_id, 2m)
263 metrics:
264 queries:
265 - drop() where attributes["http.target"] = "/health"
266 - delete(attributes["http.request.header.authorization"])
267 - replace_wildcards("/user/*/list/*", "/user/{userId}/list/{listId}", attributes["http.target"])
268 - set(attributes["k8s_pod"], resource.attributes["k8s.pod.name"])
269 logs:
270 queries:
271 - drop() where attributes["http.target"] = "/health"
272 - delete(attributes["http.request.header.authorization"])
273 - replace_wildcards("/user/*/list/*", "/user/{userId}/list/{listId}", attributes["http.target"])
274
275 pipelines:
276 - receivers: [otlp]
277 exporters: [otlp]
278 processors: [transform]
279 ```
280
281 The expressions would be executed in order, with each expression either mutating an input telemetry, dropping input
282 telemetry, or adding additional telemetry. One caveat to note is that we would like to implement optimizations
283 in the transform engine, for example to only apply filtering once for multiple operations with a shared filter. Functions
284 with unknown side effects may cause issues with optimization we will need to explore.
285
286 ## Declarative configuration
287
288 The telemetry transformation language presents an SQL-like experience for defining telemetry transformations - it is made up of
289 the three primary components described above, however, and can be presented declaratively instead depending on what makes
290 sense as a user experience.
291
292 ```yaml
293 - type: span
294 filter:
295 match:
296 path: status.code
297 value: OK
298 operation:
299 name: drop
300 - type: all
301 operation:
302 name: delete
303 args:
304 - attributes["http.request.header.authorization"]
305 ```
306
307 An implementation of the transformation language would likely parse expressions into this sort of structure so given an SQL-like
308 implementation, it would likely be little overhead to support a YAML approach in addition.
309
310 ## Function syntax
311
312 Functions should be named and formatted according to the following standards.
313 - Function names MUST start with a verb unless it is a Factory.
314 - Factory functions MUST be UpperCamelCase and named based on the object being created.
315 - Function names that contain multiple words MUST separate those words with `_`.
316 - Functions that interact with multiple items MUST have plurality in the name. Ex: `truncate_all`, `keep_keys`, `replace_all_matches`.
317 - Functions that interact with a single item MUST NOT have plurality in the name. If a function would interact with multiple items due to a condition, like `where`, it is still considered singular. Ex: `set`, `delete`, `drop`, `replace_match`.
318 - Functions that change a specific target MUST set the target as the first parameter.
319 - Functions that take a list MUST set the list as the last parameter.
320
321 ## Implementing a processor function
322
323 The `replace_match` function may look like this.
324
325 ```go
326
327 package replaceMatch
328
329 import "regexp"
330
331 import "github.com/open-telemetry/opentelemetry/processors"
332
333 // Assuming this is not in "core"
334 processors.register("replace_match", replace_match)
335
336 func replace_match(path processors.TelemetryPath, pattern regexp.Regexp, replacement string) processors.Result {
337 val := path.Get()
338 if val == nil {
339 return processors.CONTINUE
340 }
341
342 // replace finds placeholders in "replacement" and swaps them in for regex matched substrings.
343 replaced := replace(val, pattern, replacement)
344 path.Set(replaced)
345 return processors.CONTINUE
346 }
347 ```
348
349 Here, the processor framework recognizes the second parameter of the function is `regexp.Regexp` so will compile the string
350 provided by the user in the config when processing it. Similarly for `path`, it recognizes properties of type `TelemetryPath`
351 and will resolve it to the path within a matched telemetry during execution and pass it to the function. The path allows
352 scalar operations on the field within the telemetry. The processor does not need to be aware of telemetry filtering,
353 the `where ...` clause, as that will be handled by the framework before passing to the function.
354
355 ## Embedded processors
356
357 The above describes a transformation language for configuring processing logic in the OpenTelemetry collector. There will be a
358 single processor that exposes the processing logic into the collector config; however, the logic will be implemented
359 within core packages rather than directly inside a processor. This is to ensure that where appropriate, processing
360 can be embedded into other components, for example metric processing is often most appropriate to execute within a
361 receiver based on receiver-specific requirements.
362
363 ## Limitations
364
365 There are some known issues and limitations that we hope to address while iterating on this idea.
366
367 - Handling array-typed attributes
368 - Working on a array of points, rather than a single point
369 - Metric alignment - for example defining an expression on two metrics, that may not be at the same timestamp
370 - The collector has separate pipelines per signal - while the transformation language could apply cross-signal, we will need to remain single-signal for now