fastrace_jaeger/
lib.rs

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
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.

#![doc = include_str!("../README.md")]

mod thrift;

use std::error::Error;
use std::net::SocketAddr;
use std::net::UdpSocket;

use fastrace::collector::Reporter;
use fastrace::prelude::*;
use thrift::Log;
use thrift_codec::CompactEncode;
use thrift_codec::message::Message;

use crate::thrift::Batch;
use crate::thrift::EmitBatchNotification;
use crate::thrift::JaegerSpan;
use crate::thrift::Process;
use crate::thrift::Tag;

/// [Jaeger](https://www.jaegertracing.io/) reporter for `fastrace` via UDP endpoint.
pub struct JaegerReporter {
    agent_addr: SocketAddr,
    service_name: String,
    socket: UdpSocket,
}

impl JaegerReporter {
    pub fn new(
        agent_addr: SocketAddr,
        service_name: impl Into<String>,
    ) -> Result<Self, Box<dyn Error + Send + Sync + 'static>> {
        let local_addr: SocketAddr = if agent_addr.is_ipv4() {
            "0.0.0.0:0"
        } else {
            "[::]:0"
        }
        .parse()
        .unwrap();
        let socket = std::net::UdpSocket::bind(local_addr)?;

        Ok(Self {
            agent_addr,
            service_name: service_name.into(),
            socket,
        })
    }

    fn convert(&self, spans: &[SpanRecord]) -> Vec<JaegerSpan> {
        spans
            .iter()
            .map(move |s| JaegerSpan {
                trace_id_high: (s.trace_id.0 >> 64) as i64,
                trace_id_low: s.trace_id.0 as i64,
                span_id: s.span_id.0 as i64,
                parent_span_id: s.parent_id.0 as i64,
                operation_name: s.name.to_string(),
                references: vec![],
                flags: 1,
                start_time: (s.begin_time_unix_ns / 1_000) as i64,
                duration: (s.duration_ns / 1_000) as i64,
                tags: s
                    .properties
                    .iter()
                    .map(|(k, v)| Tag::String {
                        key: k.to_string(),
                        value: v.to_string(),
                    })
                    .collect(),
                logs: s
                    .events
                    .iter()
                    .map(|event| Log {
                        timestamp: (event.timestamp_unix_ns / 1_000) as i64,
                        fields: [("name".into(), event.name.clone())]
                            .iter()
                            .chain(&event.properties)
                            .map(|(k, v)| Tag::String {
                                key: k.to_string(),
                                value: v.to_string(),
                            })
                            .collect(),
                    })
                    .collect(),
            })
            .collect()
    }

    fn serialize(&self, spans: Vec<JaegerSpan>) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        let bn = EmitBatchNotification {
            batch: Batch {
                process: Process {
                    service_name: self.service_name.clone(),
                    tags: vec![],
                },
                spans,
            },
        };

        let mut bytes = Vec::new();
        let msg = Message::from(bn);
        msg.compact_encode(&mut bytes)?;

        Ok(bytes)
    }

    fn try_report(&self, spans: &[SpanRecord]) -> Result<(), Box<dyn std::error::Error>> {
        const MAX_UDP_PACKAGE_SIZE: usize = 8000;

        let mut spans_per_batch = spans.len();
        let mut sent_spans = 0;

        while sent_spans < spans.len() {
            let batch_size = spans_per_batch.min(spans.len() - sent_spans);
            let jaeger_spans = self.convert(&spans[sent_spans..sent_spans + batch_size]);
            let bytes = self.serialize(jaeger_spans)?;
            if bytes.len() >= MAX_UDP_PACKAGE_SIZE {
                if batch_size <= 1 {
                    sent_spans += 1;
                } else {
                    spans_per_batch /= 2;
                }
                continue;
            }
            self.socket.send_to(&bytes, self.agent_addr)?;
            sent_spans += batch_size;
        }

        Ok(())
    }
}

impl Reporter for JaegerReporter {
    fn report(&mut self, spans: Vec<SpanRecord>) {
        if spans.is_empty() {
            return;
        }

        if let Err(err) = self.try_report(&spans) {
            log::error!("report to jaeger failed: {}", err);
        }
    }
}