Xuanwo commented on code in PR #3134: URL: https://github.com/apache/incubator-opendal/pull/3134#discussion_r1329895475
########## core/src/layers/prometheus_client.rs: ########## @@ -0,0 +1,669 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +use std::fmt::Debug; +use std::fmt::Formatter; +use std::io; +use std::sync::Arc; +use std::task::Context; +use std::task::Poll; +use std::time::Instant; + +use async_trait::async_trait; +use bytes::Bytes; +use futures::FutureExt; +use futures::TryFutureExt; +use prometheus_client::metrics::counter::Counter; +use prometheus_client::metrics::family::Family; +use prometheus_client::metrics::histogram::Histogram; +use prometheus_client::registry::Registry; + +use crate::raw::Accessor; +use crate::raw::*; +use crate::*; + +/// Add [prometheus](https://docs.rs/prometheus) for every operations. +/// +/// # Examples +/// +/// ``` +/// use log::debug; +/// use log::info; +/// use opendal::layers::PrometheusClientLayer; +/// use opendal::services; +/// use opendal::Operator; +/// use opendal::Result; +/// +/// /// Visit [`opendal::services`] for more service related config. +/// /// Visit [`opendal::Operator`] for more operator level APIs. +/// #[tokio::main] +/// async fn main() -> Result<()> { +/// // Pick a builder and configure it. +/// let builder = services::Memory::default(); +/// let mut registry = prometheus_client::registry::Registry::default(); +/// +/// let op = Operator::new(builder) +/// .expect("must init") +/// .layer(PrometheusClientLayer::with_registry(&mut registry)) +/// .finish(); +/// debug!("operator: {op:?}"); +/// +/// // Write data into object test. +/// op.write("test", "Hello, World!").await?; +/// // Read data from object. +/// let bs = op.read("test").await?; +/// info!("content: {}", String::from_utf8_lossy(&bs)); +/// +/// // Get object metadata. +/// let meta = op.stat("test").await?; +/// info!("meta: {:?}", meta); +/// +/// // Export prometheus metrics. +/// let mut buf = String::new(); +/// prometheus_client::encoding::text::encode(&mut buf, ®istry).unwrap(); +/// println!("## Prometheus Metrics"); +/// println!("{}", buf); +/// Ok(()) +/// } +/// ``` +#[derive(Debug)] +pub struct PrometheusClientLayer { + metrics: PrometheusClientMetrics, +} + +impl PrometheusClientLayer { + /// create PrometheusClientLayer while registering itself to this registry. + pub fn with_registry(registry: &mut Registry) -> Self { + let metrics = PrometheusClientMetrics::register(registry); + Self { metrics } + } +} + +impl<A: Accessor> Layer<A> for PrometheusClientLayer { + type LayeredAccessor = PrometheusAccessor<A>; + + fn layer(&self, inner: A) -> Self::LayeredAccessor { + let meta = inner.info(); + let scheme = meta.scheme(); + + let stats = Arc::new(self.metrics.clone()); + PrometheusAccessor { + inner, + stats, + scheme: scheme.to_string(), + } + } +} + +type VecLabels = Vec<(&'static str, String)>; + +/// [`PrometheusClientMetrics`] provide the performance and IO metrics with the `prometheus-client` crate. +#[derive(Debug, Clone)] +struct PrometheusClientMetrics { + /// Total counter of the specific operation be called. + requests_total: Family<VecLabels, Counter>, + /// Latency of the specific operation be called. + request_duration_seconds: Family<VecLabels, Histogram>, + /// The histogram of bytes + bytes_histogram: Family<VecLabels, Histogram>, +} + +impl PrometheusClientMetrics { + pub fn register(registry: &mut Registry) -> Self { + let requests_total = Family::default(); + let request_duration_seconds = Family::<VecLabels, _>::new_with_constructor(|| { + let buckets = prometheus_client::metrics::histogram::exponential_buckets(0.01, 2.0, 16); + Histogram::new(buckets) + }); + let bytes_histogram = Family::<VecLabels, _>::new_with_constructor(|| { + let buckets = prometheus_client::metrics::histogram::exponential_buckets(1.0, 2.0, 16); + Histogram::new(buckets) + }); + + registry.register("requests_total", "", requests_total.clone()); + registry.register( + "request_duration_seconds", + "", + request_duration_seconds.clone(), + ); + registry.register("bytes_histogram", "", bytes_histogram.clone()); + Self { + requests_total, + request_duration_seconds, + bytes_histogram, + } + } + + fn increment_errors_total(&self, op: Operation, kind: ErrorKind) { + let labels = vec![("operation", op.to_string()), ("kind", kind.to_string())]; + self.requests_total.get_or_create(&labels).inc(); + } + + fn increment_request_total(&self, scheme: &str, op: Operation) { + let labels = vec![ + ("scheme", scheme.to_string()), + ("operation", op.to_string()), + ]; + self.requests_total.get_or_create(&labels).inc(); + } + + fn observe_bytes_total(&self, scheme: &str, op: Operation, bytes: usize) { + let labels = vec![ + ("scheme", scheme.to_string()), + ("operation", op.to_string()), + ]; + self.bytes_histogram + .get_or_create(&labels) + .observe(bytes as f64); + } + + fn observe_request_duration(&self, scheme: &str, op: Operation, duration: std::time::Duration) { + let labels = vec![ + ("scheme", scheme.to_string()), + ("operation", op.to_string()), + ]; + self.request_duration_seconds + .get_or_create(&labels) + .observe(duration.as_secs_f64()); + } +} + +#[derive(Clone)] +pub struct PrometheusAccessor<A: Accessor> { + inner: A, + stats: Arc<PrometheusClientMetrics>, + scheme: String, +} + +impl<A: Accessor> Debug for PrometheusAccessor<A> { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PrometheusAccessor") + .field("inner", &self.inner) + .finish_non_exhaustive() + } +} + +#[async_trait] +impl<A: Accessor> LayeredAccessor for PrometheusAccessor<A> { + type Inner = A; + type Reader = PrometheusMetricWrapper<A::Reader>; + type BlockingReader = PrometheusMetricWrapper<A::BlockingReader>; + type Writer = PrometheusMetricWrapper<A::Writer>; + type BlockingWriter = PrometheusMetricWrapper<A::BlockingWriter>; + type Pager = A::Pager; + type BlockingPager = A::BlockingPager; + + fn inner(&self) -> &Self::Inner { + &self.inner + } + + async fn create_dir(&self, path: &str, args: OpCreateDir) -> Result<RpCreateDir> { + self.stats + .increment_request_total(&self.scheme, Operation::CreateDir); + + let start_time = Instant::now(); + let create_res = self.inner.create_dir(path, args).await; + + self.stats.observe_request_duration( + &self.scheme, + Operation::CreateDir, + start_time.elapsed(), + ); + create_res.map_err(|e| { + self.stats + .increment_errors_total(Operation::CreateDir, e.kind()); + e + }) + } + + async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> { + self.stats + .increment_request_total(&self.scheme, Operation::Read); + let start_time = Instant::now(); + + let read_res = self + .inner + .read(path, args) + .map(|v| { + v.map(|(rp, r)| { + self.stats.observe_bytes_total( + &self.scheme, + Operation::Read, + rp.metadata().content_length() as usize, Review Comment: Yes, I believe they are wrong. I will take a look over `PrometheusLayer` later. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
