memfaultd 1.26.1

Memfault daemon for embedded Linux systems. Observability, logging, crash reporting, and updating all in one service. Learn more at https://docs.memfault.com/
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//
// Copyright (c) Memfault, Inc.
// See License.txt for details
use std::{
    cmp::max,
    collections::HashMap,
    io::Read,
    iter::once,
    str::{from_utf8, FromStr},
    sync::mpsc::{channel, Receiver, Sender},
    time::Duration,
};

use eyre::{eyre, Result};
use log::{trace, warn};
use serde::{Deserialize, Serialize};
use tiny_http::{Method, Request, Response};

use crate::{
    cli::NotifyCrashRequest,
    http_server::{HttpHandler, HttpHandlerResult},
    metrics::{
        core_metrics::{
            METRIC_OPERATIONAL_CRASHES, METRIC_OPERATIONAL_CRASHES_PROCESS_PREFIX,
            METRIC_OPERATIONAL_CRASHFREE_HOURS, METRIC_OPERATIONAL_HOURS,
        },
        KeyedMetricReading,
    },
    util::time_measure::TimeMeasure,
};

use super::{MetricStringKey, MetricsMBox};

pub struct CrashFreeIntervalTracker<T: TimeMeasure> {
    last_interval_mark: T,
    last_crashfree_interval_mark: T,
    crash_count: u32,
    process_crash_count: HashMap<String, u64>,
    sender: Sender<CrashInfo<T>>,
    receiver: Receiver<CrashInfo<T>>,
    interval: Duration,
    elapsed_intervals_key: MetricStringKey,
    crashfree_intervals_key: MetricStringKey,
    crash_count_key: MetricStringKey,
    metrics_mbox: MetricsMBox,
}

#[derive(Debug, PartialEq, Eq)]
struct TimeMod<T: TimeMeasure> {
    count: u32,
    mark: T,
}

impl<T> CrashFreeIntervalTracker<T>
where
    T: TimeMeasure + Copy + Ord + std::ops::Add<Duration, Output = T> + Send + Sync + 'static,
{
    pub fn new(
        interval: Duration,
        elapsed_intervals_key: &'static str,
        crashfree_intervals_key: &'static str,
        crash_count_key: &'static str,
        metrics_mbox: MetricsMBox,
    ) -> Self {
        let (sender, receiver) = channel();
        Self {
            last_crashfree_interval_mark: T::now(),
            last_interval_mark: T::now(),
            sender,
            receiver,
            crash_count: 0,
            process_crash_count: HashMap::new(),
            interval,
            elapsed_intervals_key: MetricStringKey::from(elapsed_intervals_key),
            crashfree_intervals_key: MetricStringKey::from(crashfree_intervals_key),
            crash_count_key: MetricStringKey::from(crash_count_key),
            metrics_mbox,
        }
    }

    /// Returns a tracker with an hourly interval
    pub fn new_hourly(metrics_mbox: MetricsMBox) -> Self {
        Self::new(
            Duration::from_secs(3600),
            METRIC_OPERATIONAL_HOURS,
            METRIC_OPERATIONAL_CRASHFREE_HOURS,
            METRIC_OPERATIONAL_CRASHES,
            metrics_mbox,
        )
    }

    /// Wait for the next crash or update the metrics if the wait duration has passed.
    ///
    /// This allows us to have instant updates on crashes and hourly updates on the metrics, but
    /// also allows us to periodically update the metrics so that we don't have to wait for a crash.
    pub fn wait_and_update(&mut self, wait_duration: Duration) -> Result<()> {
        if let Ok(crash_info) = self.receiver.recv_timeout(wait_duration) {
            // Drain the receiver to get all crashes that happened since the last update
            self.receiver
                .try_iter()
                .chain(once(crash_info))
                .for_each(|info| {
                    self.crash_count += 1;
                    self.last_crashfree_interval_mark =
                        max(self.last_crashfree_interval_mark, info.timestamp);
                    *self
                        .process_crash_count
                        .entry(info.process_name)
                        .or_insert(0) += 1;
                });
        }

        // Since timing out just means no crashes occurred in the `wait_duration`,
        // update even when the receiver times out.
        self.update()
    }

    fn update(&mut self) -> Result<()> {
        let TimeMod {
            count: count_op_interval,
            mark: last_counted_op_interval,
        } = Self::full_interval_elapsed_since(self.interval, &self.last_interval_mark);
        let TimeMod {
            count: count_crashfree_interval,
            mark: last_counted_crashfree_interval,
        } = Self::full_interval_elapsed_since(self.interval, &self.last_crashfree_interval_mark);

        self.last_interval_mark = last_counted_op_interval;
        self.last_crashfree_interval_mark = last_counted_crashfree_interval;

        let crashes = self.crash_count;
        self.crash_count = 0;

        let mut metrics = vec![
            KeyedMetricReading::add_to_counter(
                self.elapsed_intervals_key.clone(),
                count_op_interval as f64,
            ),
            KeyedMetricReading::add_to_counter(
                self.crashfree_intervals_key.clone(),
                count_crashfree_interval as f64,
            ),
            KeyedMetricReading::add_to_counter(self.crash_count_key.clone(), crashes as f64),
        ];

        let process_crash_metrics = self.process_crash_count.drain().flat_map(
            |(process_name, crash_count)| -> Result<KeyedMetricReading> {
                let operation_crashes_process_key = MetricStringKey::from_str(
                    format!(
                        "{}{}",
                        METRIC_OPERATIONAL_CRASHES_PROCESS_PREFIX, process_name
                    )
                    .as_str(),
                )
                .map_err(|e| eyre!("Couldn't construct MetricStringKey: {}", e))?;
                Ok(KeyedMetricReading::add_to_counter(
                    operation_crashes_process_key,
                    crash_count as f64,
                ))
            },
        );

        metrics.extend(process_crash_metrics);

        trace!("Crashfree hours metrics: {:?}", metrics);

        self.metrics_mbox.send_and_forget(metrics)?;

        Ok(())
    }

    pub fn http_handler(&mut self) -> Box<dyn HttpHandler> {
        Box::new(CrashFreeIntervalHttpHandler {
            channel: self.sender.clone(),
        })
    }

    pub fn channel_handler(&mut self) -> Box<Sender<CrashInfo<T>>> {
        Box::new(self.sender.clone())
    }

    pub fn capture_crash(&self, process_name: String) {
        self.sender
            .send(CrashInfo {
                process_name,
                timestamp: T::now(),
            })
            .expect("Failed to send crash timestamp");
    }

    /// Count how many `interval` have elapsed since `since`.
    ///
    /// This returns the number of intervals that have elapsed since `since`, and the timestamp of the end of the last interval
    /// that was counted. This is the value you should pass as `since` next time you call this function.
    ///
    /// See unit test for examples.
    fn full_interval_elapsed_since(interval: Duration, since: &T) -> TimeMod<T> {
        let now = T::now();
        if *since > now {
            return TimeMod {
                count: 0,
                mark: T::now(),
            };
        }

        let duration = now.since(since);
        let count_interval_elapsed = (duration.as_nanos() / interval.as_nanos()) as u32;
        TimeMod {
            count: count_interval_elapsed,
            mark: since.add(interval * count_interval_elapsed),
        }
    }
}

struct CrashFreeIntervalHttpHandler<T> {
    channel: Sender<CrashInfo<T>>,
}

#[derive(Serialize, Deserialize)]
pub struct CrashInfo<T> {
    pub process_name: String,
    pub timestamp: T,
}

impl<T> CrashFreeIntervalHttpHandler<T>
where
    T: TimeMeasure + Copy + Ord + std::ops::Add<Duration, Output = T> + Send + Sync,
{
    fn parse_notify_crash_request(stream: &mut dyn Read) -> Result<NotifyCrashRequest> {
        let mut buf = vec![];
        stream.read_to_end(&mut buf)?;
        let reading = serde_json::from_str(from_utf8(&buf)?)?;
        Ok(reading)
    }
}

impl<T> HttpHandler for CrashFreeIntervalHttpHandler<T>
where
    T: TimeMeasure + Copy + Ord + std::ops::Add<Duration, Output = T> + Send + Sync,
{
    fn handle_request(&self, request: &mut Request) -> HttpHandlerResult {
        if request.url() == "/v1/crash/report" && request.method() == &Method::Post {
            match Self::parse_notify_crash_request(request.as_reader()) {
                Ok(NotifyCrashRequest { process_name }) => {
                    self.channel
                        .send(CrashInfo {
                            process_name,
                            timestamp: T::now(),
                        })
                        .expect("Crashfree channel closed");
                }
                Err(e) => {
                    warn!("Failed to parse notify crash request: {}", e);
                    return HttpHandlerResult::Error(format!(
                        "Failed to notify crash request: {}",
                        e
                    ));
                }
            }
            HttpHandlerResult::Response(Response::from_string("OK").boxed())
        } else {
            HttpHandlerResult::NotHandled
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{collections::BTreeMap, time::Duration};

    use insta::assert_json_snapshot;
    use rstest::rstest;
    use ssf::ServiceMock;

    use crate::{
        metrics::{
            crashfree_interval::{
                METRIC_OPERATIONAL_CRASHES, METRIC_OPERATIONAL_CRASHFREE_HOURS,
                METRIC_OPERATIONAL_HOURS,
            },
            MetricStringKey, MetricValue, TakeMetrics,
        },
        test_utils::TestInstant,
    };

    use super::CrashFreeIntervalTracker;
    use super::TimeMod;

    #[rstest]
    fn test_counting_intervals() {
        use std::time::Duration;

        // move the clock forward so we can go backwards below
        TestInstant::sleep(Duration::from_secs(3600));
        let now = TestInstant::now();

        let d10 = Duration::from_secs(10);
        assert_eq!(
            CrashFreeIntervalTracker::full_interval_elapsed_since(d10, &now),
            TimeMod {
                count: 0,
                mark: now
            }
        );
        assert_eq!(
            CrashFreeIntervalTracker::full_interval_elapsed_since(
                d10,
                &(now - Duration::from_secs(10))
            ),
            TimeMod {
                count: 1,
                mark: now
            }
        );
        assert_eq!(
            CrashFreeIntervalTracker::full_interval_elapsed_since(
                d10,
                &(now - Duration::from_secs(25))
            ),
            TimeMod {
                count: 2,
                mark: now - Duration::from_secs(5)
            }
        );
    }

    #[rstest]
    fn test_counting_hours() {
        let mut metrics_mock = ServiceMock::new();
        let mut crashfree_tracker =
            CrashFreeIntervalTracker::<TestInstant>::new_hourly(metrics_mock.mbox.clone());

        TestInstant::sleep(Duration::from_secs(7200));

        crashfree_tracker
            .wait_and_update(Duration::from_secs(0))
            .unwrap();

        assert_operational_metrics(metrics_mock.take_metrics().unwrap(), 2, 2);
    }

    #[rstest]
    fn test_counting_minutes() {
        let mut metrics_mock = ServiceMock::new();
        let mut crashfree_tracker = CrashFreeIntervalTracker::<TestInstant>::new(
            Duration::from_secs(60),
            METRIC_OPERATIONAL_HOURS,
            METRIC_OPERATIONAL_CRASHFREE_HOURS,
            METRIC_OPERATIONAL_CRASHES,
            metrics_mock.mbox.clone(),
        );

        TestInstant::sleep(Duration::from_secs(3600));
        crashfree_tracker.capture_crash("memfaultd".to_string());
        TestInstant::sleep(Duration::from_secs(3600));

        crashfree_tracker
            .wait_and_update(Duration::from_secs(0))
            .unwrap();
        assert_operational_metrics(metrics_mock.take_metrics().unwrap(), 120, 60);
    }

    #[rstest]
    fn test_30min_heartbeat() {
        let mut metrics_mock = ServiceMock::new();
        let mut crashfree_tracker =
            CrashFreeIntervalTracker::<TestInstant>::new_hourly(metrics_mock.mbox.clone());

        TestInstant::sleep(Duration::from_secs(1800));
        crashfree_tracker
            .wait_and_update(Duration::from_secs(0))
            .unwrap();
        assert_operational_metrics(metrics_mock.take_metrics().unwrap(), 0, 0);

        TestInstant::sleep(Duration::from_secs(1800));
        crashfree_tracker
            .wait_and_update(Duration::from_secs(0))
            .unwrap();
        assert_operational_metrics(metrics_mock.take_metrics().unwrap(), 1, 1);
    }

    #[rstest]
    fn test_30min_heartbeat_with_crash() {
        let mut metrics_mock = ServiceMock::new();
        let mut crashfree_tracker =
            CrashFreeIntervalTracker::<TestInstant>::new_hourly(metrics_mock.mbox.clone());

        TestInstant::sleep(Duration::from_secs(1800));
        crashfree_tracker
            .wait_and_update(Duration::from_secs(0))
            .unwrap();
        assert_operational_metrics(metrics_mock.take_metrics().unwrap(), 0, 0);

        // Crash at t0 + 30min
        crashfree_tracker.capture_crash("memfaultd".to_string());

        // After 30' we should be ready to mark an operational hour
        TestInstant::sleep(Duration::from_secs(1800));
        crashfree_tracker
            .wait_and_update(Duration::from_secs(0))
            .unwrap();
        assert_operational_metrics(metrics_mock.take_metrics().unwrap(), 1, 0);

        // After another 30' we should be ready to mark another crashfree hour
        TestInstant::sleep(Duration::from_secs(1800));
        crashfree_tracker
            .wait_and_update(Duration::from_secs(0))
            .unwrap();
        assert_operational_metrics(metrics_mock.take_metrics().unwrap(), 0, 1);

        // After another 30' we should be ready to mark another operational hour
        TestInstant::sleep(Duration::from_secs(1800));
        crashfree_tracker
            .wait_and_update(Duration::from_secs(0))
            .unwrap();
        assert_operational_metrics(metrics_mock.take_metrics().unwrap(), 1, 0);
    }

    #[rstest]
    fn test_180min_heartbeat_with_one_crash() {
        let mut metrics_mock = ServiceMock::new();
        let mut crashfree_tracker =
            CrashFreeIntervalTracker::<TestInstant>::new_hourly(metrics_mock.mbox.clone());

        // Basic test
        TestInstant::sleep(Duration::from_secs(3600 * 3));
        crashfree_tracker
            .wait_and_update(Duration::from_secs(0))
            .unwrap();
        assert_operational_metrics(metrics_mock.take_metrics().unwrap(), 3, 3);

        // Crash at interval + 170'
        TestInstant::sleep(Duration::from_secs(170 * 60));
        crashfree_tracker.capture_crash("memfaultd".to_string());

        // Another 10' to the heartbeat mark
        // We will count 0 operational hour here. That is a consequence of the heartbeat being larger than the hour
        // To avoid this bug, we need to make sure we call the `update` at least once per hour!
        TestInstant::sleep(Duration::from_secs(10 * 60));
        crashfree_tracker
            .wait_and_update(Duration::from_secs(0))
            .unwrap();
        assert_operational_metrics(metrics_mock.take_metrics().unwrap(), 3, 0);

        // However, doing the crash at interval +10' then waiting for 170' will record 2 crashfree hours
        TestInstant::sleep(Duration::from_secs(10 * 60));
        crashfree_tracker.capture_crash("memfaultd".to_string());
        TestInstant::sleep(Duration::from_secs(170 * 60));
        crashfree_tracker
            .wait_and_update(Duration::from_secs(0))
            .unwrap();
        assert_operational_metrics(metrics_mock.take_metrics().unwrap(), 3, 2);
    }

    #[rstest]
    fn test_process_crash_counter() {
        let mut metrics_mock = ServiceMock::new();
        let mut crashfree_tracker =
            CrashFreeIntervalTracker::<TestInstant>::new_hourly(metrics_mock.mbox.clone());

        crashfree_tracker.capture_crash("memfaultd".to_string());
        crashfree_tracker.capture_crash("memfaultd".to_string());
        crashfree_tracker.capture_crash("memfaultd".to_string());
        crashfree_tracker.capture_crash("collectd".to_string());

        TestInstant::sleep(Duration::from_secs(3600));
        crashfree_tracker
            .wait_and_update(Duration::from_secs(0))
            .unwrap();
        assert_json_snapshot!(metrics_mock.take_metrics().unwrap());
    }

    fn assert_operational_metrics(
        metrics: BTreeMap<MetricStringKey, MetricValue>,
        expected_op_hours: u32,
        expected_crashfree_hours: u32,
    ) {
        let op_hours = metrics
            .iter()
            .find(|(name, _)| name.as_str() == METRIC_OPERATIONAL_HOURS)
            .map(|(_, value)| value)
            .unwrap();
        let crash_free_hours = metrics
            .iter()
            .find(|(name, _)| name.as_str() == METRIC_OPERATIONAL_CRASHFREE_HOURS)
            .map(|(_, value)| value)
            .unwrap();

        let op_hours_value = match op_hours {
            MetricValue::Number(value) => value,
            _ => panic!("Unexpected metric type"),
        };

        let crashfree_hours_value = match crash_free_hours {
            MetricValue::Number(value) => value,
            _ => panic!("Unexpected metric type"),
        };

        assert_eq!(
            (*op_hours_value as u32, *crashfree_hours_value as u32),
            (expected_op_hours, expected_crashfree_hours)
        );
    }
}