1use crate::Error;
7use crate::yaml::Node;
8
9#[derive(Clone, Debug, PartialEq, Default)]
11pub struct Config {
12 pub file_format: String,
14 pub disabled: bool,
16 pub resource: ResourceConfig,
18 pub attribute_limits: Limits,
20 pub propagators: Option<Vec<String>>,
22 pub tracer_provider: Option<TracerProviderConfig>,
24 pub meter_provider: Option<MeterProviderConfig>,
26 pub logger_provider: Option<LoggerProviderConfig>,
28}
29
30#[derive(Clone, Debug, PartialEq)]
32pub enum AttributeValue {
33 String(String),
35 Bool(bool),
37 Int(i64),
39 Double(f64),
41 StringArray(Vec<String>),
43 BoolArray(Vec<bool>),
45 IntArray(Vec<i64>),
47 DoubleArray(Vec<f64>),
49}
50
51#[derive(Clone, Debug, PartialEq, Default)]
53pub struct ResourceConfig {
54 pub attributes: Vec<(String, AttributeValue)>,
56 pub attributes_list: Option<String>,
59 pub schema_url: Option<String>,
61 pub detectors: Option<Vec<String>>,
63}
64
65#[derive(Clone, Copy, Debug, PartialEq, Default)]
67pub struct Limits {
68 pub attribute_count: Option<usize>,
70 pub event_count: Option<usize>,
72 pub link_count: Option<usize>,
74}
75
76#[derive(Clone, Debug, PartialEq)]
78pub enum ExporterConfig {
79 OtlpHttp(OtlpHttpConfig),
81 Console,
83}
84
85#[derive(Clone, Debug, PartialEq, Default)]
87pub struct OtlpHttpConfig {
88 pub endpoint: Option<String>,
90 pub headers: Vec<(String, String)>,
92 pub headers_list: Option<String>,
94 pub gzip: bool,
96 pub timeout_ms: Option<u64>,
98 pub json: bool,
100}
101
102#[derive(Clone, Debug, PartialEq)]
104pub enum ProcessorConfig {
105 Batch {
107 exporter: ExporterConfig,
109 schedule_delay_ms: Option<u64>,
111 export_timeout_ms: Option<u64>,
113 max_queue_size: Option<usize>,
115 max_export_batch_size: Option<usize>,
117 },
118 Simple {
120 exporter: ExporterConfig,
122 },
123}
124
125#[derive(Clone, Debug, PartialEq)]
127pub enum SamplerConfig {
128 AlwaysOn,
130 AlwaysOff,
132 TraceIdRatio(f64),
134 ParentBased(Box<SamplerConfig>),
136}
137
138#[derive(Clone, Debug, PartialEq, Default)]
140pub struct TracerProviderConfig {
141 pub processors: Vec<ProcessorConfig>,
143 pub limits: Limits,
145 pub sampler: Option<SamplerConfig>,
147}
148
149#[derive(Clone, Debug, PartialEq)]
151pub enum ReaderConfig {
152 Periodic {
154 exporter: ExporterConfig,
156 interval_ms: Option<u64>,
158 timeout_ms: Option<u64>,
160 },
161 Prometheus {
163 host: Option<String>,
165 port: Option<u16>,
167 without_scope_info: bool,
169 without_target_info: bool,
171 },
172}
173
174#[derive(Clone, Debug, PartialEq, Default)]
176pub struct MeterProviderConfig {
177 pub readers: Vec<ReaderConfig>,
179 pub exemplar_filter: Option<String>,
181 pub cardinality_limit: Option<usize>,
183}
184
185#[derive(Clone, Debug, PartialEq, Default)]
187pub struct LoggerProviderConfig {
188 pub processors: Vec<ProcessorConfig>,
190 pub limits: Limits,
192}
193
194struct Fields<'n> {
197 path: String,
198 entries: &'n [(String, Node)],
199 used: Vec<bool>,
200}
201
202impl<'n> Fields<'n> {
203 fn of(node: &'n Node, path: &str) -> Result<Self, Error> {
204 static EMPTY: Vec<(String, Node)> = Vec::new();
205 let entries: &'n [(String, Node)] = match node {
206 Node::Map(entries) => entries,
207 Node::Null => &EMPTY,
209 _ => return Err(invalid(path, "a mapping")),
210 };
211 Ok(Fields {
212 path: path.to_string(),
213 entries,
214 used: vec![false; entries.len()],
215 })
216 }
217
218 fn get(&mut self, key: &str) -> Option<&'n Node> {
219 let i = self.entries.iter().position(|(k, _)| k == key)?;
220 self.used[i] = true;
221 Some(&self.entries[i].1).filter(|n| **n != Node::Null)
222 }
223
224 fn sub(&self, key: &str) -> String {
225 if self.path.is_empty() {
226 key.to_string()
227 } else {
228 format!("{}.{key}", self.path)
229 }
230 }
231
232 fn str(&mut self, key: &str) -> Result<Option<String>, Error> {
233 let path = self.sub(key);
234 self.get(key).map(|n| string(n, &path)).transpose()
235 }
236
237 fn bool(&mut self, key: &str) -> Result<Option<bool>, Error> {
238 let path = self.sub(key);
239 match self.get(key) {
240 None => Ok(None),
241 Some(Node::Bool(b)) => Ok(Some(*b)),
242 Some(_) => Err(invalid(&path, "a boolean")),
243 }
244 }
245
246 fn uint(&mut self, key: &str) -> Result<Option<u64>, Error> {
247 let path = self.sub(key);
248 match self.get(key) {
249 None => Ok(None),
250 Some(Node::Int(i)) if *i >= 0 => Ok(Some(*i as u64)),
251 Some(_) => Err(invalid(&path, "a non-negative integer")),
252 }
253 }
254
255 fn usize(&mut self, key: &str) -> Result<Option<usize>, Error> {
256 Ok(self
257 .uint(key)?
258 .map(|v| usize::try_from(v).unwrap_or(usize::MAX)))
259 }
260
261 fn float(&mut self, key: &str) -> Result<Option<f64>, Error> {
262 let path = self.sub(key);
263 match self.get(key) {
264 None => Ok(None),
265 Some(Node::Float(f)) => Ok(Some(*f)),
266 Some(Node::Int(i)) => Ok(Some(*i as f64)),
267 Some(_) => Err(invalid(&path, "a number")),
268 }
269 }
270
271 fn map(&mut self, key: &str) -> Result<Option<Fields<'n>>, Error> {
272 let path = self.sub(key);
273 let i = self.entries.iter().position(|(k, _)| k == key);
275 match i {
276 None => Ok(None),
277 Some(i) => {
278 self.used[i] = true;
279 Fields::of(&self.entries[i].1, &path).map(Some)
280 }
281 }
282 }
283
284 fn list(&mut self, key: &str) -> Result<&'n [Node], Error> {
285 let path = self.sub(key);
286 match self.get(key) {
287 None => Ok(&[]),
288 Some(Node::Seq(items)) => Ok(items),
289 Some(_) => Err(invalid(&path, "a list")),
290 }
291 }
292
293 fn finish(self, warnings: &mut Vec<String>) {
295 for ((key, _), used) in self.entries.iter().zip(&self.used) {
296 if !*used {
297 warnings.push(format!("`{}` isn't supported; ignored", self.sub(key)));
298 }
299 }
300 }
301}
302
303fn invalid(path: &str, expected: &str) -> Error {
304 Error::Invalid {
305 path: path.to_string(),
306 expected: expected.to_string(),
307 }
308}
309
310fn string(node: &Node, path: &str) -> Result<String, Error> {
311 match node {
312 Node::Str(s) => Ok(s.clone()),
313 Node::Int(i) => Ok(i.to_string()),
314 Node::Float(f) => Ok(f.to_string()),
315 Node::Bool(b) => Ok(b.to_string()),
316 _ => Err(invalid(path, "a string")),
317 }
318}
319
320fn one_of<'n>(item: &'n Node, path: &str) -> Result<(&'n str, &'n Node), Error> {
323 match item {
324 Node::Map(entries) if entries.len() == 1 => Ok((entries[0].0.as_str(), &entries[0].1)),
325 _ => Err(invalid(path, "a mapping with exactly one key")),
326 }
327}
328
329pub(crate) fn config(root: &Node, warnings: &mut Vec<String>) -> Result<Config, Error> {
331 let mut f = Fields::of(root, "")?;
332 let file_format = f.str("file_format")?.ok_or(Error::FileFormat(None))?;
333 let major = file_format.split('.').next().unwrap_or_default();
334 if major != "1" {
335 return Err(Error::FileFormat(Some(file_format)));
336 }
337 let mut config = Config {
338 file_format,
339 disabled: f.bool("disabled")?.unwrap_or(false),
340 ..Config::default()
341 };
342 f.get("log_level");
344 if let Some(r) = f.map("resource")? {
345 config.resource = resource(r, warnings)?;
346 }
347 if let Some(mut l) = f.map("attribute_limits")? {
348 config.attribute_limits.attribute_count = l.usize("attribute_count_limit")?;
349 l.get("attribute_value_depth_limit");
352 if l.get("attribute_value_length_limit").is_some() {
353 warnings.push(
354 "`attribute_limits.attribute_value_length_limit` isn't supported yet; ignored"
355 .into(),
356 );
357 }
358 l.finish(warnings);
359 }
360 if let Some(p) = f.map("propagator")? {
361 config.propagators = Some(propagators(p, warnings)?);
362 }
363 if let Some(t) = f.map("tracer_provider")? {
364 config.tracer_provider = Some(tracer_provider(t, warnings)?);
365 }
366 if let Some(m) = f.map("meter_provider")? {
367 config.meter_provider = Some(meter_provider(m, warnings)?);
368 }
369 if let Some(l) = f.map("logger_provider")? {
370 config.logger_provider = Some(logger_provider(l, warnings)?);
371 }
372 f.get("instrumentation/development");
374 f.finish(warnings);
375 Ok(config)
376}
377
378fn resource(mut f: Fields<'_>, warnings: &mut Vec<String>) -> Result<ResourceConfig, Error> {
379 let mut r = ResourceConfig {
380 attributes_list: f.str("attributes_list")?,
381 schema_url: f.str("schema_url")?,
382 ..ResourceConfig::default()
383 };
384 for (i, item) in f.list("attributes")?.iter().enumerate() {
385 let path = format!("{}.attributes[{i}]", f.path);
386 let mut a = Fields::of(item, &path)?;
387 let name = a
388 .str("name")?
389 .ok_or_else(|| invalid(&format!("{path}.name"), "a name"))?;
390 let kind = a.str("type")?.unwrap_or_else(|| "string".into());
391 let value_path = format!("{path}.value");
392 let value = a
393 .get("value")
394 .ok_or_else(|| invalid(&value_path, "a value"))?;
395 r.attributes
396 .push((name, attribute_value(value, &kind, &value_path)?));
397 a.finish(warnings);
398 }
399 if let Some(mut d) = f.map("detection/development")? {
400 let mut names = Vec::new();
401 for (i, item) in d.list("detectors")?.iter().enumerate() {
402 let (name, _) = one_of(item, &format!("{}.detectors[{i}]", d.path))?;
403 names.push(name.to_string());
404 }
405 r.detectors = Some(names);
406 if d.get("attributes").is_some() {
407 warnings.push(
408 "`resource.detection/development.attributes` isn't supported yet; every detected attribute is kept"
409 .into(),
410 );
411 }
412 d.finish(warnings);
413 }
414 f.finish(warnings);
415 Ok(r)
416}
417
418fn attribute_value(node: &Node, kind: &str, path: &str) -> Result<AttributeValue, Error> {
419 let items = || match node {
420 Node::Seq(items) => Ok(items.as_slice()),
421 _ => Err(invalid(path, "a list")),
422 };
423 Ok(match kind {
424 "string" => AttributeValue::String(string(node, path)?),
425 "bool" => match node {
426 Node::Bool(b) => AttributeValue::Bool(*b),
427 _ => return Err(invalid(path, "a boolean")),
428 },
429 "int" => match node {
430 Node::Int(i) => AttributeValue::Int(*i),
431 _ => return Err(invalid(path, "an integer")),
432 },
433 "double" => match node {
434 Node::Float(f) => AttributeValue::Double(*f),
435 Node::Int(i) => AttributeValue::Double(*i as f64),
436 _ => return Err(invalid(path, "a number")),
437 },
438 "string_array" => AttributeValue::StringArray(
439 items()?
440 .iter()
441 .map(|n| string(n, path))
442 .collect::<Result<_, _>>()?,
443 ),
444 "bool_array" => AttributeValue::BoolArray(
445 items()?
446 .iter()
447 .map(|n| match n {
448 Node::Bool(b) => Ok(*b),
449 _ => Err(invalid(path, "booleans")),
450 })
451 .collect::<Result<_, _>>()?,
452 ),
453 "int_array" => AttributeValue::IntArray(
454 items()?
455 .iter()
456 .map(|n| match n {
457 Node::Int(i) => Ok(*i),
458 _ => Err(invalid(path, "integers")),
459 })
460 .collect::<Result<_, _>>()?,
461 ),
462 "double_array" => AttributeValue::DoubleArray(
463 items()?
464 .iter()
465 .map(|n| match n {
466 Node::Float(f) => Ok(*f),
467 Node::Int(i) => Ok(*i as f64),
468 _ => Err(invalid(path, "numbers")),
469 })
470 .collect::<Result<_, _>>()?,
471 ),
472 other => return Err(invalid(path, &format!("a known type, not `{other}`"))),
473 })
474}
475
476fn propagators(mut f: Fields<'_>, warnings: &mut Vec<String>) -> Result<Vec<String>, Error> {
477 let mut names = Vec::new();
478 for (i, item) in f.list("composite")?.iter().enumerate() {
479 let (name, _) = one_of(item, &format!("{}.composite[{i}]", f.path))?;
480 names.push(name.to_string());
481 }
482 if let Some(list) = f.str("composite_list")? {
483 for name in list.split(',').map(str::trim).filter(|n| !n.is_empty()) {
484 if !names.iter().any(|n| n == name) {
485 names.push(name.to_string());
486 }
487 }
488 }
489 f.finish(warnings);
490 Ok(names)
491}
492
493fn limits(f: &mut Fields<'_>, warnings: &mut Vec<String>) -> Result<Limits, Error> {
494 let limits = Limits {
495 attribute_count: f.usize("attribute_count_limit")?,
496 event_count: f.usize("event_count_limit")?,
497 link_count: f.usize("link_count_limit")?,
498 };
499 f.get("attribute_value_depth_limit");
500 for key in [
501 "attribute_value_length_limit",
502 "event_attribute_count_limit",
503 "link_attribute_count_limit",
504 ] {
505 if f.get(key).is_some() {
506 warnings.push(format!("`{}` isn't supported yet; ignored", f.sub(key)));
507 }
508 }
509 Ok(limits)
510}
511
512fn tracer_provider(
513 mut f: Fields<'_>,
514 warnings: &mut Vec<String>,
515) -> Result<TracerProviderConfig, Error> {
516 let mut t = TracerProviderConfig {
517 processors: processors(&mut f, warnings)?,
518 ..TracerProviderConfig::default()
519 };
520 if let Some(mut l) = f.map("limits")? {
521 t.limits = limits(&mut l, warnings)?;
522 l.finish(warnings);
523 }
524 let sampler_path = f.sub("sampler");
525 if let Some(s) = f.get("sampler") {
526 t.sampler = sampler(s, &sampler_path, warnings)?;
527 }
528 f.finish(warnings);
529 Ok(t)
530}
531
532fn sampler(
533 node: &Node,
534 path: &str,
535 warnings: &mut Vec<String>,
536) -> Result<Option<SamplerConfig>, Error> {
537 let (name, body) = one_of(node, path)?;
538 let path = format!("{path}.{name}");
539 Ok(Some(match name {
540 "always_on" => SamplerConfig::AlwaysOn,
541 "always_off" => SamplerConfig::AlwaysOff,
542 "trace_id_ratio_based" => {
543 let mut f = Fields::of(body, &path)?;
544 let ratio = f.float("ratio")?.unwrap_or(1.0);
545 f.finish(warnings);
546 SamplerConfig::TraceIdRatio(ratio)
547 }
548 "parent_based" => {
549 let mut f = Fields::of(body, &path)?;
550 let root_path = f.sub("root");
551 let root = match f.get("root") {
552 Some(r) => sampler(r, &root_path, warnings)?.unwrap_or(SamplerConfig::AlwaysOn),
553 None => SamplerConfig::AlwaysOn,
554 };
555 for (key, expected) in [
558 ("remote_parent_sampled", "always_on"),
559 ("remote_parent_not_sampled", "always_off"),
560 ("local_parent_sampled", "always_on"),
561 ("local_parent_not_sampled", "always_off"),
562 ] {
563 if let Some(child) = f.get(key)
564 && one_of(child, &f.sub(key))?.0 != expected
565 {
566 warnings.push(format!(
567 "`{}` other than `{expected}` isn't supported yet; the parent's decision is followed",
568 f.sub(key)
569 ));
570 }
571 }
572 f.finish(warnings);
573 SamplerConfig::ParentBased(Box::new(root))
574 }
575 other => {
576 warnings.push(format!(
577 "the `{other}` sampler isn't supported; using parent_based with always_on"
578 ));
579 return Ok(None);
580 }
581 }))
582}
583
584fn processors(
585 f: &mut Fields<'_>,
586 warnings: &mut Vec<String>,
587) -> Result<Vec<ProcessorConfig>, Error> {
588 let mut out = Vec::new();
589 for (i, item) in f.list("processors")?.iter().enumerate() {
590 let path = format!("{}.processors[{i}]", f.path);
591 let (kind, body) = one_of(item, &path)?;
592 let path = format!("{path}.{kind}");
593 let mut p = Fields::of(body, &path)?;
594 let Some(exporter) = exporter(&mut p, warnings)? else {
595 p.finish(warnings);
596 continue;
597 };
598 match kind {
599 "batch" => out.push(ProcessorConfig::Batch {
600 exporter,
601 schedule_delay_ms: p.uint("schedule_delay")?,
602 export_timeout_ms: p.uint("export_timeout")?,
603 max_queue_size: p.usize("max_queue_size")?,
604 max_export_batch_size: p.usize("max_export_batch_size")?,
605 }),
606 "simple" => out.push(ProcessorConfig::Simple { exporter }),
607 other => warnings.push(format!("the `{other}` processor isn't supported; ignored")),
608 }
609 p.finish(warnings);
610 }
611 Ok(out)
612}
613
614fn exporter(
617 f: &mut Fields<'_>,
618 warnings: &mut Vec<String>,
619) -> Result<Option<ExporterConfig>, Error> {
620 let path = f.sub("exporter");
621 let Some(node) = f.get("exporter") else {
622 return Err(invalid(&path, "an exporter"));
623 };
624 let (kind, body) = one_of(node, &path)?;
625 let path = format!("{path}.{kind}");
626 match kind {
627 "otlp_http" => {
628 let mut e = Fields::of(body, &path)?;
629 let mut otlp = OtlpHttpConfig {
630 endpoint: e.str("endpoint")?,
631 headers_list: e.str("headers_list")?,
632 timeout_ms: e.uint("timeout")?,
633 ..OtlpHttpConfig::default()
634 };
635 for (i, item) in e.list("headers")?.iter().enumerate() {
636 let hp = format!("{path}.headers[{i}]");
637 let mut h = Fields::of(item, &hp)?;
638 let name = h.str("name")?.ok_or_else(|| invalid(&hp, "a name"))?;
639 let value = h.str("value")?.unwrap_or_default();
640 otlp.headers.push((name, value));
641 h.finish(warnings);
642 }
643 match e.str("compression")?.as_deref() {
644 None | Some("none") => {}
645 Some("gzip") => otlp.gzip = true,
646 Some(other) => {
647 return Err(invalid(
648 &e.sub("compression"),
649 &format!("gzip or none, not `{other}`"),
650 ));
651 }
652 }
653 match e.str("encoding")?.as_deref() {
654 None | Some("protobuf") => {}
655 Some("json") => otlp.json = true,
656 Some(other) => {
657 return Err(invalid(
658 &e.sub("encoding"),
659 &format!("protobuf or json, not `{other}`"),
660 ));
661 }
662 }
663 if let Some(mut tls) = e.map("tls")? {
664 for key in ["ca_file", "key_file", "cert_file"] {
665 if tls.get(key).is_some() {
666 warnings.push(format!(
667 "`{}` isn't supported yet; the system's roots are used",
668 tls.sub(key)
669 ));
670 }
671 }
672 tls.finish(warnings);
673 }
674 match e.str("temporality_preference")?.as_deref() {
675 None | Some("cumulative") => {}
676 Some(other) => warnings.push(format!(
677 "`{}: {other}` isn't supported yet; metrics are cumulative",
678 e.sub("temporality_preference")
679 )),
680 }
681 match e.str("default_histogram_aggregation")?.as_deref() {
682 None | Some("explicit_bucket_histogram") => {}
683 Some(other) => warnings.push(format!(
684 "`{}: {other}` isn't supported yet; histograms use explicit buckets",
685 e.sub("default_histogram_aggregation")
686 )),
687 }
688 e.finish(warnings);
689 Ok(Some(ExporterConfig::OtlpHttp(otlp)))
690 }
691 "console" => {
692 Fields::of(body, &path)?.finish(warnings);
693 Ok(Some(ExporterConfig::Console))
694 }
695 other => {
696 warnings.push(format!("the `{other}` exporter isn't supported; ignored"));
697 Ok(None)
698 }
699 }
700}
701
702fn meter_provider(
703 mut f: Fields<'_>,
704 warnings: &mut Vec<String>,
705) -> Result<MeterProviderConfig, Error> {
706 let mut m = MeterProviderConfig {
707 exemplar_filter: f.str("exemplar_filter")?,
708 ..MeterProviderConfig::default()
709 };
710 for (i, item) in f.list("readers")?.iter().enumerate() {
711 let path = format!("{}.readers[{i}]", f.path);
712 let (kind, body) = one_of(item, &path)?;
713 let path = format!("{path}.{kind}");
714 let mut r = Fields::of(body, &path)?;
715 if let Some(mut c) = r.map("cardinality_limits")? {
716 if let Some(limit) = c.usize("default")? {
717 m.cardinality_limit = Some(m.cardinality_limit.map_or(limit, |l| l.min(limit)));
718 }
719 c.finish(warnings);
720 }
721 match kind {
722 "periodic" => {
723 let interval_ms = r.uint("interval")?;
724 let timeout_ms = r.uint("timeout")?;
725 if let Some(exporter) = exporter(&mut r, warnings)? {
726 m.readers.push(ReaderConfig::Periodic {
727 exporter,
728 interval_ms,
729 timeout_ms,
730 });
731 }
732 }
733 "pull" => {
734 let ep = r.sub("exporter");
735 let node = r
736 .get("exporter")
737 .ok_or_else(|| invalid(&ep, "an exporter"))?;
738 let (name, body) = one_of(node, &ep)?;
739 if name == "prometheus/development" {
740 let mut p = Fields::of(body, &format!("{ep}.{name}"))?;
741 let port = p.uint("port")?;
742 m.readers.push(ReaderConfig::Prometheus {
743 host: p.str("host")?,
744 port: port.map(|v| u16::try_from(v).unwrap_or(9464)),
745 without_scope_info: p.bool("without_scope_info")?.unwrap_or(false),
746 without_target_info: p.bool("without_target_info")?.unwrap_or(false),
747 });
748 p.finish(warnings);
749 } else {
750 warnings.push(format!(
751 "the `{name}` pull exporter isn't supported; ignored"
752 ));
753 }
754 }
755 other => warnings.push(format!("the `{other}` reader isn't supported; ignored")),
756 }
757 r.finish(warnings);
758 }
759 if f.get("views").is_some() {
760 warnings.push("`meter_provider.views` isn't supported yet; ignored".into());
761 }
762 f.finish(warnings);
763 Ok(m)
764}
765
766fn logger_provider(
767 mut f: Fields<'_>,
768 warnings: &mut Vec<String>,
769) -> Result<LoggerProviderConfig, Error> {
770 let mut l = LoggerProviderConfig {
771 processors: processors(&mut f, warnings)?,
772 ..LoggerProviderConfig::default()
773 };
774 if let Some(mut lim) = f.map("limits")? {
775 l.limits = limits(&mut lim, warnings)?;
776 lim.finish(warnings);
777 }
778 f.finish(warnings);
779 Ok(l)
780}