solana_metrics/
metrics.rs

1//! The `metrics` module enables sending measurements to an `InfluxDB` instance
2
3use {
4    crate::{counter::CounterPoint, datapoint::DataPoint},
5    crossbeam_channel::{unbounded, Receiver, Sender, TryRecvError},
6    gethostname::gethostname,
7    log::*,
8    solana_cluster_type::ClusterType,
9    solana_sha256_hasher::hash,
10    std::{
11        cmp,
12        collections::HashMap,
13        convert::Into,
14        env,
15        fmt::Write,
16        sync::{Arc, Barrier, Mutex, Once, RwLock},
17        thread,
18        time::{Duration, Instant, UNIX_EPOCH},
19    },
20    thiserror::Error,
21};
22
23type CounterMap = HashMap<(&'static str, u64), CounterPoint>;
24
25#[derive(Debug, Error)]
26pub enum MetricsError {
27    #[error(transparent)]
28    VarError(#[from] env::VarError),
29    #[error(transparent)]
30    ReqwestError(#[from] reqwest::Error),
31    #[error("SOLANA_METRICS_CONFIG is invalid: '{0}'")]
32    ConfigInvalid(String),
33    #[error("SOLANA_METRICS_CONFIG is incomplete")]
34    ConfigIncomplete,
35    #[error("SOLANA_METRICS_CONFIG database mismatch: {0}")]
36    DbMismatch(String),
37}
38
39impl From<MetricsError> for String {
40    fn from(error: MetricsError) -> Self {
41        error.to_string()
42    }
43}
44
45impl From<&CounterPoint> for DataPoint {
46    fn from(counter_point: &CounterPoint) -> Self {
47        let mut point = Self::new(counter_point.name);
48        point.timestamp = counter_point.timestamp;
49        point.add_field_i64("count", counter_point.count);
50        point
51    }
52}
53
54#[derive(Debug)]
55enum MetricsCommand {
56    Flush(Arc<Barrier>),
57    Submit(DataPoint, log::Level),
58    SubmitCounter(CounterPoint, log::Level, u64),
59}
60
61pub struct MetricsAgent {
62    sender: Sender<MetricsCommand>,
63}
64
65pub trait MetricsWriter {
66    // Write the points and empty the vector.  Called on the internal
67    // MetricsAgent worker thread.
68    fn write(&self, points: Vec<DataPoint>);
69}
70
71struct InfluxDbMetricsWriter {
72    write_url: Option<String>,
73}
74
75impl InfluxDbMetricsWriter {
76    fn new() -> Self {
77        Self {
78            write_url: Self::build_write_url().ok(),
79        }
80    }
81
82    fn build_write_url() -> Result<String, MetricsError> {
83        let config = get_metrics_config().map_err(|err| {
84            info!("metrics disabled: {}", err);
85            err
86        })?;
87
88        info!(
89            "metrics configuration: host={} db={} username={}",
90            config.host, config.db, config.username
91        );
92
93        let write_url = format!(
94            "{}/write?db={}&u={}&p={}&precision=n",
95            &config.host, &config.db, &config.username, &config.password
96        );
97
98        Ok(write_url)
99    }
100}
101
102pub fn serialize_points(points: &Vec<DataPoint>, host_id: &str) -> String {
103    const TIMESTAMP_LEN: usize = 20;
104    const HOST_ID_LEN: usize = 8; // "host_id=".len()
105    const EXTRA_LEN: usize = 2; // "=,".len()
106    let mut len = 0;
107    for point in points {
108        for (name, value) in &point.fields {
109            len += name.len() + value.len() + EXTRA_LEN;
110        }
111        for (name, value) in &point.tags {
112            len += name.len() + value.len() + EXTRA_LEN;
113        }
114        len += point.name.len();
115        len += TIMESTAMP_LEN;
116        len += host_id.len() + HOST_ID_LEN;
117    }
118    let mut line = String::with_capacity(len);
119    for point in points {
120        let _ = write!(line, "{},host_id={}", &point.name, host_id);
121        for (name, value) in point.tags.iter() {
122            let _ = write!(line, ",{name}={value}");
123        }
124
125        let mut first = true;
126        for (name, value) in point.fields.iter() {
127            let _ = write!(line, "{}{}={}", if first { ' ' } else { ',' }, name, value);
128            first = false;
129        }
130        let timestamp = point.timestamp.duration_since(UNIX_EPOCH);
131        let nanos = timestamp.unwrap().as_nanos();
132        let _ = writeln!(line, " {nanos}");
133    }
134    line
135}
136
137impl MetricsWriter for InfluxDbMetricsWriter {
138    fn write(&self, points: Vec<DataPoint>) {
139        if let Some(ref write_url) = self.write_url {
140            debug!("submitting {} points", points.len());
141
142            let host_id = HOST_ID.read().unwrap();
143
144            let line = serialize_points(&points, &host_id);
145
146            let client = reqwest::blocking::Client::builder()
147                .timeout(Duration::from_secs(5))
148                .build();
149            let client = match client {
150                Ok(client) => client,
151                Err(err) => {
152                    warn!("client instantiation failed: {}", err);
153                    return;
154                }
155            };
156
157            let response = client.post(write_url.as_str()).body(line).send();
158            if let Ok(resp) = response {
159                let status = resp.status();
160                if !status.is_success() {
161                    let text = resp
162                        .text()
163                        .unwrap_or_else(|_| "[text body empty]".to_string());
164                    warn!("submit response unsuccessful: {} {}", status, text,);
165                }
166            } else {
167                warn!("submit error: {}", response.unwrap_err());
168            }
169        }
170    }
171}
172
173impl Default for MetricsAgent {
174    fn default() -> Self {
175        let max_points_per_sec = env::var("SOLANA_METRICS_MAX_POINTS_PER_SECOND")
176            .map(|x| {
177                x.parse()
178                    .expect("Failed to parse SOLANA_METRICS_MAX_POINTS_PER_SECOND")
179            })
180            .unwrap_or(4000);
181
182        Self::new(
183            Arc::new(InfluxDbMetricsWriter::new()),
184            Duration::from_secs(10),
185            max_points_per_sec,
186        )
187    }
188}
189
190impl MetricsAgent {
191    pub fn new(
192        writer: Arc<dyn MetricsWriter + Send + Sync>,
193        write_frequency: Duration,
194        max_points_per_sec: usize,
195    ) -> Self {
196        let (sender, receiver) = unbounded::<MetricsCommand>();
197
198        thread::Builder::new()
199            .name("solMetricsAgent".into())
200            .spawn(move || Self::run(&receiver, &writer, write_frequency, max_points_per_sec))
201            .unwrap();
202
203        Self { sender }
204    }
205
206    // Combines `points` and `counters` into a single array of `DataPoint`s, appending a data point
207    // with the metrics stats at the end.
208    //
209    // Limits the number of produced points to the `max_points` value.  Takes `points` followed by
210    // `counters`, dropping `counters` first.
211    //
212    // `max_points_per_sec` is only used in a warning message.
213    // `points_buffered` is used in the stats.
214    fn combine_points(
215        max_points: usize,
216        max_points_per_sec: usize,
217        secs_since_last_write: u64,
218        points_buffered: usize,
219        points: &mut Vec<DataPoint>,
220        counters: &mut CounterMap,
221    ) -> Vec<DataPoint> {
222        // Reserve one slot for the stats point we will add at the end.
223        let max_points = max_points.saturating_sub(1);
224
225        let num_points = points.len().saturating_add(counters.len());
226        let fit_counters = max_points.saturating_sub(points.len());
227        let points_written = cmp::min(num_points, max_points);
228
229        debug!("run: attempting to write {} points", num_points);
230
231        if num_points > max_points {
232            warn!(
233                "Max submission rate of {} datapoints per second exceeded.  Only the \
234                 first {} of {} points will be submitted.",
235                max_points_per_sec, max_points, num_points
236            );
237        }
238
239        let mut combined = std::mem::take(points);
240        combined.truncate(points_written);
241
242        combined.extend(counters.values().take(fit_counters).map(|v| v.into()));
243        counters.clear();
244
245        combined.push(
246            DataPoint::new("metrics")
247                .add_field_i64("points_written", points_written as i64)
248                .add_field_i64("num_points", num_points as i64)
249                .add_field_i64("points_lost", (num_points - points_written) as i64)
250                .add_field_i64("points_buffered", points_buffered as i64)
251                .add_field_i64("secs_since_last_write", secs_since_last_write as i64)
252                .to_owned(),
253        );
254
255        combined
256    }
257
258    // Consumes provided `points`, sending up to `max_points` of them into the `writer`.
259    //
260    // Returns an updated value for `last_write_time`.  Which is equal to `Instant::now()`, just
261    // before `write` in updated.
262    fn write(
263        writer: &Arc<dyn MetricsWriter + Send + Sync>,
264        max_points: usize,
265        max_points_per_sec: usize,
266        last_write_time: Instant,
267        points_buffered: usize,
268        points: &mut Vec<DataPoint>,
269        counters: &mut CounterMap,
270    ) -> Instant {
271        let now = Instant::now();
272        let secs_since_last_write = now.duration_since(last_write_time).as_secs();
273
274        writer.write(Self::combine_points(
275            max_points,
276            max_points_per_sec,
277            secs_since_last_write,
278            points_buffered,
279            points,
280            counters,
281        ));
282
283        now
284    }
285
286    fn run(
287        receiver: &Receiver<MetricsCommand>,
288        writer: &Arc<dyn MetricsWriter + Send + Sync>,
289        write_frequency: Duration,
290        max_points_per_sec: usize,
291    ) {
292        trace!("run: enter");
293        let mut last_write_time = Instant::now();
294        let mut points = Vec::<DataPoint>::new();
295        let mut counters = CounterMap::new();
296
297        let max_points = write_frequency.as_secs() as usize * max_points_per_sec;
298
299        // Bind common arguments in the `Self::write()` call.
300        let write = |last_write_time: Instant,
301                     points: &mut Vec<DataPoint>,
302                     counters: &mut CounterMap|
303         -> Instant {
304            Self::write(
305                writer,
306                max_points,
307                max_points_per_sec,
308                last_write_time,
309                receiver.len(),
310                points,
311                counters,
312            )
313        };
314
315        loop {
316            match receiver.try_recv() {
317                Ok(cmd) => match cmd {
318                    MetricsCommand::Flush(barrier) => {
319                        debug!("metrics_thread: flush");
320                        last_write_time = write(last_write_time, &mut points, &mut counters);
321                        barrier.wait();
322                    }
323                    MetricsCommand::Submit(point, level) => {
324                        log!(level, "{}", point);
325                        points.push(point);
326                    }
327                    MetricsCommand::SubmitCounter(counter, _level, bucket) => {
328                        debug!("{:?}", counter);
329                        let key = (counter.name, bucket);
330                        if let Some(value) = counters.get_mut(&key) {
331                            value.count += counter.count;
332                        } else {
333                            counters.insert(key, counter);
334                        }
335                    }
336                },
337                Err(TryRecvError::Empty) => {
338                    std::thread::sleep(Duration::from_millis(5));
339                }
340                Err(TryRecvError::Disconnected) => {
341                    debug!("run: sender disconnected");
342                    break;
343                }
344            };
345
346            let now = Instant::now();
347            if now.duration_since(last_write_time) >= write_frequency {
348                last_write_time = write(last_write_time, &mut points, &mut counters);
349            }
350        }
351
352        debug_assert!(
353            points.is_empty() && counters.is_empty(),
354            "Controlling `MetricsAgent` is expected to call `flush()` from the `Drop` \n\
355             implementation, before exiting.  So both `points` and `counters` must be empty at \n\
356             this point.\n\
357             `points`: {points:?}\n\
358             `counters`: {counters:?}",
359        );
360
361        trace!("run: exit");
362    }
363
364    pub fn submit(&self, point: DataPoint, level: log::Level) {
365        self.sender
366            .send(MetricsCommand::Submit(point, level))
367            .unwrap();
368    }
369
370    pub fn submit_counter(&self, counter: CounterPoint, level: log::Level, bucket: u64) {
371        self.sender
372            .send(MetricsCommand::SubmitCounter(counter, level, bucket))
373            .unwrap();
374    }
375
376    pub fn flush(&self) {
377        debug!("Flush");
378        let barrier = Arc::new(Barrier::new(2));
379        self.sender
380            .send(MetricsCommand::Flush(Arc::clone(&barrier)))
381            .unwrap();
382
383        barrier.wait();
384    }
385}
386
387impl Drop for MetricsAgent {
388    fn drop(&mut self) {
389        self.flush();
390    }
391}
392
393fn get_singleton_agent() -> &'static MetricsAgent {
394    static AGENT: std::sync::LazyLock<MetricsAgent> =
395        std::sync::LazyLock::new(MetricsAgent::default);
396    &AGENT
397}
398
399static HOST_ID: std::sync::LazyLock<RwLock<String>> = std::sync::LazyLock::new(|| {
400    RwLock::new({
401        let hostname: String = gethostname()
402            .into_string()
403            .unwrap_or_else(|_| "".to_string());
404        format!("{}", hash(hostname.as_bytes()))
405    })
406});
407
408pub fn set_host_id(host_id: String) {
409    info!("host id: {}", host_id);
410    *HOST_ID.write().unwrap() = host_id;
411}
412
413/// Submits a new point from any thread.  Note that points are internally queued
414/// and transmitted periodically in batches.
415pub fn submit(point: DataPoint, level: log::Level) {
416    let agent = get_singleton_agent();
417    agent.submit(point, level);
418}
419
420/// Submits a new counter or updates an existing counter from any thread.  Note that points are
421/// internally queued and transmitted periodically in batches.
422pub(crate) fn submit_counter(point: CounterPoint, level: log::Level, bucket: u64) {
423    let agent = get_singleton_agent();
424    agent.submit_counter(point, level, bucket);
425}
426
427#[derive(Debug, Default)]
428struct MetricsConfig {
429    pub host: String,
430    pub db: String,
431    pub username: String,
432    pub password: String,
433}
434
435impl MetricsConfig {
436    fn complete(&self) -> bool {
437        !(self.host.is_empty()
438            || self.db.is_empty()
439            || self.username.is_empty()
440            || self.password.is_empty())
441    }
442}
443
444fn get_metrics_config() -> Result<MetricsConfig, MetricsError> {
445    let mut config = MetricsConfig::default();
446    let config_var = env::var("SOLANA_METRICS_CONFIG")?;
447    if config_var.is_empty() {
448        Err(env::VarError::NotPresent)?;
449    }
450
451    for pair in config_var.split(',') {
452        let nv: Vec<_> = pair.split('=').collect();
453        if nv.len() != 2 {
454            return Err(MetricsError::ConfigInvalid(pair.to_string()));
455        }
456        let v = nv[1].to_string();
457        match nv[0] {
458            "host" => config.host = v,
459            "db" => config.db = v,
460            "u" => config.username = v,
461            "p" => config.password = v,
462            _ => return Err(MetricsError::ConfigInvalid(pair.to_string())),
463        }
464    }
465
466    if !config.complete() {
467        return Err(MetricsError::ConfigIncomplete);
468    }
469
470    Ok(config)
471}
472
473pub fn metrics_config_sanity_check(cluster_type: ClusterType) -> Result<(), MetricsError> {
474    let config = match get_metrics_config() {
475        Ok(config) => config,
476        Err(MetricsError::VarError(env::VarError::NotPresent)) => return Ok(()),
477        Err(e) => return Err(e),
478    };
479    match &config.db[..] {
480        "mainnet-beta" if cluster_type != ClusterType::MainnetBeta => (),
481        "tds" if cluster_type != ClusterType::Testnet => (),
482        "devnet" if cluster_type != ClusterType::Devnet => (),
483        _ => return Ok(()),
484    };
485    let (host, db) = (&config.host, &config.db);
486    let msg = format!("cluster_type={cluster_type:?} host={host} database={db}");
487    Err(MetricsError::DbMismatch(msg))
488}
489
490pub fn query(q: &str) -> Result<String, MetricsError> {
491    let config = get_metrics_config()?;
492    let query_url = format!(
493        "{}/query?u={}&p={}&q={}",
494        &config.host, &config.username, &config.password, &q
495    );
496
497    let response = reqwest::blocking::get(query_url.as_str())?.text()?;
498
499    Ok(response)
500}
501
502/// Blocks until all pending points from previous calls to `submit` have been
503/// transmitted.
504pub fn flush() {
505    let agent = get_singleton_agent();
506    agent.flush();
507}
508
509/// Hook the panic handler to generate a data point on each panic
510pub fn set_panic_hook(program: &'static str, version: Option<String>) {
511    static SET_HOOK: Once = Once::new();
512    SET_HOOK.call_once(|| {
513        let default_hook = std::panic::take_hook();
514        std::panic::set_hook(Box::new(move |ono| {
515            default_hook(ono);
516            let location = match ono.location() {
517                Some(location) => location.to_string(),
518                None => "?".to_string(),
519            };
520            submit(
521                DataPoint::new("panic")
522                    .add_field_str("program", program)
523                    .add_field_str("thread", thread::current().name().unwrap_or("?"))
524                    // The 'one' field exists to give Kapacitor Alerts a numerical value
525                    // to filter on
526                    .add_field_i64("one", 1)
527                    .add_field_str("message", &ono.to_string())
528                    .add_field_str("location", &location)
529                    .add_field_str("version", version.as_ref().unwrap_or(&"".to_string()))
530                    .to_owned(),
531                Level::Error,
532            );
533            // Flush metrics immediately
534            flush();
535
536            // Exit cleanly so the process don't limp along in a half-dead state
537            std::process::exit(1);
538        }));
539    });
540}
541
542pub mod test_mocks {
543    use super::*;
544
545    pub struct MockMetricsWriter {
546        pub points_written: Arc<Mutex<Vec<DataPoint>>>,
547    }
548    impl MockMetricsWriter {
549        pub fn new() -> Self {
550            MockMetricsWriter {
551                points_written: Arc::new(Mutex::new(Vec::new())),
552            }
553        }
554
555        pub fn points_written(&self) -> usize {
556            self.points_written.lock().unwrap().len()
557        }
558    }
559
560    impl Default for MockMetricsWriter {
561        fn default() -> Self {
562            Self::new()
563        }
564    }
565
566    impl MetricsWriter for MockMetricsWriter {
567        fn write(&self, points: Vec<DataPoint>) {
568            assert!(!points.is_empty());
569
570            let new_points = points.len();
571            self.points_written.lock().unwrap().extend(points);
572
573            info!(
574                "Writing {} points ({} total)",
575                new_points,
576                self.points_written(),
577            );
578        }
579    }
580}
581
582#[cfg(test)]
583mod test {
584    use {super::*, test_mocks::MockMetricsWriter};
585
586    #[test]
587    fn test_submit() {
588        let writer = Arc::new(MockMetricsWriter::new());
589        let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(10), 1000);
590
591        for i in 0..42 {
592            agent.submit(
593                DataPoint::new("measurement")
594                    .add_field_i64("i", i)
595                    .to_owned(),
596                Level::Info,
597            );
598        }
599
600        agent.flush();
601        assert_eq!(writer.points_written(), 43);
602    }
603
604    #[test]
605    fn test_submit_counter() {
606        let writer = Arc::new(MockMetricsWriter::new());
607        let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(10), 1000);
608
609        for i in 0..10 {
610            agent.submit_counter(CounterPoint::new("counter 1"), Level::Info, i);
611            agent.submit_counter(CounterPoint::new("counter 2"), Level::Info, i);
612        }
613
614        agent.flush();
615        assert_eq!(writer.points_written(), 21);
616    }
617
618    #[test]
619    fn test_submit_counter_increment() {
620        let writer = Arc::new(MockMetricsWriter::new());
621        let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(10), 1000);
622
623        for _ in 0..10 {
624            agent.submit_counter(
625                CounterPoint {
626                    name: "counter",
627                    count: 10,
628                    timestamp: UNIX_EPOCH,
629                },
630                Level::Info,
631                0, // use the same bucket
632            );
633        }
634
635        agent.flush();
636        assert_eq!(writer.points_written(), 2);
637
638        let submitted_point = writer.points_written.lock().unwrap()[0].clone();
639        assert_eq!(submitted_point.fields[0], ("count", "100i".to_string()));
640    }
641
642    #[test]
643    fn test_submit_bucketed_counter() {
644        let writer = Arc::new(MockMetricsWriter::new());
645        let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(10), 1000);
646
647        for i in 0..50 {
648            agent.submit_counter(CounterPoint::new("counter 1"), Level::Info, i / 10);
649            agent.submit_counter(CounterPoint::new("counter 2"), Level::Info, i / 10);
650        }
651
652        agent.flush();
653        assert_eq!(writer.points_written(), 11);
654    }
655
656    #[test]
657    fn test_submit_with_delay() {
658        let writer = Arc::new(MockMetricsWriter::new());
659        let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(1), 1000);
660
661        agent.submit(DataPoint::new("point 1"), Level::Info);
662        thread::sleep(Duration::from_secs(2));
663        assert_eq!(writer.points_written(), 2);
664    }
665
666    #[test]
667    fn test_submit_exceed_max_rate() {
668        let writer = Arc::new(MockMetricsWriter::new());
669
670        let max_points_per_sec = 100;
671
672        let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(1), max_points_per_sec);
673
674        for i in 0..(max_points_per_sec + 20) {
675            agent.submit(
676                DataPoint::new("measurement")
677                    .add_field_i64("i", i.try_into().unwrap())
678                    .to_owned(),
679                Level::Info,
680            );
681        }
682
683        agent.flush();
684
685        // We are expecting `max_points_per_sec - 1` data points from `submit()` and one more metric
686        // stats data points.
687        assert_eq!(writer.points_written(), max_points_per_sec);
688    }
689
690    #[test]
691    fn test_multithread_submit() {
692        let writer = Arc::new(MockMetricsWriter::new());
693        let agent = Arc::new(Mutex::new(MetricsAgent::new(
694            writer.clone(),
695            Duration::from_secs(10),
696            1000,
697        )));
698
699        //
700        // Submit measurements from different threads
701        //
702        let mut threads = Vec::new();
703        for i in 0..42 {
704            let mut point = DataPoint::new("measurement");
705            point.add_field_i64("i", i);
706            let agent = Arc::clone(&agent);
707            threads.push(thread::spawn(move || {
708                agent.lock().unwrap().submit(point, Level::Info);
709            }));
710        }
711
712        for thread in threads {
713            thread.join().unwrap();
714        }
715
716        agent.lock().unwrap().flush();
717        assert_eq!(writer.points_written(), 43);
718    }
719
720    #[test]
721    fn test_flush_before_drop() {
722        let writer = Arc::new(MockMetricsWriter::new());
723        {
724            let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(9_999_999), 1000);
725            agent.submit(DataPoint::new("point 1"), Level::Info);
726        }
727
728        // The datapoints we expect to see are:
729        // 1. `point 1` from the above.
730        // 2. `metrics` stats submitted as a result of the `Flush` sent by `agent` being destroyed.
731        assert_eq!(writer.points_written(), 2);
732    }
733
734    #[test]
735    fn test_live_submit() {
736        let agent = MetricsAgent::default();
737
738        let point = DataPoint::new("live_submit_test")
739            .add_field_bool("true", true)
740            .add_field_bool("random_bool", rand::random::<u8>() < 128)
741            .add_field_i64("random_int", rand::random::<u8>() as i64)
742            .to_owned();
743        agent.submit(point, Level::Info);
744    }
745}