Skip to main content

opendal_layer_dtrace/
lib.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18#![cfg(target_os = "linux")]
19#![doc = include_str!("../README.md")]
20#![cfg_attr(docsrs, feature(doc_cfg))]
21#![cfg_attr(docsrs, doc(auto_cfg))]
22#![deny(missing_docs)]
23use std::cell::LazyCell;
24use std::ffi::CString;
25use std::sync::Arc;
26use std::task::Poll;
27
28use bytes::Buf;
29use futures::StreamExt;
30use futures::stream::poll_fn;
31use opendal_core::raw::*;
32use opendal_core::*;
33use probe::probe;
34use probe::probe_lazy;
35
36#[cfg(test)]
37mod tests;
38
39/// Convert a probe argument to a NUL-terminated C string.
40///
41/// OpenDAL paths can contain NUL bytes, which a C string cannot represent. Such
42/// arguments are reported as an empty string instead of panicking.
43fn probe_cstring(value: &str) -> CString {
44    CString::new(value).unwrap_or_default()
45}
46
47/// `DtraceLayer` supports User Statically-Defined Tracing (USDT) on Linux.
48///
49/// Enable this experimental layer with `features = ["layers-dtrace"]` in
50/// `Cargo.toml`.
51///
52/// For now we have following probes:
53///
54/// Probe arguments are NUL-terminated C strings. OpenDAL paths can contain NUL
55/// bytes; such paths are reported as an empty string.
56///
57/// ### For Service
58///
59/// 1. ${operation}_start, arguments: path
60///     1. create_dir
61///     2. read
62///     3. write
63///     4. stat
64///     5. list
65///     6. presign
66///
67/// 2. ${operation}_end, arguments: path
68///     1. create_dir
69///     2. read
70///     3. write
71///     4. stat
72///     5. list
73///     6. presign
74///
75/// `delete_start` and `delete_end` surround deleter creation and take no arguments.
76///
77/// ### For Reader
78///
79/// 1. reader_read_start, arguments: path, range
80/// 2. reader_read_ok, arguments: path, range, length
81/// 3. reader_read_error, arguments: path, range
82///
83/// ### For Writer
84///
85/// 1. writer_write_start, arguments: path
86/// 2. writer_write_ok, arguments: path, length
87/// 3. writer_write_error, arguments: path
88/// 4. writer_abort_start, arguments: path
89/// 5. writer_abort_ok, arguments: path
90/// 6. writer_abort_error, arguments: path
91/// 7. writer_close_start, arguments: path
92/// 8. writer_close_ok, arguments: path
93/// 9. writer_close_error, arguments: path
94///
95/// ### For Lister
96///
97/// `lister_next_start`, `lister_next_ok`, and `lister_next_error` take the listing
98/// path. `lister_next_ok` covers both an entry and the end of the listing.
99///
100/// ### For Deleter
101///
102/// `deleter_delete_start`, `deleter_delete_ok`, and `deleter_delete_error` take
103/// the path passed to the deleter. `deleter_delete_ok` means the deleter
104/// accepted the request, which may still be buffered.
105///
106/// `deleter_close_start`, `deleter_close_ok`, and `deleter_close_error` take no
107/// arguments and trace the final flush.
108///
109/// ### For HTTP Transport
110///
111/// The `opendal` provider emits these probes for requests through the operator's
112/// [`OperationContext`].
113///
114/// - `http_request_start` fires before the transport fetches the request.
115/// - `http_request_ok` reports the HTTP status code when the transport returns
116///   a response, including responses with 4xx and 5xx status codes.
117/// - `http_request_error` fires when the transport returns an error.
118/// - `http_response_body_chunk` reports the byte length of each streamed chunk.
119/// - `http_response_body_end` fires when the underlying stream reports EOF.
120/// - `http_response_body_error` fires when the underlying stream returns an error.
121///
122/// Example:
123///
124/// ```no_run
125/// # use opendal_core::services;
126/// # use opendal_core::Operator;
127/// # use opendal_core::Result;
128/// # use opendal_layer_dtrace::DtraceLayer;
129/// #
130/// # #[tokio::main]
131/// # async fn main() -> Result<()> {
132/// // `Service` provides the low level APIs, we will use `Operator` normally.
133/// let op: Operator = Operator::new(services::Memory::default().root("/tmp"))?
134///     .layer(DtraceLayer::new());
135///
136/// let path = "/tmp/test.txt";
137/// for _ in 1..100000 {
138///     let bs = vec![0; 64 * 1024 * 1024];
139///     op.write(path, bs).await?;
140///     op.read(path).await?;
141/// }
142/// # Ok(())
143/// # }
144/// ```
145///
146/// Then you can use `readelf -n target/debug/examples/dtrace` to see the probes:
147///
148/// ```text
149/// Displaying notes found in: .note.stapsdt
150///   Owner                Data size        Description
151///   stapsdt              0x00000039       NT_STAPSDT (SystemTap probe descriptors)
152///     Provider: opendal
153///     Name: create_dir_start
154///     Location: 0x00000000000f8f05, Base: 0x0000000000000000, Semaphore: 0x00000000003649f8
155///     Arguments: -8@%rax
156///   stapsdt              0x00000037       NT_STAPSDT (SystemTap probe descriptors)
157///     Provider: opendal
158///     Name: create_dir_end
159///     Location: 0x00000000000f9284, Base: 0x0000000000000000, Semaphore: 0x00000000003649fa
160///     Arguments: -8@%rax
161///   stapsdt              0x0000003c       NT_STAPSDT (SystemTap probe descriptors)
162///     Provider: opendal
163///     Name: blocking_list_start
164///     Location: 0x00000000000f9487, Base: 0x0000000000000000, Semaphore: 0x0000000000364a28
165///     Arguments: -8@%rax
166///   stapsdt              0x0000003a       NT_STAPSDT (SystemTap probe descriptors)
167///     Provider: opendal
168///     Name: blocking_list_end
169///     Location: 0x00000000000f9546, Base: 0x0000000000000000, Semaphore: 0x0000000000364a2a
170///     Arguments: -8@%rax
171///   stapsdt              0x0000003c       NT_STAPSDT (SystemTap probe descriptors)
172/// ```
173#[derive(Clone, Debug, Default)]
174#[non_exhaustive]
175pub struct DtraceLayer {}
176
177impl DtraceLayer {
178    /// Create a new [`DtraceLayer`].
179    pub fn new() -> Self {
180        Self::default()
181    }
182}
183
184impl Layer for DtraceLayer {
185    fn apply_service(&self, inner: Servicer) -> Servicer {
186        Arc::new(DtraceService { inner })
187    }
188
189    fn apply_context(&self, _service: Servicer, inner: OperationContext) -> OperationContext {
190        let transport = HttpTransporter::new(DtraceHttpTransport {
191            inner: inner.http_transport().clone(),
192        });
193        inner.with_http_transport(transport)
194    }
195}
196
197struct DtraceHttpTransport {
198    inner: HttpTransporter,
199}
200
201macro_rules! http_probe {
202    ($name:ident $(, $arg:expr)*) => {{
203        #[cfg(test)]
204        tests::record_probe(stringify!($name), &[$($arg as isize),*]);
205        probe!(opendal, $name $(, $arg)*);
206    }};
207}
208
209impl HttpTransport for DtraceHttpTransport {
210    async fn fetch(&self, request: http::Request<Buffer>) -> Result<http::Response<HttpBody>> {
211        http_probe!(http_request_start);
212        let response = self.inner.fetch(request).await.inspect_err(|_| {
213            http_probe!(http_request_error);
214        })?;
215        http_probe!(http_request_ok, response.status().as_u16());
216
217        Ok(response.map(|body| {
218            body.map_inner(|mut stream| {
219                Box::new(poll_fn(move |cx| {
220                    let result = stream.poll_next_unpin(cx);
221                    match &result {
222                        Poll::Ready(Some(Ok(chunk))) => {
223                            http_probe!(http_response_body_chunk, chunk.len());
224                        }
225                        Poll::Ready(Some(Err(_))) => {
226                            http_probe!(http_response_body_error);
227                        }
228                        Poll::Ready(None) => {
229                            http_probe!(http_response_body_end);
230                        }
231                        Poll::Pending => {}
232                    }
233                    result
234                }))
235            })
236        }))
237    }
238}
239
240macro_rules! operation_probe {
241    ($name:ident $(, $arg:expr)* $(,)?) => {{
242        #[cfg(test)]
243        tests::record_probe(stringify!($name), &[$($arg as isize),*]);
244        probe_lazy!(opendal, $name $(, $arg)*);
245    }};
246}
247
248#[derive(Debug)]
249struct DtraceService {
250    inner: Servicer,
251}
252
253impl Service for DtraceService {
254    type Reader = DtraceWrapper<oio::Reader>;
255    type Writer = DtraceWrapper<oio::Writer>;
256    type Lister = DtraceWrapper<oio::Lister>;
257    type Deleter = DtraceWrapper<oio::Deleter>;
258    type Copier = oio::Copier;
259    type Composer = oio::Composer;
260
261    fn info(&self) -> ServiceInfo {
262        self.inner.info()
263    }
264
265    fn capability(&self) -> Capability {
266        self.inner.capability()
267    }
268
269    fn compose(&self, ctx: &OperationContext, to: &str, args: OpCompose) -> Result<Self::Composer> {
270        self.inner.compose(ctx, to, args)
271    }
272
273    async fn create_dir(
274        &self,
275        ctx: &OperationContext,
276        path: &str,
277        args: OpCreateDir,
278    ) -> Result<RpCreateDir> {
279        let c_path = probe_cstring(path);
280        operation_probe!(create_dir_start, c_path.as_ptr());
281        let result = self.inner.create_dir(ctx, path, args).await;
282        operation_probe!(create_dir_end, c_path.as_ptr());
283        result
284    }
285
286    fn read(&self, ctx: &OperationContext, path: &str, args: OpRead) -> Result<Self::Reader> {
287        let c_path = probe_cstring(path);
288        operation_probe!(read_start, c_path.as_ptr());
289        let result = self
290            .inner
291            .read(ctx, path, args)
292            .map(|r| DtraceWrapper::new(r, path));
293        operation_probe!(read_end, c_path.as_ptr());
294        result
295    }
296
297    fn write(&self, ctx: &OperationContext, path: &str, args: OpWrite) -> Result<Self::Writer> {
298        let c_path = probe_cstring(path);
299        operation_probe!(write_start, c_path.as_ptr());
300        let result = self
301            .inner
302            .write(ctx, path, args)
303            .map(|r| DtraceWrapper::new(r, path));
304
305        operation_probe!(write_end, c_path.as_ptr());
306        result
307    }
308
309    fn copy(
310        &self,
311        ctx: &OperationContext,
312        from: &str,
313        to: &str,
314        args: OpCopy,
315    ) -> Result<Self::Copier> {
316        let c_from = probe_cstring(from);
317        operation_probe!(copy_start, c_from.as_ptr());
318        let result = self.inner.copy(ctx, from, to, args);
319        operation_probe!(copy_end, c_from.as_ptr());
320        result
321    }
322
323    async fn rename(
324        &self,
325        ctx: &OperationContext,
326        from: &str,
327        to: &str,
328        args: OpRename,
329    ) -> Result<RpRename> {
330        self.inner.rename(ctx, from, to, args).await
331    }
332
333    async fn restore(
334        &self,
335        ctx: &OperationContext,
336        path: &str,
337        args: OpRestore,
338    ) -> Result<RpRestore> {
339        self.inner.restore(ctx, path, args).await
340    }
341
342    async fn stat(&self, ctx: &OperationContext, path: &str, args: OpStat) -> Result<RpStat> {
343        let c_path = probe_cstring(path);
344        operation_probe!(stat_start, c_path.as_ptr());
345        let result = self.inner.stat(ctx, path, args).await;
346        operation_probe!(stat_end, c_path.as_ptr());
347        result
348    }
349
350    fn delete(&self, ctx: &OperationContext) -> Result<Self::Deleter> {
351        operation_probe!(delete_start);
352        let result = self
353            .inner
354            .delete(ctx)
355            .map(|deleter| DtraceWrapper::new(deleter, ""));
356        operation_probe!(delete_end);
357        result
358    }
359
360    fn list(&self, ctx: &OperationContext, path: &str, args: OpList) -> Result<Self::Lister> {
361        let c_path = probe_cstring(path);
362        operation_probe!(list_start, c_path.as_ptr());
363        let result = self
364            .inner
365            .list(ctx, path, args)
366            .map(|lister| DtraceWrapper::new(lister, path));
367        operation_probe!(list_end, c_path.as_ptr());
368        result
369    }
370
371    async fn presign(
372        &self,
373        ctx: &OperationContext,
374        path: &str,
375        args: OpPresign,
376    ) -> Result<RpPresign> {
377        let c_path = probe_cstring(path);
378        operation_probe!(presign_start, c_path.as_ptr());
379        let result = self.inner.presign(ctx, path, args).await;
380        operation_probe!(presign_end, c_path.as_ptr());
381        result
382    }
383}
384
385struct DtraceWrapper<R> {
386    inner: R,
387    path: String,
388    range: Option<BytesRange>,
389}
390
391impl<R> DtraceWrapper<R> {
392    fn new(inner: R, path: &str) -> Self {
393        Self::with_range(inner, path, None)
394    }
395
396    fn with_range(inner: R, path: &str, range: Option<BytesRange>) -> Self {
397        Self {
398            inner,
399            path: path.to_string(),
400            range,
401        }
402    }
403
404    fn range_label(&self) -> String {
405        self.range
406            .map(|range| range.to_string())
407            .unwrap_or_default()
408    }
409}
410
411impl<R: oio::ReadStream> oio::ReadStream for DtraceWrapper<R> {
412    async fn read(&mut self) -> Result<Buffer> {
413        let c_path = probe_cstring(&self.path);
414        let c_range = probe_cstring(&self.range_label());
415        operation_probe!(reader_read_start, c_path.as_ptr(), c_range.as_ptr());
416        match self.inner.read().await {
417            Ok(bs) => {
418                operation_probe!(
419                    reader_read_ok,
420                    c_path.as_ptr(),
421                    c_range.as_ptr(),
422                    bs.remaining(),
423                );
424                Ok(bs)
425            }
426            Err(e) => {
427                operation_probe!(reader_read_error, c_path.as_ptr(), c_range.as_ptr());
428                Err(e)
429            }
430        }
431    }
432}
433
434impl<R: oio::Read> oio::Read for DtraceWrapper<R> {
435    async fn open(&self, range: BytesRange) -> Result<(RpRead, Box<dyn oio::ReadStreamDyn>)> {
436        let c_path = probe_cstring(&self.path);
437        let c_range = probe_cstring(&range.to_string());
438        operation_probe!(reader_read_start, c_path.as_ptr(), c_range.as_ptr());
439        match self.inner.open(range).await {
440            Ok((rp, stream)) => {
441                operation_probe!(reader_read_ok, c_path.as_ptr(), c_range.as_ptr(), 0);
442                Ok((
443                    rp,
444                    Box::new(DtraceWrapper::with_range(stream, &self.path, Some(range)))
445                        as Box<dyn oio::ReadStreamDyn>,
446                ))
447            }
448            Err(e) => {
449                operation_probe!(reader_read_error, c_path.as_ptr(), c_range.as_ptr());
450                Err(e)
451            }
452        }
453    }
454
455    async fn read(&self, range: BytesRange) -> Result<(RpRead, Buffer)> {
456        let c_path = probe_cstring(&self.path);
457        let c_range = probe_cstring(&range.to_string());
458        operation_probe!(reader_read_start, c_path.as_ptr(), c_range.as_ptr());
459        match self.inner.read(range).await {
460            Ok((rp, buffer)) => {
461                operation_probe!(
462                    reader_read_ok,
463                    c_path.as_ptr(),
464                    c_range.as_ptr(),
465                    buffer.len(),
466                );
467                Ok((rp, buffer))
468            }
469            Err(e) => {
470                operation_probe!(reader_read_error, c_path.as_ptr(), c_range.as_ptr());
471                Err(e)
472            }
473        }
474    }
475}
476
477impl<R: oio::Write> oio::Write for DtraceWrapper<R> {
478    async fn write(&mut self, bs: Buffer) -> Result<()> {
479        let c_path = probe_cstring(&self.path);
480        let len = bs.len();
481        operation_probe!(writer_write_start, c_path.as_ptr());
482        self.inner
483            .write(bs)
484            .await
485            .map(|_| {
486                operation_probe!(writer_write_ok, c_path.as_ptr(), len);
487            })
488            .inspect_err(|_| {
489                operation_probe!(writer_write_error, c_path.as_ptr());
490            })
491    }
492
493    async fn copy_from(&mut self, path: &str, args: OpRead, range: BytesRange) -> Result<()> {
494        let c_path = probe_cstring(&self.path);
495        let len = range
496            .size()
497            .expect("writer copy range must be absolute and bounded");
498        operation_probe!(writer_write_start, c_path.as_ptr());
499        self.inner
500            .copy_from(path, args, range)
501            .await
502            .map(|_| {
503                operation_probe!(writer_write_ok, c_path.as_ptr(), len);
504            })
505            .inspect_err(|_| {
506                operation_probe!(writer_write_error, c_path.as_ptr());
507            })
508    }
509
510    async fn abort(&mut self) -> Result<()> {
511        let c_path = probe_cstring(&self.path);
512        operation_probe!(writer_abort_start, c_path.as_ptr());
513        self.inner
514            .abort()
515            .await
516            .map(|_| {
517                operation_probe!(writer_abort_ok, c_path.as_ptr());
518            })
519            .inspect_err(|_| {
520                operation_probe!(writer_abort_error, c_path.as_ptr());
521            })
522    }
523
524    async fn close(&mut self) -> Result<Metadata> {
525        let c_path = probe_cstring(&self.path);
526        operation_probe!(writer_close_start, c_path.as_ptr());
527        self.inner
528            .close()
529            .await
530            .inspect(|_| {
531                operation_probe!(writer_close_ok, c_path.as_ptr());
532            })
533            .inspect_err(|_| {
534                operation_probe!(writer_close_error, c_path.as_ptr());
535            })
536    }
537}
538
539impl<R: oio::List> oio::List for DtraceWrapper<R> {
540    async fn next(&mut self) -> Result<Option<oio::Entry>> {
541        let c_path = LazyCell::new(|| probe_cstring(self.path.as_str()));
542        operation_probe!(lister_next_start, c_path.as_ptr());
543        self.inner
544            .next()
545            .await
546            .inspect(|_| {
547                operation_probe!(lister_next_ok, c_path.as_ptr());
548            })
549            .inspect_err(|_| {
550                operation_probe!(lister_next_error, c_path.as_ptr());
551            })
552    }
553}
554
555impl<R: oio::Delete> oio::Delete for DtraceWrapper<R> {
556    async fn delete(&mut self, path: &str, args: OpDelete) -> Result<()> {
557        let c_path = LazyCell::new(|| probe_cstring(path));
558        operation_probe!(deleter_delete_start, c_path.as_ptr());
559        self.inner
560            .delete(path, args)
561            .await
562            .inspect(|_| {
563                operation_probe!(deleter_delete_ok, c_path.as_ptr());
564            })
565            .inspect_err(|_| {
566                operation_probe!(deleter_delete_error, c_path.as_ptr());
567            })
568    }
569
570    async fn close(&mut self) -> Result<()> {
571        operation_probe!(deleter_close_start);
572        self.inner
573            .close()
574            .await
575            .inspect(|_| {
576                operation_probe!(deleter_close_ok);
577            })
578            .inspect_err(|_| {
579                operation_probe!(deleter_close_error);
580            })
581    }
582}