Remove the last bits of unknown_os in the code base (#9718)

* Remove the last bits of unknown_os in the code base

* Fmt
This commit is contained in:
Bastian Köcher
2021-09-09 11:17:16 +02:00
committed by GitHub
parent a443944167
commit 129c9ed09e
28 changed files with 197 additions and 523 deletions
-2
View File
@@ -17,8 +17,6 @@ log = "0.4.8"
prometheus = { version = "0.11.0", default-features = false }
futures-util = { version = "0.3.1", default-features = false, features = ["io"] }
derive_more = "0.99"
[target.'cfg(not(target_os = "unknown"))'.dependencies]
async-std = { version = "1.6.5", features = ["unstable"] }
tokio = "1.10"
hyper = { version = "0.14.11", default-features = false, features = ["http1", "server", "tcp"] }
+87 -120
View File
@@ -15,9 +15,13 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(not(target_os = "unknown"))]
use futures_util::future::Future;
use prometheus::core::Collector;
use hyper::{
http::StatusCode,
server::Server,
service::{make_service_fn, service_fn},
Body, Request, Response,
};
pub use prometheus::{
self,
core::{
@@ -27,21 +31,14 @@ pub use prometheus::{
exponential_buckets, Error as PrometheusError, Histogram, HistogramOpts, HistogramVec, Opts,
Registry,
};
#[cfg(not(target_os = "unknown"))]
use prometheus::{Encoder, TextEncoder};
use prometheus::{core::Collector, Encoder, TextEncoder};
use std::net::SocketAddr;
#[cfg(not(target_os = "unknown"))]
mod networking;
mod sourced;
pub use sourced::{MetricSource, SourcedCounter, SourcedGauge, SourcedMetric};
#[cfg(not(target_os = "unknown"))]
pub use known_os::init_prometheus;
#[cfg(target_os = "unknown")]
pub use unknown_os::init_prometheus;
pub fn register<T: Clone + Collector + 'static>(
metric: T,
registry: &Registry,
@@ -50,126 +47,96 @@ pub fn register<T: Clone + Collector + 'static>(
Ok(metric)
}
// On WASM `init_prometheus` becomes a no-op.
#[cfg(target_os = "unknown")]
mod unknown_os {
use super::*;
#[derive(Debug, derive_more::Display, derive_more::From)]
pub enum Error {
/// Hyper internal error.
Hyper(hyper::Error),
/// Http request error.
Http(hyper::http::Error),
/// i/o error.
Io(std::io::Error),
#[display(fmt = "Prometheus port {} already in use.", _0)]
PortInUse(SocketAddr),
}
pub enum Error {}
pub async fn init_prometheus(_: SocketAddr, _registry: Registry) -> Result<(), Error> {
Ok(())
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Hyper(error) => Some(error),
Error::Http(error) => Some(error),
Error::Io(error) => Some(error),
Error::PortInUse(_) => None,
}
}
}
#[cfg(not(target_os = "unknown"))]
mod known_os {
use super::*;
use hyper::{
http::StatusCode,
server::Server,
service::{make_service_fn, service_fn},
Body, Request, Response,
};
async fn request_metrics(req: Request<Body>, registry: Registry) -> Result<Response<Body>, Error> {
if req.uri().path() == "/metrics" {
let metric_families = registry.gather();
let mut buffer = vec![];
let encoder = TextEncoder::new();
encoder.encode(&metric_families, &mut buffer).unwrap();
#[derive(Debug, derive_more::Display, derive_more::From)]
pub enum Error {
/// Hyper internal error.
Hyper(hyper::Error),
/// Http request error.
Http(hyper::http::Error),
/// i/o error.
Io(std::io::Error),
#[display(fmt = "Prometheus port {} already in use.", _0)]
PortInUse(SocketAddr),
Response::builder()
.status(StatusCode::OK)
.header("Content-Type", encoder.format_type())
.body(Body::from(buffer))
.map_err(Error::Http)
} else {
Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::from("Not found."))
.map_err(Error::Http)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Hyper(error) => Some(error),
Error::Http(error) => Some(error),
Error::Io(error) => Some(error),
Error::PortInUse(_) => None,
}
#[derive(Clone)]
pub struct Executor;
impl<T> hyper::rt::Executor<T> for Executor
where
T: Future + Send + 'static,
T::Output: Send + 'static,
{
fn execute(&self, future: T) {
async_std::task::spawn(future);
}
}
/// Initializes the metrics context, and starts an HTTP server
/// to serve metrics.
pub async fn init_prometheus(prometheus_addr: SocketAddr, registry: Registry) -> Result<(), Error> {
let listener = async_std::net::TcpListener::bind(&prometheus_addr)
.await
.map_err(|_| Error::PortInUse(prometheus_addr))?;
init_prometheus_with_listener(listener, registry).await
}
/// Init prometheus using the given listener.
async fn init_prometheus_with_listener(
listener: async_std::net::TcpListener,
registry: Registry,
) -> Result<(), Error> {
use networking::Incoming;
log::info!("〽️ Prometheus exporter started at {}", listener.local_addr()?);
let service = make_service_fn(move |_| {
let registry = registry.clone();
async move {
Ok::<_, hyper::Error>(service_fn(move |req: Request<Body>| {
request_metrics(req, registry.clone())
}))
}
}
});
async fn request_metrics(
req: Request<Body>,
registry: Registry,
) -> Result<Response<Body>, Error> {
if req.uri().path() == "/metrics" {
let metric_families = registry.gather();
let mut buffer = vec![];
let encoder = TextEncoder::new();
encoder.encode(&metric_families, &mut buffer).unwrap();
let server = Server::builder(Incoming(listener.incoming())).executor(Executor).serve(service);
Response::builder()
.status(StatusCode::OK)
.header("Content-Type", encoder.format_type())
.body(Body::from(buffer))
.map_err(Error::Http)
} else {
Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::from("Not found."))
.map_err(Error::Http)
}
}
let result = server.await.map_err(Into::into);
#[derive(Clone)]
pub struct Executor;
impl<T> hyper::rt::Executor<T> for Executor
where
T: Future + Send + 'static,
T::Output: Send + 'static,
{
fn execute(&self, future: T) {
async_std::task::spawn(future);
}
}
/// Initializes the metrics context, and starts an HTTP server
/// to serve metrics.
pub async fn init_prometheus(
prometheus_addr: SocketAddr,
registry: Registry,
) -> Result<(), Error> {
let listener = async_std::net::TcpListener::bind(&prometheus_addr)
.await
.map_err(|_| Error::PortInUse(prometheus_addr))?;
init_prometheus_with_listener(listener, registry).await
}
/// Init prometheus using the given listener.
pub(crate) async fn init_prometheus_with_listener(
listener: async_std::net::TcpListener,
registry: Registry,
) -> Result<(), Error> {
use networking::Incoming;
log::info!("〽️ Prometheus exporter started at {}", listener.local_addr()?);
let service = make_service_fn(move |_| {
let registry = registry.clone();
async move {
Ok::<_, hyper::Error>(service_fn(move |req: Request<Body>| {
request_metrics(req, registry.clone())
}))
}
});
let server =
Server::builder(Incoming(listener.incoming())).executor(Executor).serve(service);
let result = server.await.map_err(Into::into);
result
}
result
}
#[cfg(test)]
@@ -197,7 +164,7 @@ mod tests {
)
.expect("Registers the test metric");
runtime.spawn(known_os::init_prometheus_with_listener(listener, registry));
runtime.spawn(init_prometheus_with_listener(listener, registry));
runtime.block_on(async {
let client = Client::new();