1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
//! Stdout Metrics Exporter
use crate::global;
use crate::sdk::{
    export::metrics::{
        CheckpointSet, Count, ExportKind, ExportKindFor, ExportKindSelector, Exporter, LastValue,
        Max, Min, Quantile, Sum,
    },
    metrics::{
        aggregators::{
            ArrayAggregator, HistogramAggregator, LastValueAggregator, MinMaxSumCountAggregator,
            SumAggregator,
        },
        controllers::{self, PushController, PushControllerWorker},
        selectors::simple,
    },
};
use crate::{
    labels::{default_encoder, Encoder, LabelSet},
    metrics,
    metrics::{Descriptor, MetricsError, Result},
    KeyValue,
};
use futures::Stream;
#[cfg(feature = "serialize")]
use serde::{Serialize, Serializer};
use std::fmt;
use std::io;
use std::iter;
use std::sync::Mutex;
use std::time::{Duration, SystemTime};

/// Create a new stdout exporter builder with the configuration for a stdout exporter.
pub fn stdout<S, SO, I, IS, ISI>(spawn: S, interval: I) -> StdoutExporterBuilder<io::Stdout, S, I>
where
    S: Fn(PushControllerWorker) -> SO,
    I: Fn(Duration) -> IS,
    IS: Stream<Item = ISI> + Send + 'static,
{
    StdoutExporterBuilder::<io::Stdout, S, I>::builder(spawn, interval)
}

///
#[derive(Debug)]
pub struct StdoutExporter<W> {
    /// Writer is the destination. If not set, `Stdout` is used.
    writer: Mutex<W>,
    /// Will pretty print the output sent to the writer. Default is false.
    pretty_print: bool,
    /// Suppresses timestamp printing. This is useful to create deterministic test
    /// conditions.
    do_not_print_time: bool,
    /// Quantiles are the desired aggregation quantiles for distribution summaries,
    /// used when the configured aggregator supports quantiles.
    ///
    /// Note: this exporter is meant as a demonstration; a real exporter may wish to
    /// configure quantiles on a per-metric basis.
    quantiles: Vec<f64>,
    /// Encodes the labels.
    label_encoder: Box<dyn Encoder + Send + Sync>,
    /// An optional user-defined function to format a given export batch.
    formatter: Option<Formatter>,
}

/// A collection of exported lines
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[derive(Default, Debug)]
pub struct ExportBatch {
    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "Option::is_none"))]
    timestamp: Option<SystemTime>,
    lines: Vec<ExportLine>,
}

#[cfg_attr(feature = "serialize", derive(Serialize))]
#[derive(Default, Debug)]
struct ExportLine {
    name: String,
    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "Option::is_none"))]
    min: Option<ExportNumeric>,
    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "Option::is_none"))]
    max: Option<ExportNumeric>,
    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "Option::is_none"))]
    sum: Option<ExportNumeric>,
    count: u64,
    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "Option::is_none"))]
    last_value: Option<ExportNumeric>,

    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "Option::is_none"))]
    quantiles: Option<Vec<ExporterQuantile>>,

    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "Option::is_none"))]
    timestamp: Option<SystemTime>,
}

/// A number exported as debug for serialization
pub struct ExportNumeric(Box<dyn fmt::Debug>);

impl fmt::Debug for ExportNumeric {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[cfg(feature = "serialize")]
impl Serialize for ExportNumeric {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let s = format!("{:?}", self);
        serializer.serialize_str(&s)
    }
}

#[cfg_attr(feature = "serialize", derive(Serialize))]
#[derive(Debug)]
struct ExporterQuantile {
    q: f64,
    v: ExportNumeric,
}

impl<W> Exporter for StdoutExporter<W>
where
    W: fmt::Debug + io::Write,
{
    fn export(&self, checkpoint_set: &mut dyn CheckpointSet) -> Result<()> {
        let mut batch = ExportBatch::default();
        if !self.do_not_print_time {
            batch.timestamp = Some(crate::time::now());
        }
        checkpoint_set.try_for_each(self, &mut |record| {
            let agg = record.aggregator().ok_or(MetricsError::NoDataCollected)?;
            let desc = record.descriptor();
            let kind = desc.number_kind();
            let encoded_resource = record.resource().encoded(self.label_encoder.as_ref());
            let encoded_inst_labels = if !desc.instrumentation_name().is_empty() {
                let inst_labels = LabelSet::from_labels(iter::once(KeyValue::new(
                    "instrumentation.name",
                    desc.instrumentation_name().to_owned(),
                )));
                inst_labels.encoded(Some(self.label_encoder.as_ref()))
            } else {
                String::new()
            };

            let mut expose = ExportLine::default();

            if let Some(array) = agg.as_any().downcast_ref::<ArrayAggregator>() {
                expose.min = Some(ExportNumeric(array.min()?.to_debug(kind)));
                expose.max = Some(ExportNumeric(array.max()?.to_debug(kind)));
                expose.sum = Some(ExportNumeric(array.sum()?.to_debug(kind)));
                expose.count = array.count()?;

                let quantiles = self
                    .quantiles
                    .iter()
                    .map(|&q| {
                        Ok(ExporterQuantile {
                            q,
                            v: ExportNumeric(array.quantile(q)?.to_debug(kind)),
                        })
                    })
                    .collect::<Result<Vec<_>>>()?;
                expose.quantiles = Some(quantiles);
            }

            if let Some(last_value) = agg.as_any().downcast_ref::<LastValueAggregator>() {
                let (value, timestamp) = last_value.last_value()?;
                expose.last_value = Some(ExportNumeric(value.to_debug(kind)));

                if !self.do_not_print_time {
                    expose.timestamp = Some(timestamp);
                }
            }

            if let Some(histogram) = agg.as_any().downcast_ref::<HistogramAggregator>() {
                expose.sum = Some(ExportNumeric(histogram.sum()?.to_debug(kind)));
                expose.count = histogram.count()?;
                // TODO expose buckets
            }

            if let Some(mmsc) = agg.as_any().downcast_ref::<MinMaxSumCountAggregator>() {
                expose.min = Some(ExportNumeric(mmsc.min()?.to_debug(kind)));
                expose.max = Some(ExportNumeric(mmsc.max()?.to_debug(kind)));
                expose.sum = Some(ExportNumeric(mmsc.sum()?.to_debug(kind)));
                expose.count = mmsc.count()?;
            }

            if let Some(sum) = agg.as_any().downcast_ref::<SumAggregator>() {
                expose.sum = Some(ExportNumeric(sum.sum()?.to_debug(kind)));
            }

            let mut encoded_labels = String::new();
            let iter = record.labels().iter();
            if let (0, _) = iter.size_hint() {
                encoded_labels = record.labels().encoded(Some(self.label_encoder.as_ref()));
            }

            let mut sb = String::new();

            sb.push_str(desc.name());

            if !encoded_labels.is_empty()
                || !encoded_resource.is_empty()
                || !encoded_inst_labels.is_empty()
            {
                sb.push('{');
                sb.push_str(&encoded_resource);
                if !encoded_inst_labels.is_empty() && !encoded_resource.is_empty() {
                    sb.push(',');
                }
                sb.push_str(&encoded_inst_labels);
                if !encoded_labels.is_empty()
                    && (!encoded_inst_labels.is_empty() || !encoded_resource.is_empty())
                {
                    sb.push(',');
                }
                sb.push_str(&encoded_labels);
                sb.push('}');
            }

            expose.name = sb;

            batch.lines.push(expose);
            Ok(())
        })?;

        self.writer.lock().map_err(From::from).and_then(|mut w| {
            let formatted = match &self.formatter {
                Some(formatter) => formatter.0(batch)?,
                None => format!("{:?}\n", batch),
            };
            w.write_all(formatted.as_bytes())
                .map_err(|e| MetricsError::Other(e.to_string()))
        })
    }
}

impl<W> ExportKindFor for StdoutExporter<W>
where
    W: fmt::Debug + io::Write,
{
    fn export_kind_for(&self, descriptor: &Descriptor) -> ExportKind {
        ExportKindSelector::Stateless.export_kind_for(descriptor)
    }
}

/// A formatter for user-defined batch serialization.
pub struct Formatter(Box<dyn Fn(ExportBatch) -> Result<String> + Send + Sync>);
impl fmt::Debug for Formatter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Formatter(closure)")
    }
}

/// Configuration for a given stdout exporter.
#[derive(Debug)]
pub struct StdoutExporterBuilder<W, S, I> {
    spawn: S,
    interval: I,
    writer: Mutex<W>,
    pretty_print: bool,
    do_not_print_time: bool,
    quantiles: Option<Vec<f64>>,
    label_encoder: Option<Box<dyn Encoder + Send + Sync>>,
    period: Option<Duration>,
    formatter: Option<Formatter>,
}

impl<W, S, SO, I, IS, ISI> StdoutExporterBuilder<W, S, I>
where
    W: io::Write + fmt::Debug + Send + Sync + 'static,
    S: Fn(PushControllerWorker) -> SO,
    I: Fn(Duration) -> IS,
    IS: Stream<Item = ISI> + Send + 'static,
{
    fn builder(spawn: S, interval: I) -> StdoutExporterBuilder<io::Stdout, S, I> {
        StdoutExporterBuilder {
            spawn,
            interval,
            writer: Mutex::new(io::stdout()),
            pretty_print: false,
            do_not_print_time: false,
            quantiles: None,
            label_encoder: None,
            period: None,
            formatter: None,
        }
    }
    /// Set the writer that this exporter will use.
    pub fn with_writer<W2: io::Write>(self, writer: W2) -> StdoutExporterBuilder<W2, S, I> {
        StdoutExporterBuilder {
            spawn: self.spawn,
            interval: self.interval,
            writer: Mutex::new(writer),
            pretty_print: self.pretty_print,
            do_not_print_time: self.do_not_print_time,
            quantiles: self.quantiles,
            label_encoder: self.label_encoder,
            period: self.period,
            formatter: self.formatter,
        }
    }

    /// Set if the writer should format with pretty print
    pub fn with_pretty_print(self, pretty_print: bool) -> Self {
        StdoutExporterBuilder {
            pretty_print,
            ..self
        }
    }

    /// Hide the timestamps from exported results
    pub fn with_do_not_print_time(self, do_not_print_time: bool) -> Self {
        StdoutExporterBuilder {
            do_not_print_time,
            ..self
        }
    }

    /// Set the quantiles that this exporter will use.
    pub fn with_quantiles(self, quantiles: Vec<f64>) -> Self {
        StdoutExporterBuilder {
            quantiles: Some(quantiles),
            ..self
        }
    }

    /// Set the label encoder that this exporter will use.
    pub fn with_label_encoder<E>(self, label_encoder: E) -> Self
    where
        E: Encoder + Send + Sync + 'static,
    {
        StdoutExporterBuilder {
            label_encoder: Some(Box::new(label_encoder)),
            ..self
        }
    }

    /// Set the frequency in which metrics are exported.
    pub fn with_period(self, period: Duration) -> Self {
        StdoutExporterBuilder {
            period: Some(period),
            ..self
        }
    }

    /// Set a formatter for serializing export batch data
    pub fn with_formatter<T>(self, formatter: T) -> Self
    where
        T: Fn(ExportBatch) -> Result<String> + Send + Sync + 'static,
    {
        StdoutExporterBuilder {
            formatter: Some(Formatter(Box::new(formatter))),
            ..self
        }
    }

    /// Build a new push controller, returning errors if they arise.
    pub fn try_init(mut self) -> metrics::Result<PushController> {
        let period = self.period.take();
        let (spawn, interval, exporter) = self.try_build()?;
        let mut push_builder = controllers::push(
            simple::Selector::Exact,
            ExportKindSelector::Stateless,
            exporter,
            spawn,
            interval,
        )
        .with_stateful(true);
        if let Some(period) = period {
            push_builder = push_builder.with_period(period);
        }

        let controller = push_builder.build();
        global::set_meter_provider(controller.provider());
        Ok(controller)
    }

    fn try_build(self) -> metrics::Result<(S, I, StdoutExporter<W>)> {
        if let Some(quantiles) = self.quantiles.as_ref() {
            for q in quantiles {
                if *q < 0.0 || *q > 1.0 {
                    return Err(MetricsError::InvalidQuantile);
                }
            }
        }

        Ok((
            self.spawn,
            self.interval,
            StdoutExporter {
                writer: self.writer,
                pretty_print: self.pretty_print,
                do_not_print_time: self.do_not_print_time,
                quantiles: self.quantiles.unwrap_or_else(|| vec![0.5, 0.9, 0.99]),
                label_encoder: self.label_encoder.unwrap_or_else(default_encoder),
                formatter: self.formatter,
            },
        ))
    }
}