Skip to content

Commit f0879b1

Browse files
refactor: use OTLP env variables only
Signed-off-by: Fabrizio Sestito <fabrizio.sestito@suse.com>
1 parent d7e156e commit f0879b1

File tree

7 files changed

+79
-139
lines changed

7 files changed

+79
-139
lines changed

src/cli.rs

-20
Original file line numberDiff line numberDiff line change
@@ -194,26 +194,6 @@ pub(crate) fn build_cli() -> Command {
194194
.env("KUBEWARDEN_CONTINUE_ON_ERRORS")
195195
.action(ArgAction::SetTrue)
196196
.hide(true),
197-
198-
Arg::new("otlp-endpoint")
199-
.long("otlp-endpoint")
200-
.env("OTEL_EXPORTER_OTLP_ENDPOINT")
201-
.help("The OTLP gRPC endpoint for exporting traces and metrics."),
202-
203-
Arg::new("otlp-certificate")
204-
.long("otlp-certificate")
205-
.env("OTEL_EXPORTER_OTLP_CERTIFICATE")
206-
.help("Path to the trusted certificate in PEM format used for verifying the TLS credentials of the OTLP gRPC endpoint."),
207-
208-
Arg::new("otlp-client-certificate")
209-
.long("otlp-client-certificate")
210-
.env("OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE")
211-
.help("Path to the certificate in PEM format to use in mTLS communication."),
212-
213-
Arg::new("otlp-client-key")
214-
.long("otlp-client-key")
215-
.env("OTEL_EXPORTER_OTLP_CLIENT_KEY")
216-
.help("Path to the client private key in PEM format to use in mTLS communication."),
217197
];
218198

219199
args.sort_by(|a, b| a.get_id().cmp(b.get_id()));

src/config.rs

+45-56
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,11 @@ use serde::Deserialize;
1212
use std::{
1313
collections::{BTreeSet, HashMap},
1414
env,
15-
fs::File,
15+
fs::{self, File},
1616
net::SocketAddr,
1717
path::{Path, PathBuf},
1818
};
19+
use tonic::transport::{Certificate, ClientTlsConfig, Identity};
1920

2021
pub static SERVICE_NAME: &str = "kubewarden-policy-server";
2122
const DOCKER_CONFIG_ENV_VAR: &str = "DOCKER_CONFIG";
@@ -41,8 +42,6 @@ pub struct Config {
4142
pub log_level: String,
4243
pub log_fmt: String,
4344
pub log_no_color: bool,
44-
pub otlp_endpoint: Option<String>,
45-
pub otlp_tls_config: OtlpTlsConfig,
4645
pub daemon: bool,
4746
pub enable_pprof: bool,
4847
pub daemon_pid_file: String,
@@ -56,44 +55,6 @@ pub struct TlsConfig {
5655
pub key_file: String,
5756
}
5857

59-
#[derive(Clone, Default)]
60-
pub struct OtlpTlsConfig {
61-
pub ca_file: Option<PathBuf>,
62-
pub cert_file: Option<PathBuf>,
63-
pub key_file: Option<PathBuf>,
64-
}
65-
66-
impl TryFrom<OtlpTlsConfig> for tonic::transport::ClientTlsConfig {
67-
type Error = anyhow::Error;
68-
69-
fn try_from(value: OtlpTlsConfig) -> Result<tonic::transport::ClientTlsConfig, Self::Error> {
70-
use std::fs;
71-
use tonic::transport::{Certificate, ClientTlsConfig, Identity};
72-
73-
let mut tls = ClientTlsConfig::new();
74-
75-
if let Some(ca) = value.ca_file {
76-
let ca_cert = fs::read(ca)?;
77-
tls = tls.ca_certificate(Certificate::from_pem(ca_cert))
78-
}
79-
80-
if let Some(cert) = value.cert_file {
81-
let cert = fs::read(cert)?;
82-
83-
let key = value
84-
.key_file
85-
.map(fs::read)
86-
.transpose()?
87-
.unwrap_or_default();
88-
89-
let identity = Identity::from_pem(cert, key);
90-
tls = tls.identity(identity);
91-
}
92-
93-
Ok(tls)
94-
}
95-
}
96-
9758
impl Config {
9859
pub fn from_args(matches: &ArgMatches) -> Result<Self> {
9960
// init some variables based on the cli parameters
@@ -166,19 +127,6 @@ impl Config {
166127
.expect("clap should have assigned a default value")
167128
.to_owned();
168129

169-
let otlp_endpoint = matches.get_one::<String>("otlp-endpoint").cloned();
170-
let otlp_ca_file = matches.get_one::<PathBuf>("otlp-certificate").cloned();
171-
let otlp_cert_file = matches
172-
.get_one::<PathBuf>("otlp-client-certificate")
173-
.cloned();
174-
let otlp_key_file = matches.get_one::<PathBuf>("otlp-client-key").cloned();
175-
176-
let otlp_tls_config = OtlpTlsConfig {
177-
ca_file: otlp_ca_file,
178-
cert_file: otlp_cert_file,
179-
key_file: otlp_key_file,
180-
};
181-
182130
let (cert_file, key_file) = tls_files(matches)?;
183131
let tls_config = if cert_file.is_empty() {
184132
None
@@ -214,8 +162,6 @@ impl Config {
214162
log_level,
215163
log_fmt,
216164
log_no_color,
217-
otlp_endpoint,
218-
otlp_tls_config,
219165
daemon,
220166
daemon_pid_file,
221167
daemon_stdout_file,
@@ -482,6 +428,49 @@ fn read_policies_file(path: &Path) -> Result<HashMap<String, PolicyOrPolicyGroup
482428
Ok(ps)
483429
}
484430

431+
/// Creates a `ClientTlsConfig` used by OTLP exporters based on the environment variables.
432+
/// TODO: this function will be removed once this issue is resolved upstream:
433+
/// https://github.com/open-telemetry/opentelemetry-rust/issues/984
434+
pub fn build_client_tls_config_from_env(prefix: &str) -> Result<ClientTlsConfig> {
435+
let mut client_tls_config = ClientTlsConfig::new();
436+
437+
let ca_env = format!("OTEL_EXPORTER_OTLP_{}CERTIFICATE", prefix);
438+
let fallback_ca_env = "OTEL_EXPORTER_OTLP_CERTIFICATE";
439+
440+
let ca_file = env::var(&ca_env)
441+
.or_else(|_| env::var(fallback_ca_env))
442+
.ok();
443+
444+
if let Some(ca_path) = ca_file {
445+
let ca_cert = std::fs::read(ca_path)?;
446+
client_tls_config = client_tls_config.ca_certificate(Certificate::from_pem(ca_cert));
447+
}
448+
449+
let client_cert_env = format!("OTEL_EXPORTER_OTLP_{}CLIENT_CERTIFICATE", prefix);
450+
let fallback_client_cert_env = "OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE";
451+
452+
let client_cert_file = std::env::var(&client_cert_env)
453+
.or_else(|_| std::env::var(fallback_client_cert_env))
454+
.ok();
455+
456+
let client_key_env = format!("OTEL_EXPORTER_OTLP_{}CLIENT_KEY", prefix);
457+
let fallback_client_key_env = "OTEL_EXPORTER_OTLP_CLIENT_KEY";
458+
459+
let client_key_file = std::env::var(&client_key_env)
460+
.or_else(|_| std::env::var(fallback_client_key_env))
461+
.ok();
462+
463+
if let (Some(cert_path), Some(key_path)) = (client_cert_file, client_key_file) {
464+
let cert = fs::read(cert_path)?;
465+
let key = fs::read(key_path)?;
466+
467+
let identity = Identity::from_pem(cert, key);
468+
client_tls_config = client_tls_config.identity(identity);
469+
}
470+
471+
Ok(client_tls_config)
472+
}
473+
485474
#[cfg(test)]
486475
mod tests {
487476
use super::*;

src/main.rs

+2-11
Original file line numberDiff line numberDiff line change
@@ -21,19 +21,10 @@ async fn main() -> Result<()> {
2121
let matches = cli::build_cli().get_matches();
2222
let config = policy_server::config::Config::from_args(&matches)?;
2323

24-
setup_tracing(
25-
&config.log_level,
26-
&config.log_fmt,
27-
config.log_no_color,
28-
config.otlp_endpoint.as_deref(),
29-
config.otlp_tls_config.clone(),
30-
)?;
24+
setup_tracing(&config.log_level, &config.log_fmt, config.log_no_color)?;
3125

3226
if config.metrics_enabled {
33-
setup_metrics(
34-
config.otlp_endpoint.as_deref(),
35-
config.otlp_tls_config.clone(),
36-
)?;
27+
setup_metrics()?;
3728
};
3829

3930
if config.daemon {

src/metrics.rs

+9-10
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,20 @@ pub use policy_evaluations_total::add_policy_evaluation;
88
mod policy_evaluations_latency;
99
pub use policy_evaluations_latency::record_policy_latency;
1010

11-
use crate::config::OtlpTlsConfig;
11+
use crate::config::build_client_tls_config_from_env;
1212

1313
const METER_NAME: &str = "kubewarden";
1414

15-
pub fn setup_metrics(otlp_endpoint: Option<&str>, otlp_tls_config: OtlpTlsConfig) -> Result<()> {
16-
let mut metric_exporter_builder = opentelemetry_otlp::MetricExporter::builder()
15+
pub fn setup_metrics() -> Result<()> {
16+
let metric_exporter = opentelemetry_otlp::MetricExporter::builder()
1717
.with_tonic()
18-
.with_tls_config(otlp_tls_config.try_into()?)
19-
.with_export_config(ExportConfig::default());
20-
if let Some(endpoint) = otlp_endpoint {
21-
metric_exporter_builder = metric_exporter_builder.with_endpoint(endpoint);
22-
}
23-
let meter_reader = metric_exporter_builder.build()?;
18+
.with_tls_config(build_client_tls_config_from_env("METRICS")?)
19+
.with_export_config(ExportConfig::default())
20+
.build()?;
21+
2422
let periodic_reader =
25-
opentelemetry_sdk::metrics::PeriodicReader::builder(meter_reader, runtime::Tokio).build();
23+
opentelemetry_sdk::metrics::PeriodicReader::builder(metric_exporter, runtime::Tokio)
24+
.build();
2625
let meter_provider = opentelemetry_sdk::metrics::SdkMeterProvider::builder()
2726
.with_reader(periodic_reader)
2827
.build();

src/tracing.rs

+6-19
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,15 @@
1-
use std::convert::TryInto;
2-
31
use anyhow::{anyhow, Result};
42
use opentelemetry::trace::TracerProvider;
5-
use opentelemetry_otlp::{WithExportConfig, WithTonicConfig};
3+
use opentelemetry_otlp::WithTonicConfig;
64

75
use tracing_subscriber::prelude::*;
86
use tracing_subscriber::{fmt, EnvFilter};
97

10-
use crate::config::{self, OtlpTlsConfig};
8+
use crate::config::{self, build_client_tls_config_from_env};
119

1210
// Setup the tracing system. This MUST be done inside of a tokio Runtime
1311
// because some collectors rely on it and would panic otherwise.
14-
pub fn setup_tracing(
15-
log_level: &str,
16-
log_fmt: &str,
17-
log_no_color: bool,
18-
otlp_endpoint: Option<&str>,
19-
otlp_tls_config: OtlpTlsConfig,
20-
) -> Result<()> {
12+
pub fn setup_tracing(log_level: &str, log_fmt: &str, log_no_color: bool) -> Result<()> {
2113
// setup logging
2214
let filter_layer = EnvFilter::new(log_level)
2315
// some of our dependencies generate trace events too, but we don't care about them ->
@@ -50,15 +42,10 @@ pub fn setup_tracing(
5042
// If no endpoint is provided, the default one is used.
5143
// The default endpoint is "http://localhost:4317".
5244
//
53-
let mut otlp_exporter_builder = opentelemetry_otlp::SpanExporter::builder()
45+
let otlp_exporter = opentelemetry_otlp::SpanExporter::builder()
5446
.with_tonic()
55-
.with_tls_config(otlp_tls_config.try_into()?);
56-
57-
if let Some(endpoint) = otlp_endpoint {
58-
otlp_exporter_builder = otlp_exporter_builder.with_endpoint(endpoint);
59-
}
60-
61-
let otlp_exporter = otlp_exporter_builder.build()?;
47+
.with_tls_config(build_client_tls_config_from_env("OTLP")?)
48+
.build()?;
6249

6350
let tracer_provider = opentelemetry_sdk::trace::TracerProvider::builder()
6451
.with_resource(opentelemetry_sdk::Resource::new(vec![

tests/common/mod.rs

-2
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,6 @@ pub(crate) fn default_test_config() -> Config {
120120
log_level: "info".to_owned(),
121121
log_fmt: "json".to_owned(),
122122
log_no_color: false,
123-
otlp_endpoint: None,
124-
otlp_tls_config: Default::default(),
125123
daemon: false,
126124
daemon_pid_file: "policy_server.pid".to_owned(),
127125
daemon_stdout_file: None,

tests/integration_test.rs

+17-21
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ use policy_evaluator::{
2323
admission_response::AdmissionResponseStatus,
2424
policy_fetcher::verify::config::VerificationConfigV1,
2525
};
26-
use policy_server::config::OtlpTlsConfig;
2726
use policy_server::{
2827
api::admission_review::AdmissionReviewResponse,
2928
config::{PolicyMode, PolicyOrPolicyGroup},
@@ -832,29 +831,26 @@ async fn test_otel() {
832831
.await
833832
.unwrap();
834833

834+
std::env::set_var("OTEL_EXPORTER_OTLP_ENDPOINT", "https://localhost:1337");
835+
std::env::set_var(
836+
"OTEL_EXPORTER_OTLP_CERTIFICATE",
837+
server_ca_file.path().to_str().unwrap(),
838+
);
839+
std::env::set_var(
840+
"OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE",
841+
client_cert_file.path().to_str().unwrap(),
842+
);
843+
std::env::set_var(
844+
"OTEL_EXPORTER_OTLP_CLIENT_KEY",
845+
client_key_file.path().to_str().unwrap(),
846+
);
847+
835848
let mut config = default_test_config();
836849
config.metrics_enabled = true;
837850
config.log_fmt = "otlp".to_string();
838-
config.otlp_endpoint = Some("https://localhost:1337".to_string());
839-
config.otlp_tls_config = OtlpTlsConfig {
840-
ca_file: Some(server_ca_file.path().to_owned()),
841-
cert_file: Some(client_cert_file.path().to_owned()),
842-
key_file: Some(client_key_file.path().to_owned()),
843-
};
844-
845-
setup_metrics(
846-
config.otlp_endpoint.as_deref(),
847-
config.otlp_tls_config.clone(),
848-
)
849-
.unwrap();
850-
setup_tracing(
851-
&config.log_level,
852-
&config.log_fmt,
853-
config.log_no_color,
854-
config.otlp_endpoint.as_deref(),
855-
config.otlp_tls_config.clone(),
856-
)
857-
.unwrap();
851+
852+
setup_metrics().unwrap();
853+
setup_tracing(&config.log_level, &config.log_fmt, config.log_no_color).unwrap();
858854

859855
let app = app(config).await;
860856

0 commit comments

Comments
 (0)