Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

push-gateway support authentication #366

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions metrics-exporter-prometheus/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ metrics-util = { version = "^0.15", path = "../metrics-util", default-features =
thiserror = { version = "1", default-features = false }
quanta = { version = "0.11", default-features = false }
indexmap = { version = "1", default-features = false }
base64 = { version = "0.21.0" }
JasonLi-cn marked this conversation as resolved.
Show resolved Hide resolved

# Optional
hyper = { version = "0.14", default-features = false, features = ["tcp", "http1"], optional = true }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,12 @@ fn main() {
tracing_subscriber::fmt::init();

PrometheusBuilder::new()
.with_push_gateway("http://127.0.0.1:9091/metrics/job/example", Duration::from_secs(10))
.with_push_gateway(
"http://127.0.0.1:9091/metrics/job/example",
Duration::from_secs(10),
None,
None,
)
.expect("push gateway endpoint should be valid")
.idle_timeout(
MetricKindMask::COUNTER | MetricKindMask::HISTOGRAM,
Expand Down
44 changes: 41 additions & 3 deletions metrics-exporter-prometheus/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use hyper::{
Response, StatusCode,
};

use hyper::http::HeaderValue;
JasonLi-cn marked this conversation as resolved.
Show resolved Hide resolved
#[cfg(feature = "push-gateway")]
use hyper::{
body::{aggregate, Buf},
Expand Down Expand Up @@ -62,7 +63,12 @@ enum ExporterConfig {
// Run a push gateway task sending to the given `endpoint` after `interval` time has elapsed,
// infinitely.
#[cfg(feature = "push-gateway")]
PushGateway { endpoint: Uri, interval: Duration },
PushGateway {
endpoint: Uri,
interval: Duration,
username: Option<String>,
password: Option<String>,
},

#[allow(dead_code)]
Unconfigured,
Expand Down Expand Up @@ -157,6 +163,8 @@ impl PrometheusBuilder {
mut self,
endpoint: T,
interval: Duration,
username: Option<String>,
password: Option<String>,
) -> Result<Self, BuildError>
where
T: AsRef<str>,
Expand All @@ -165,6 +173,8 @@ impl PrometheusBuilder {
endpoint: Uri::try_from(endpoint.as_ref())
.map_err(|e| BuildError::InvalidPushGatewayEndpoint(e.to_string()))?,
interval,
username,
password,
};

Ok(self)
Expand Down Expand Up @@ -448,16 +458,22 @@ impl PrometheusBuilder {
}

#[cfg(feature = "push-gateway")]
ExporterConfig::PushGateway { endpoint, interval } => {
ExporterConfig::PushGateway { endpoint, interval, username, password } => {
let exporter = async move {
let client = Client::new();
let auth = username.as_ref().map(|name| basic_auth(name, password.as_ref()));

loop {
// Sleep for `interval` amount of time, and then do a push.
tokio::time::sleep(interval).await;

let mut builder = Request::builder();
if let Some(auth) = &auth {
builder = builder.header("authorization", auth.clone());
}

let output = handle.render();
let result = Request::builder()
let result = builder
.method(Method::PUT)
.uri(endpoint.clone())
.body(Body::from(output));
Expand Down Expand Up @@ -531,6 +547,28 @@ impl Default for PrometheusBuilder {
}
}

fn basic_auth<U, P>(username: U, password: Option<P>) -> HeaderValue
JasonLi-cn marked this conversation as resolved.
Show resolved Hide resolved
where
U: std::fmt::Display,
P: std::fmt::Display,
{
use base64::prelude::BASE64_STANDARD;
use base64::write::EncoderWriter;
use std::io::Write;

let mut buf = b"Basic ".to_vec();
{
let mut encoder = EncoderWriter::new(&mut buf, &BASE64_STANDARD);
let _ = write!(encoder, "{username}:");
if let Some(password) = password {
let _ = write!(encoder, "{password}");
}
}
let mut header = HeaderValue::from_bytes(&buf).expect("base64 is always valid HeaderValue");
header.set_sensitive(true);
header
}

JasonLi-cn marked this conversation as resolved.
Show resolved Hide resolved
#[cfg(test)]
mod tests {
use std::time::Duration;
Expand Down