common_pprof/
lib.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#[cfg(unix)]
16pub mod nix;
17
18pub mod error {
19    use std::any::Any;
20
21    use common_error::ext::ErrorExt;
22    use common_error::status_code::StatusCode;
23    use common_macro::stack_trace_debug;
24    use snafu::{Location, Snafu};
25
26    #[derive(Snafu)]
27    #[stack_trace_debug]
28    #[snafu(visibility(pub(crate)))]
29    pub enum Error {
30        #[cfg(unix)]
31        #[snafu(display("Pprof error"))]
32        Pprof {
33            #[snafu(source)]
34            error: pprof::Error,
35            #[snafu(implicit)]
36            location: Location,
37        },
38
39        #[snafu(display("Pprof is unsupported on this platform"))]
40        Unsupported {
41            #[snafu(implicit)]
42            location: Location,
43        },
44    }
45
46    pub type Result<T> = std::result::Result<T, Error>;
47
48    impl ErrorExt for Error {
49        fn status_code(&self) -> StatusCode {
50            match self {
51                #[cfg(unix)]
52                Error::Pprof { .. } => StatusCode::Unexpected,
53                Error::Unsupported { .. } => StatusCode::Unsupported,
54            }
55        }
56
57        fn as_any(&self) -> &dyn Any {
58            self
59        }
60    }
61}
62
63#[cfg(not(unix))]
64pub mod dummy {
65    use std::time::Duration;
66
67    use crate::error::{Result, UnsupportedSnafu};
68
69    /// Dummpy CPU profiler utility.
70    #[derive(Debug)]
71    pub struct Profiling {}
72
73    impl Profiling {
74        /// Creates a new profiler.
75        pub fn new(_duration: Duration, _frequency: i32) -> Profiling {
76            Profiling {}
77        }
78
79        /// Profiles and returns a generated text.
80        pub async fn dump_text(&self) -> Result<String> {
81            UnsupportedSnafu {}.fail()
82        }
83
84        /// Profiles and returns a generated flamegraph.
85        pub async fn dump_flamegraph(&self) -> Result<Vec<u8>> {
86            UnsupportedSnafu {}.fail()
87        }
88
89        /// Profiles and returns a generated proto.
90        pub async fn dump_proto(&self) -> Result<Vec<u8>> {
91            UnsupportedSnafu {}.fail()
92        }
93    }
94}
95
96#[cfg(not(unix))]
97pub use dummy::Profiling;
98#[cfg(unix)]
99pub use nix::Profiling;