File size: 3,692 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use std::{
    env::args,
    fs::File,
    io::{self, BufRead},
    path::Path,
};

use reqwest::blocking::Client;
use serde_json::{Map, Number, Value};

/// Read individual lines from a file.
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
    P: AsRef<Path>,
{
    let file = File::open(filename)?;
    Ok(io::BufReader::new(file).lines())
}

/// Log the url to view the trace in the browser.
fn log_web_url(jaeger_web_ui_url: &str, trace_id: &str) {
    println!("Jaeger trace will be available on {jaeger_web_ui_url}/trace/{trace_id}")
}

/// Send trace JSON to Jaeger using ZipKin API.
fn send_json_to_zipkin(zipkin_api: &str, value: String) {
    let client = Client::new();

    let res = client
        .post(zipkin_api)
        .header("Content-Type", "application/json")
        .body(value)
        .send()
        .expect("Failed to send request");

    if !res.status().is_success() {
        println!("body = {:?}", res.text());
    }
}

// function to append zero to a number until 16 characters
fn pad_zeros(num: u64) -> String {
    let mut num_str = num.to_string();
    while num_str.len() < 16 {
        num_str = format!("0{num_str}");
    }
    num_str
}

fn main() {
    let service_name = "nextjs";
    let ipv4 = "127.0.0.1";
    let port = 9411;
    let zipkin_url = format!("http://{ipv4}:{port}");
    let jaeger_web_ui_url = format!("http://{ipv4}:16686");
    let zipkin_api = format!("{zipkin_url}/api/v2/spans");
    let mut logged_url = false;

    let mut local_endpoint = Map::new();
    local_endpoint.insert(
        "serviceName".to_string(),
        Value::String(service_name.to_string()),
    );
    local_endpoint.insert("ipv4".to_string(), Value::String(ipv4.to_string()));
    local_endpoint.insert("port".to_string(), Value::Number(Number::from(port)));

    let first_arg = args().nth(1).expect("Please provide a file name");

    if let Ok(lines) = read_lines(first_arg) {
        for json_to_parse in lines.map_while(Result::ok) {
            let v = match serde_json::from_str::<Vec<Value>>(&json_to_parse) {
                Ok(v) => v
                    .into_iter()
                    .map(|mut data| {
                        if !logged_url {
                            log_web_url(&jaeger_web_ui_url, data["traceId"].as_str().unwrap());
                            logged_url = true;
                        }
                        data["localEndpoint"] = Value::Object(local_endpoint.clone());

                        data["id"] = Value::String(pad_zeros(data["id"].as_u64().unwrap()));
                        if data["parentId"] != Value::Null {
                            data["parentId"] =
                                Value::String(pad_zeros(data["parentId"].as_u64().unwrap()));
                        }

                        if let Some(tags) = data["tags"].as_object_mut() {
                            for (_, value) in tags.iter_mut() {
                                if value.is_boolean() {
                                    let bool_val = value.as_bool().unwrap();
                                    *value = serde_json::Value::String(bool_val.to_string());
                                }
                            }
                        }

                        data
                    })
                    .collect::<Value>(),
                Err(e) => {
                    println!("{e}");
                    continue;
                }
            };

            let json_map = serde_json::to_string(&v).expect("Failed to serialize");

            // println!("{:}", json_map);

            send_json_to_zipkin(&zipkin_api, json_map);
        }
    }
}