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, RecvTimeoutError, Sender},
6    gethostname::gethostname,
7    lazy_static::lazy_static,
8    log::*,
9    solana_sdk::{genesis_config::ClusterType, hash::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.recv_timeout(write_frequency / 2) {
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(RecvTimeoutError::Timeout) => (),
338                Err(RecvTimeoutError::Disconnected) => {
339                    debug!("run: sender disconnected");
340                    break;
341                }
342            }
343
344            let now = Instant::now();
345            if now.duration_since(last_write_time) >= write_frequency {
346                last_write_time = write(last_write_time, &mut points, &mut counters);
347            }
348        }
349
350        debug_assert!(
351            points.is_empty() && counters.is_empty(),
352            "Controlling `MetricsAgent` is expected to call `flush()` from the `Drop` \n\
353             implementation, before exiting.  So both `points` and `counters` must be empty at \n\
354             this point.\n\
355             `points`: {points:?}\n\
356             `counters`: {counters:?}",
357        );
358
359        trace!("run: exit");
360    }
361
362    pub fn submit(&self, point: DataPoint, level: log::Level) {
363        self.sender
364            .send(MetricsCommand::Submit(point, level))
365            .unwrap();
366    }
367
368    pub fn submit_counter(&self, counter: CounterPoint, level: log::Level, bucket: u64) {
369        self.sender
370            .send(MetricsCommand::SubmitCounter(counter, level, bucket))
371            .unwrap();
372    }
373
374    pub fn flush(&self) {
375        debug!("Flush");
376        let barrier = Arc::new(Barrier::new(2));
377        self.sender
378            .send(MetricsCommand::Flush(Arc::clone(&barrier)))
379            .unwrap();
380
381        barrier.wait();
382    }
383}
384
385impl Drop for MetricsAgent {
386    fn drop(&mut self) {
387        self.flush();
388    }
389}
390
391fn get_singleton_agent() -> &'static MetricsAgent {
392    lazy_static! {
393        static ref AGENT: MetricsAgent = MetricsAgent::default();
394    };
395
396    &AGENT
397}
398
399lazy_static! {
400    static ref HOST_ID: Arc<RwLock<String>> = {
401        Arc::new(RwLock::new({
402            let hostname: String = gethostname()
403                .into_string()
404                .unwrap_or_else(|_| "".to_string());
405            format!("{}", hash(hostname.as_bytes()))
406        }))
407    };
408}
409
410pub fn set_host_id(host_id: String) {
411    info!("host id: {}", host_id);
412    *HOST_ID.write().unwrap() = host_id;
413}
414
415/// Submits a new point from any thread.  Note that points are internally queued
416/// and transmitted periodically in batches.
417pub fn submit(point: DataPoint, level: log::Level) {
418    let agent = get_singleton_agent();
419    agent.submit(point, level);
420}
421
422/// Submits a new counter or updates an existing counter from any thread.  Note that points are
423/// internally queued and transmitted periodically in batches.
424pub(crate) fn submit_counter(point: CounterPoint, level: log::Level, bucket: u64) {
425    let agent = get_singleton_agent();
426    agent.submit_counter(point, level, bucket);
427}
428
429#[derive(Debug, Default)]
430struct MetricsConfig {
431    pub host: String,
432    pub db: String,
433    pub username: String,
434    pub password: String,
435}
436
437impl MetricsConfig {
438    fn complete(&self) -> bool {
439        !(self.host.is_empty()
440            || self.db.is_empty()
441            || self.username.is_empty()
442            || self.password.is_empty())
443    }
444}
445
446fn get_metrics_config() -> Result<MetricsConfig, MetricsError> {
447    let mut config = MetricsConfig::default();
448    let config_var = env::var("SOLANA_METRICS_CONFIG")?;
449    if config_var.is_empty() {
450        Err(env::VarError::NotPresent)?;
451    }
452
453    for pair in config_var.split(',') {
454        let nv: Vec<_> = pair.split('=').collect();
455        if nv.len() != 2 {
456            return Err(MetricsError::ConfigInvalid(pair.to_string()));
457        }
458        let v = nv[1].to_string();
459        match nv[0] {
460            "host" => config.host = v,
461            "db" => config.db = v,
462            "u" => config.username = v,
463            "p" => config.password = v,
464            _ => return Err(MetricsError::ConfigInvalid(pair.to_string())),
465        }
466    }
467
468    if !config.complete() {
469        return Err(MetricsError::ConfigIncomplete);
470    }
471
472    Ok(config)
473}
474
475pub fn metrics_config_sanity_check(cluster_type: ClusterType) -> Result<(), MetricsError> {
476    let config = match get_metrics_config() {
477        Ok(config) => config,
478        Err(MetricsError::VarError(env::VarError::NotPresent)) => return Ok(()),
479        Err(e) => return Err(e),
480    };
481    match &config.db[..] {
482        "mainnet-beta" if cluster_type != ClusterType::MainnetBeta => (),
483        "tds" if cluster_type != ClusterType::Testnet => (),
484        "devnet" if cluster_type != ClusterType::Devnet => (),
485        _ => return Ok(()),
486    };
487    let (host, db) = (&config.host, &config.db);
488    let msg = format!("cluster_type={cluster_type:?} host={host} database={db}");
489    Err(MetricsError::DbMismatch(msg))
490}
491
492pub fn query(q: &str) -> Result<String, MetricsError> {
493    let config = get_metrics_config()?;
494    let query_url = format!(
495        "{}/query?u={}&p={}&q={}",
496        &config.host, &config.username, &config.password, &q
497    );
498
499    let response = reqwest::blocking::get(query_url.as_str())?.text()?;
500
501    Ok(response)
502}
503
504/// Blocks until all pending points from previous calls to `submit` have been
505/// transmitted.
506pub fn flush() {
507    let agent = get_singleton_agent();
508    agent.flush();
509}
510
511/// Hook the panic handler to generate a data point on each panic
512pub fn set_panic_hook(program: &'static str, version: Option<String>) {
513    static SET_HOOK: Once = Once::new();
514    SET_HOOK.call_once(|| {
515        let default_hook = std::panic::take_hook();
516        std::panic::set_hook(Box::new(move |ono| {
517            default_hook(ono);
518            let location = match ono.location() {
519                Some(location) => location.to_string(),
520                None => "?".to_string(),
521            };
522            submit(
523                DataPoint::new("panic")
524                    .add_field_str("program", program)
525                    .add_field_str("thread", thread::current().name().unwrap_or("?"))
526                    // The 'one' field exists to give Kapacitor Alerts a numerical value
527                    // to filter on
528                    .add_field_i64("one", 1)
529                    .add_field_str("message", &ono.to_string())
530                    .add_field_str("location", &location)
531                    .add_field_str("version", version.as_ref().unwrap_or(&"".to_string()))
532                    .to_owned(),
533                Level::Error,
534            );
535            // Flush metrics immediately
536            flush();
537
538            // Exit cleanly so the process don't limp along in a half-dead state
539            std::process::exit(1);
540        }));
541    });
542}
543
544pub mod test_mocks {
545    use super::*;
546
547    pub struct MockMetricsWriter {
548        pub points_written: Arc<Mutex<Vec<DataPoint>>>,
549    }
550    impl MockMetricsWriter {
551        pub fn new() -> Self {
552            MockMetricsWriter {
553                points_written: Arc::new(Mutex::new(Vec::new())),
554            }
555        }
556
557        pub fn points_written(&self) -> usize {
558            self.points_written.lock().unwrap().len()
559        }
560    }
561
562    impl Default for MockMetricsWriter {
563        fn default() -> Self {
564            Self::new()
565        }
566    }
567
568    impl MetricsWriter for MockMetricsWriter {
569        fn write(&self, points: Vec<DataPoint>) {
570            assert!(!points.is_empty());
571
572            let new_points = points.len();
573            self.points_written.lock().unwrap().extend(points);
574
575            info!(
576                "Writing {} points ({} total)",
577                new_points,
578                self.points_written(),
579            );
580        }
581    }
582}
583
584#[cfg(test)]
585mod test {
586    use {super::*, test_mocks::MockMetricsWriter};
587
588    #[test]
589    fn test_submit() {
590        let writer = Arc::new(MockMetricsWriter::new());
591        let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(10), 1000);
592
593        for i in 0..42 {
594            agent.submit(
595                DataPoint::new("measurement")
596                    .add_field_i64("i", i)
597                    .to_owned(),
598                Level::Info,
599            );
600        }
601
602        agent.flush();
603        assert_eq!(writer.points_written(), 43);
604    }
605
606    #[test]
607    fn test_submit_counter() {
608        let writer = Arc::new(MockMetricsWriter::new());
609        let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(10), 1000);
610
611        for i in 0..10 {
612            agent.submit_counter(CounterPoint::new("counter 1"), Level::Info, i);
613            agent.submit_counter(CounterPoint::new("counter 2"), Level::Info, i);
614        }
615
616        agent.flush();
617        assert_eq!(writer.points_written(), 21);
618    }
619
620    #[test]
621    fn test_submit_counter_increment() {
622        let writer = Arc::new(MockMetricsWriter::new());
623        let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(10), 1000);
624
625        for _ in 0..10 {
626            agent.submit_counter(
627                CounterPoint {
628                    name: "counter",
629                    count: 10,
630                    timestamp: UNIX_EPOCH,
631                },
632                Level::Info,
633                0, // use the same bucket
634            );
635        }
636
637        agent.flush();
638        assert_eq!(writer.points_written(), 2);
639
640        let submitted_point = writer.points_written.lock().unwrap()[0].clone();
641        assert_eq!(submitted_point.fields[0], ("count", "100i".to_string()));
642    }
643
644    #[test]
645    fn test_submit_bucketed_counter() {
646        let writer = Arc::new(MockMetricsWriter::new());
647        let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(10), 1000);
648
649        for i in 0..50 {
650            agent.submit_counter(CounterPoint::new("counter 1"), Level::Info, i / 10);
651            agent.submit_counter(CounterPoint::new("counter 2"), Level::Info, i / 10);
652        }
653
654        agent.flush();
655        assert_eq!(writer.points_written(), 11);
656    }
657
658    #[test]
659    fn test_submit_with_delay() {
660        let writer = Arc::new(MockMetricsWriter::new());
661        let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(1), 1000);
662
663        agent.submit(DataPoint::new("point 1"), Level::Info);
664        thread::sleep(Duration::from_secs(2));
665        assert_eq!(writer.points_written(), 2);
666    }
667
668    #[test]
669    fn test_submit_exceed_max_rate() {
670        let writer = Arc::new(MockMetricsWriter::new());
671
672        let max_points_per_sec = 100;
673
674        let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(1), max_points_per_sec);
675
676        for i in 0..(max_points_per_sec + 20) {
677            agent.submit(
678                DataPoint::new("measurement")
679                    .add_field_i64("i", i.try_into().unwrap())
680                    .to_owned(),
681                Level::Info,
682            );
683        }
684
685        thread::sleep(Duration::from_secs(2));
686
687        agent.flush();
688
689        // We are expecting `max_points_per_sec - 1` data points from `submit()` and two more metric
690        // stats data points.  One from the timeout when all the `submit()`ed values are sent when 1
691        // second is elapsed, and then one more from the explicit `flush()`.
692        assert_eq!(writer.points_written(), max_points_per_sec + 1);
693    }
694
695    #[test]
696    fn test_multithread_submit() {
697        let writer = Arc::new(MockMetricsWriter::new());
698        let agent = Arc::new(Mutex::new(MetricsAgent::new(
699            writer.clone(),
700            Duration::from_secs(10),
701            1000,
702        )));
703
704        //
705        // Submit measurements from different threads
706        //
707        let mut threads = Vec::new();
708        for i in 0..42 {
709            let mut point = DataPoint::new("measurement");
710            point.add_field_i64("i", i);
711            let agent = Arc::clone(&agent);
712            threads.push(thread::spawn(move || {
713                agent.lock().unwrap().submit(point, Level::Info);
714            }));
715        }
716
717        for thread in threads {
718            thread.join().unwrap();
719        }
720
721        agent.lock().unwrap().flush();
722        assert_eq!(writer.points_written(), 43);
723    }
724
725    #[test]
726    fn test_flush_before_drop() {
727        let writer = Arc::new(MockMetricsWriter::new());
728        {
729            let agent = MetricsAgent::new(writer.clone(), Duration::from_secs(9_999_999), 1000);
730            agent.submit(DataPoint::new("point 1"), Level::Info);
731        }
732
733        // The datapoints we expect to see are:
734        // 1. `point 1` from the above.
735        // 2. `metrics` stats submitted as a result of the `Flush` sent by `agent` being destroyed.
736        assert_eq!(writer.points_written(), 2);
737    }
738
739    #[test]
740    fn test_live_submit() {
741        let agent = MetricsAgent::default();
742
743        let point = DataPoint::new("live_submit_test")
744            .add_field_bool("true", true)
745            .add_field_bool("random_bool", rand::random::<u8>() < 128)
746            .add_field_i64("random_int", rand::random::<u8>() as i64)
747            .to_owned();
748        agent.submit(point, Level::Info);
749    }
750}