grow-apache-skywalking 0.2.0

Rust SDK for Apache SkyWalking by Grow Codes
Documentation
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
//! Tracer provider setup (`init_tracing_with`) and [`TracingHandle`].

use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use opentelemetry::propagation::TextMapCompositePropagator;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry::{InstrumentationScope, KeyValue, Value};
use opentelemetry_sdk::runtime::Tokio;
use opentelemetry_sdk::trace::span_processor_with_async_runtime::BatchSpanProcessor;
use opentelemetry_sdk::trace::{
    BatchConfigBuilder, Sampler, SdkTracer, SdkTracerProvider, SpanExporter, SpanProcessor,
};
use opentelemetry_sdk::Resource;

use super::{build_propagator, AttrValue, BoxedPropagator, SamplerKind, TracingConfig};
use crate::core::{Error, Result};

/// Running tracing pipeline (SPEC §5 `TracingHandle`). Cheap to clone.
///
/// Dropping the last handle without [`shutdown`](Self::shutdown) shuts the provider down on a
/// helper thread (best effort, so it never blocks an async runtime thread).
#[derive(Clone)]
pub struct TracingHandle {
    inner: Arc<HandleInner>,
}

struct HandleInner {
    provider: Option<SdkTracerProvider>,
    propagator: Arc<TextMapCompositePropagator>,
    service_name: String,
    shutdown: AtomicBool,
}

impl Drop for HandleInner {
    fn drop(&mut self) {
        if self.shutdown.load(Ordering::SeqCst) {
            return;
        }
        if let Some(provider) = self.provider.take() {
            // Blocking shutdown waits for the exporter task; never do that on this thread.
            let _ = std::thread::Builder::new()
                .name("grow-tracing-shutdown".into())
                .spawn(move || {
                    let _ = provider.shutdown();
                });
        }
    }
}

impl fmt::Debug for TracingHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TracingHandle")
            .field("service_name", &self.inner.service_name)
            .field("shutdown", &self.inner.shutdown.load(Ordering::SeqCst))
            .finish()
    }
}

impl TracingHandle {
    /// A handle around a provider built elsewhere (for services that assemble their own
    /// pipeline). Nothing is installed globally; [`shutdown`](Self::shutdown) shuts `provider`
    /// down.
    pub fn new(
        provider: SdkTracerProvider,
        propagator: Arc<TextMapCompositePropagator>,
        service_name: impl Into<String>,
    ) -> Self {
        TracingHandle {
            inner: Arc::new(HandleInner {
                provider: Some(provider),
                propagator,
                service_name: service_name.into(),
                shutdown: AtomicBool::new(false),
            }),
        }
    }

    fn provider_ref(&self) -> &SdkTracerProvider {
        self.inner
            .provider
            .as_ref()
            .expect("provider present until drop")
    }

    /// The OpenTelemetry tracer provider.
    pub fn tracer_provider(&self) -> SdkTracerProvider {
        self.provider_ref().clone()
    }

    /// The composite propagator built from the config.
    pub fn propagator(&self) -> Arc<TextMapCompositePropagator> {
        Arc::clone(&self.inner.propagator)
    }

    /// The configured `service.name`.
    pub fn service_name(&self) -> &str {
        &self.inner.service_name
    }

    /// A tracer for an instrumentation scope.
    pub fn tracer(&self, name: impl Into<Cow<'static, str>>, version: Option<&str>) -> SdkTracer {
        let mut scope = InstrumentationScope::builder(name.into());
        if let Some(v) = version {
            scope = scope.with_version(v.to_string());
        }
        self.provider_ref().tracer_with_scope(scope.build())
    }

    /// Exports every finished span now. `None` waits without a limit.
    pub async fn force_flush(&self, timeout: Option<Duration>) -> Result<()> {
        let provider = self.tracer_provider();
        let task = tokio::task::spawn_blocking(move || provider.force_flush());
        let joined = match timeout {
            None => task.await,
            Some(t) => tokio::time::timeout(t, task).await.map_err(|_| {
                Error::timeout(format!("tracing flush did not finish within {t:?}"))
            })?,
        };
        flatten("tracing flush", joined)
    }

    /// Flushes and shuts the provider down; idempotent.
    pub async fn shutdown(&self) -> Result<()> {
        if self.inner.shutdown.swap(true, Ordering::SeqCst) {
            return Ok(());
        }
        let provider = self.tracer_provider();
        let joined = tokio::task::spawn_blocking(move || provider.shutdown()).await;
        flatten("tracing shutdown", joined)
    }

    /// Whether [`shutdown`](Self::shutdown) was called.
    pub fn is_shutdown(&self) -> bool {
        self.inner.shutdown.load(Ordering::SeqCst)
    }
}

fn flatten<E: fmt::Display>(
    what: &str,
    joined: std::result::Result<std::result::Result<(), E>, tokio::task::JoinError>,
) -> Result<()> {
    match joined {
        Ok(Ok(())) => Ok(()),
        Ok(Err(e)) => Err(Error::unavailable(format!("{what} failed: {e}"))),
        Err(e) => Err(Error::unavailable(format!("{what} failed: {e}"))),
    }
}

/// Converts an attribute value to an OpenTelemetry value. Homogeneous arrays of strings,
/// integers, floats or booleans stay arrays; maps, mixed arrays and `null` become JSON text.
pub fn otel_value(value: &AttrValue) -> Value {
    use opentelemetry::{Array, StringValue};
    match value {
        AttrValue::String(s) => Value::String(s.clone().into()),
        AttrValue::Bool(b) => Value::Bool(*b),
        AttrValue::Number(n) => match n.as_i64() {
            Some(i) => Value::I64(i),
            None => Value::F64(n.as_f64().unwrap_or(f64::NAN)),
        },
        AttrValue::Array(items) => {
            let all = |f: fn(&AttrValue) -> bool| !items.is_empty() && items.iter().all(f);
            if all(|v| v.is_string()) {
                Value::Array(Array::String(
                    items
                        .iter()
                        .filter_map(|v| v.as_str())
                        .map(|s| StringValue::from(s.to_string()))
                        .collect(),
                ))
            } else if all(|v| v.is_i64()) {
                Value::Array(Array::I64(
                    items.iter().filter_map(|v| v.as_i64()).collect(),
                ))
            } else if all(|v| v.is_number()) {
                Value::Array(Array::F64(
                    items.iter().filter_map(|v| v.as_f64()).collect(),
                ))
            } else if all(|v| v.is_boolean()) {
                Value::Array(Array::Bool(
                    items.iter().filter_map(|v| v.as_bool()).collect(),
                ))
            } else {
                Value::String(value.to_string().into())
            }
        }
        other => Value::String(other.to_string().into()),
    }
}

/// Converts an attribute map to OpenTelemetry key-values.
pub fn otel_attributes<'a>(
    attrs: impl IntoIterator<Item = (&'a String, &'a AttrValue)>,
) -> Vec<KeyValue> {
    attrs
        .into_iter()
        .map(|(k, v)| KeyValue::new(k.clone(), otel_value(v)))
        .collect()
}

/// The OpenTelemetry sampler for a config.
pub fn build_sampler(kind: SamplerKind, ratio: f64) -> Sampler {
    match kind {
        SamplerKind::AlwaysOn => Sampler::AlwaysOn,
        SamplerKind::AlwaysOff => Sampler::AlwaysOff,
        SamplerKind::TraceIdRatio => Sampler::TraceIdRatioBased(ratio),
        SamplerKind::ParentBasedAlwaysOn => Sampler::ParentBased(Box::new(Sampler::AlwaysOn)),
        SamplerKind::ParentBasedAlwaysOff => Sampler::ParentBased(Box::new(Sampler::AlwaysOff)),
        SamplerKind::ParentBasedTraceIdRatio => {
            Sampler::ParentBased(Box::new(Sampler::TraceIdRatioBased(ratio)))
        }
    }
}

/// The resource for a config: SDK defaults (incl. `OTEL_RESOURCE_ATTRIBUTES`), then
/// `resource_attributes`, then `service.name`, `service.version`, `deployment.environment` and
/// `deployment.environment.name` (current semantic-convention name, same value).
pub fn build_resource(config: &TracingConfig) -> Resource {
    let mut attrs = otel_attributes(&config.resource_attributes);
    if let Some(v) = &config.service_version {
        attrs.push(KeyValue::new("service.version", v.clone()));
    }
    if let Some(env) = &config.environment {
        attrs.push(KeyValue::new("deployment.environment", env.clone()));
        attrs.push(KeyValue::new("deployment.environment.name", env.clone()));
    }
    Resource::builder()
        .with_attributes(attrs)
        .with_service_name(config.service_name.clone())
        .build()
}

/// Sets up tracing with the exporter `exporter_factory` builds from the config (SPEC §5
/// `initTracingWith`). Must be called inside a tokio runtime: spans are exported from a tokio
/// task, so exporters may use async HTTP clients. When `set_global` is on, the provider and the
/// propagator are installed globally.
pub fn init_tracing_with<E, F>(config: TracingConfig, exporter_factory: F) -> Result<TracingHandle>
where
    E: SpanExporter + 'static,
    F: FnOnce(&TracingConfig) -> Result<E>,
{
    init_tracing_with_propagators(config, exporter_factory, HashMap::new())
}

/// Like [`init_tracing_with`], with extra propagators for [`PropagatorKind::Other`](super::PropagatorKind::Other) names.
pub fn init_tracing_with_propagators<E, F>(
    config: TracingConfig,
    exporter_factory: F,
    extra_propagators: HashMap<String, BoxedPropagator>,
) -> Result<TracingHandle>
where
    E: SpanExporter + 'static,
    F: FnOnce(&TracingConfig) -> Result<E>,
{
    let options = PipelineOptions {
        propagators: extra_propagators,
        ..PipelineOptions::default()
    };
    init_tracing_with_pipeline(config, exporter_factory, options)
}

/// Like [`init_tracing_with`], with a sampler that replaces the one of `config.sampler`
/// (for example a remote/adaptive sampler).
pub fn init_tracing_with_sampler<E, F>(
    config: TracingConfig,
    exporter_factory: F,
    sampler: Sampler,
) -> Result<TracingHandle>
where
    E: SpanExporter + 'static,
    F: FnOnce(&TracingConfig) -> Result<E>,
{
    init_tracing_with_pipeline(
        config,
        exporter_factory,
        PipelineOptions::default().with_sampler(sampler),
    )
}

/// Extra options of [`init_tracing_with_pipeline`].
#[derive(Default)]
#[non_exhaustive]
pub struct PipelineOptions {
    /// Replaces the sampler built from `config.sampler` / `config.sampler_ratio`.
    pub sampler: Option<Sampler>,
    /// Span processors added after the exporting batch processor (they see every span).
    pub span_processors: Vec<Box<dyn SpanProcessor>>,
    /// Propagators for [`PropagatorKind::Other`](super::PropagatorKind::Other) names.
    pub propagators: HashMap<String, BoxedPropagator>,
}

impl fmt::Debug for PipelineOptions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut names: Vec<&String> = self.propagators.keys().collect();
        names.sort();
        f.debug_struct("PipelineOptions")
            .field("sampler", &self.sampler)
            .field("span_processors", &self.span_processors)
            .field("propagators", &names)
            .finish()
    }
}

impl PipelineOptions {
    /// No extra options.
    pub fn new() -> Self {
        PipelineOptions::default()
    }
    /// Sets the sampler override.
    pub fn with_sampler(mut self, sampler: Sampler) -> Self {
        self.sampler = Some(sampler);
        self
    }
    /// Adds a span processor.
    pub fn with_span_processor(mut self, processor: impl SpanProcessor + 'static) -> Self {
        self.span_processors.push(Box::new(processor));
        self
    }
    /// Adds a propagator for a [`PropagatorKind::Other`](super::PropagatorKind::Other) name.
    pub fn with_propagator(mut self, name: impl Into<String>, propagator: BoxedPropagator) -> Self {
        self.propagators.insert(name.into(), propagator);
        self
    }
}

/// Like [`init_tracing_with`], with a sampler override, extra span processors and extra
/// propagators (see [`PipelineOptions`]).
pub fn init_tracing_with_pipeline<E, F>(
    config: TracingConfig,
    exporter_factory: F,
    options: PipelineOptions,
) -> Result<TracingHandle>
where
    E: SpanExporter + 'static,
    F: FnOnce(&TracingConfig) -> Result<E>,
{
    config.validate()?;
    tokio::runtime::Handle::try_current()
        .map_err(|_| Error::config("init_tracing must be called inside a tokio runtime"))?;
    let propagator = Arc::new(build_propagator(&config.propagators, options.propagators)?);
    let exporter = exporter_factory(&config)?;
    let batch = BatchConfigBuilder::default()
        .with_max_queue_size(config.batch.max_queue_size)
        .with_max_export_batch_size(config.batch.max_export_batch_size)
        .with_scheduled_delay(config.batch.scheduled_delay)
        .with_max_export_timeout(config.batch.export_timeout)
        .build();
    let processor = BatchSpanProcessor::builder(exporter, Tokio)
        .with_batch_config(batch)
        .build();
    let sampler = options
        .sampler
        .unwrap_or_else(|| build_sampler(config.sampler, config.sampler_ratio));
    let mut builder = SdkTracerProvider::builder()
        .with_span_processor(processor)
        .with_sampler(sampler)
        .with_resource(build_resource(&config));
    for extra in options.span_processors {
        builder = builder.with_span_processor(BoxedSpanProcessor(extra));
    }
    let provider = builder.build();
    if config.set_global {
        opentelemetry::global::set_tracer_provider(provider.clone());
        opentelemetry::global::set_text_map_propagator(SharedPropagator(Arc::clone(&propagator)));
    }
    Ok(TracingHandle::new(
        provider,
        propagator,
        config.service_name,
    ))
}

/// Lets a boxed processor be registered with the provider builder.
#[derive(Debug)]
struct BoxedSpanProcessor(Box<dyn SpanProcessor>);

impl SpanProcessor for BoxedSpanProcessor {
    fn on_start(&self, span: &mut opentelemetry_sdk::trace::Span, cx: &opentelemetry::Context) {
        self.0.on_start(span, cx)
    }
    fn on_end(&self, span: opentelemetry_sdk::trace::SpanData) {
        self.0.on_end(span)
    }
    fn force_flush(&self) -> opentelemetry_sdk::error::OTelSdkResult {
        self.0.force_flush()
    }
    fn shutdown_with_timeout(&self, timeout: Duration) -> opentelemetry_sdk::error::OTelSdkResult {
        self.0.shutdown_with_timeout(timeout)
    }
    fn shutdown(&self) -> opentelemetry_sdk::error::OTelSdkResult {
        self.0.shutdown()
    }
    fn set_resource(&mut self, resource: &Resource) {
        self.0.set_resource(resource)
    }
}

/// Lets the global propagator share the handle's composite propagator.
#[derive(Debug)]
struct SharedPropagator(Arc<TextMapCompositePropagator>);

impl opentelemetry::propagation::TextMapPropagator for SharedPropagator {
    fn inject_context(
        &self,
        cx: &opentelemetry::Context,
        injector: &mut dyn opentelemetry::propagation::Injector,
    ) {
        self.0.inject_context(cx, injector)
    }
    fn extract_with_context(
        &self,
        cx: &opentelemetry::Context,
        extractor: &dyn opentelemetry::propagation::Extractor,
    ) -> opentelemetry::Context {
        self.0.extract_with_context(cx, extractor)
    }
    fn fields(&self) -> opentelemetry::propagation::text_map_propagator::FieldIter<'_> {
        self.0.fields()
    }
}