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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
//
// Copyright (c) Memfault, Inc.
// See License.txt for details
use eyre::eyre;
use itertools::Itertools;
use std::net::SocketAddr;
use std::num::NonZeroU32;
use std::time::Duration;
use std::{
    path::{Path, PathBuf},
    sync::{Arc, RwLock},
};

use crate::{
    mar::{MarConfig, MarStagingCleanType},
    metrics::system_metrics::SystemMetricConfig,
};
use crate::{
    network::{NetworkClient, NetworkConfig},
    util::{DiskBacked, UnwrapOrDie, UpdateStatus},
};

use crate::util::disk_size::DiskSize;

#[cfg(test)]
pub use self::config_file::ConnectionCheckProtocol;

#[cfg(target_os = "linux")]
pub use self::config_file::{CoredumpCaptureStrategy, CoredumpCompression};

use self::device_info::DeviceInfoValue;
#[cfg(test)]
pub use self::device_info::MockDeviceInfoDefaults;
pub use self::{
    config_file::{
        ConnectivityMonitorConfig, ConnectivityMonitorTarget, JsonConfigs, LogFilterConfig,
        LogFilterRule, LogRuleAction, LogSource, LogToMetricRule, MemfaultdConfig, SessionConfig,
        StorageConfig, SyslogConfig,
    },
    device_config::{DeviceConfig, Resolution, Sampling},
    device_info::{DeviceInfo, DeviceInfoDefaultsImpl, DeviceInfoWarning},
};

use crate::mar::{MarEntryBuilder, Metadata};

use eyre::{Context, Result};

mod config_file;
pub use config_file::{
    LevelMappingConfig, LevelMappingRegex, LinuxCustomTraceConfig, LinuxCustomTraceLogCompression,
    PersistStorageConfig, TraceFilter,
};

mod device_config;
pub use device_config::{DeviceConfigLogging, DeviceConfigLoggingFilters};
mod device_info;
mod messages;
mod utils;

pub use messages::DeviceConfigUpdateMessage;

const FALLBACK_SOFTWARE_VERSION: &str = "0.0.0-memfault-unknown";
const FALLBACK_SOFTWARE_TYPE: &str = "memfault-unknown";

/// Container of the entire memfaultd configuration.
/// Implement `From<Config>` trait to initialize module specific configuration (see `NetworkConfig` for example).
pub struct Config {
    pub device_info: DeviceInfo,
    pub config_file: MemfaultdConfig,
    pub config_file_path: PathBuf,
    pub cached_device_config: Arc<RwLock<DiskBacked<DeviceConfig>>>,
}

const LOGS_SUBDIRECTORY: &str = "logs";
pub const MAR_STAGING_SUBDIRECTORY: &str = "mar";
const DEVICE_CONFIG_FILE: &str = "device_config.json";
const COREDUMP_RATE_LIMITER_FILENAME: &str = "coredump_rate_limit";
const TRACE_RATE_LIMITER_FILENAME: &str = "trace_rate_limit";

impl Config {
    pub const DEFAULT_CONFIG_PATH: &'static str = "/etc/memfaultd.conf";

    pub fn read_from_system(
        user_config: Option<&Path>,
        warnings_handle_fn: impl Fn(&DeviceInfoWarning),
    ) -> Result<Self> {
        // Select config file to read
        let config_file = user_config.unwrap_or_else(|| Path::new(Self::DEFAULT_CONFIG_PATH));

        let config = MemfaultdConfig::load(config_file).wrap_err(eyre!(
            "Unable to read config file {}",
            &config_file.display()
        ))?;

        let (device_info, warnings) =
            DeviceInfo::load().wrap_err(eyre!("Unable to load device info"))?;
        warnings.iter().for_each(warnings_handle_fn);

        let device_config = DiskBacked::from_path(&Self::device_config_path_from_config(&config));

        Ok(Self {
            device_info,
            config_file: config,
            config_file_path: config_file.to_owned(),
            cached_device_config: Arc::new(RwLock::new(device_config)),
        })
    }

    pub fn refresh_device_config(&self, client: &impl NetworkClient) -> Result<UpdateStatus> {
        let response = client.fetch_device_config()?;

        // Let the server know that we have applied the new version if it still
        // believes we have an older one.
        let confirm_version = match response.data.completed {
            Some(v) if v == response.data.revision => None,
            _ => Some(response.data.revision),
        };

        // Always write the config to our cache.
        let new_config: DeviceConfig = response.into();
        let update_status = self
            .cached_device_config
            .write()
            .unwrap_or_die()
            .set(new_config)?;

        // After saving, create the device-config confirmation MAR entry
        if let Some(revision) = confirm_version {
            let mar_staging = self.mar_tmp_staging_path();
            let mar_config = MarConfig::from(self);
            MarEntryBuilder::new(&mar_staging)?
                .set_metadata(Metadata::new_device_config(revision))
                .save(&NetworkConfig::from(self), &mar_config)?;
        }
        Ok(update_status)
    }

    pub fn tmp_dir(&self) -> PathBuf {
        match self.config_file.tmp_dir {
            Some(ref tmp_dir) => tmp_dir.clone(),
            None => self.config_file.persist_dir.clone(),
        }
        .into()
    }

    pub fn persist_dir(&self) -> PathBuf {
        self.config_file.persist_dir.clone().into()
    }

    pub fn tmp_dir_max_size(&self) -> DiskSize {
        DiskSize::new_capacity(self.config_file.tmp_dir_max_usage as u64)
    }

    pub fn tmp_dir_min_headroom(&self) -> DiskSize {
        DiskSize {
            bytes: self.config_file.tmp_dir_min_headroom as u64,
            inodes: self.config_file.tmp_dir_min_inodes as u64,
        }
    }

    pub fn coredump_rate_limiter_file_path(&self) -> PathBuf {
        self.tmp_dir().join(COREDUMP_RATE_LIMITER_FILENAME)
    }

    pub fn trace_rate_limiter_file_path(&self) -> PathBuf {
        self.tmp_dir().join(TRACE_RATE_LIMITER_FILENAME)
    }

    pub fn logs_path(&self) -> PathBuf {
        self.tmp_dir().join(LOGS_SUBDIRECTORY)
    }

    pub fn mar_tmp_staging_path(&self) -> PathBuf {
        self.tmp_dir().join(MAR_STAGING_SUBDIRECTORY)
    }

    pub fn mar_logs_clean_type(&self) -> MarStagingCleanType {
        self.mar_persist_storage_config()
            .and_then(|persist_config| persist_config.logs.then_some(MarStagingCleanType::Persist))
            .unwrap_or(MarStagingCleanType::Tmp)
    }

    pub fn mar_persist_staging_path(&self) -> PathBuf {
        self.config_file.persist_dir.join(MAR_STAGING_SUBDIRECTORY)
    }

    pub fn mar_persist_storage_config(&self) -> Option<&PersistStorageConfig> {
        self.config_file.persist_storage.as_ref()
    }

    fn device_config_path_from_config(config_file: &MemfaultdConfig) -> PathBuf {
        config_file.persist_dir.join(DEVICE_CONFIG_FILE)
    }
    pub fn device_config_path(&self) -> PathBuf {
        Self::device_config_path_from_config(&self.config_file)
    }

    pub fn sampling(&self) -> Sampling {
        if self.config_file.enable_dev_mode {
            Sampling::development()
        } else {
            self.device_config().sampling
        }
    }

    /// Returns the device_config at the time of the call. If the device_config is updated
    /// after this call, the returned value will not be updated.
    /// This can block for a small moment if another thread is currently updating the device_config.
    fn device_config(&self) -> DeviceConfig {
        self.cached_device_config
            .read()
            // If another thread crashed while holding the mutex we want to crash the program
            .unwrap_or_die()
            // If we were not able to load from local-cache then return the defaults.
            .get()
            .clone()
    }

    /// Returns the software version for the device.
    ///
    /// The precedence is as follows:
    /// 1. Configured software version in device_info
    /// 2. Configured software version in config_file
    /// 3. Default software version in device_info
    /// 4. Fallback software version
    pub fn software_version(&self) -> &str {
        match (
            &self.device_info.software_version,
            &self.config_file.software_version,
        ) {
            (Some(DeviceInfoValue::Configured(sw_version)), _) => sw_version.as_ref(),
            (None, Some(sw_version)) => sw_version.as_ref(),
            (Some(DeviceInfoValue::Default(_)), Some(sw_version)) => sw_version.as_ref(),
            (Some(DeviceInfoValue::Default(sw_version)), None) => sw_version.as_ref(),
            (None, None) => FALLBACK_SOFTWARE_VERSION,
        }
    }

    /// Returns the software type for the device.
    ///
    /// The precedence is as follows:
    /// 1. Configured software type in device_info
    /// 2. Configured software type in config_file
    /// 3. Default software type in device_info
    /// 4. Fallback software type
    pub fn software_type(&self) -> &str {
        match (
            &self.device_info.software_type,
            &self.config_file.software_type,
        ) {
            (Some(DeviceInfoValue::Configured(software_type)), _) => software_type.as_ref(),
            (None, Some(software_type)) => software_type.as_ref(),
            (Some(DeviceInfoValue::Default(_)), Some(software_type)) => software_type.as_ref(),
            (Some(DeviceInfoValue::Default(software_type)), None) => software_type.as_ref(),
            (None, None) => FALLBACK_SOFTWARE_TYPE,
        }
    }

    pub fn mar_entry_max_age(&self) -> Duration {
        self.config_file.mar.mar_entry_max_age
    }

    pub fn mar_entry_max_count(&self) -> usize {
        self.config_file.mar.mar_entry_max_count
    }

    pub fn battery_monitor_periodic_update_enabled(&self) -> bool {
        self.config_file.battery_monitor.is_some()
    }

    pub fn battery_monitor_battery_info_command(&self) -> Option<&str> {
        self.config_file
            .battery_monitor
            .as_ref()
            .and_then(|monitor| monitor.battery_info_command.as_ref())
            .map(|command| command.as_str())
    }

    pub fn battery_monitor_auto_mode(&self) -> bool {
        self.config_file
            .battery_monitor
            .as_ref()
            .is_some_and(|monitor| monitor.auto)
    }

    pub fn battery_monitor_interval(&self) -> Duration {
        match self.config_file.battery_monitor.as_ref() {
            Some(battery_config) => battery_config.interval_seconds,
            None => Duration::from_secs(0),
        }
    }

    pub fn connectivity_monitor_config(&self) -> Option<&ConnectivityMonitorConfig> {
        self.config_file.connectivity_monitor.as_ref()
    }

    pub fn session_configs(&self) -> Option<&Vec<SessionConfig>> {
        self.config_file.sessions.as_ref()
    }

    pub fn statsd_server_enabled(&self) -> bool {
        self.config_file.metrics.statsd_server.is_some()
    }

    pub fn statsd_server_address(&self) -> Result<SocketAddr> {
        match &self.config_file.metrics.statsd_server {
            Some(statsd_server_config) => Ok(statsd_server_config.bind_address),
            None => Err(eyre!("No StatsD server bind_address configured!")),
        }
    }

    // Returns true if Gauge metrics should be aggregated via
    // a running average rather than simply saving the most
    // recently reported value.
    //
    // Note: This config is only meant to be used for compatibility
    // with legacy implementations that sent Gauge StatsD metrics to
    // collectd which ultimately forwarded them to memfaultd where they
    // were averaged together. New implementations should use the Histogram
    // Metric type for Metrics where the desired aggregation is averaging.
    pub fn statsd_server_legacy_gauge_aggregation_enabled(&self) -> bool {
        match &self.config_file.metrics.statsd_server {
            // This config is irrelevant if the built-in StatsD server is enabled
            None => false,
            Some(statsd_server_config) => statsd_server_config
                .legacy_gauge_aggregation
                .unwrap_or(false),
        }
    }

    pub fn statsd_server_legacy_key_names_enabled(&self) -> bool {
        self.config_file
            .metrics
            .statsd_server
            .as_ref()
            .and_then(|server| server.legacy_key_names)
            .unwrap_or(false)
    }

    pub fn hrt_enabled(&self) -> bool {
        self.config_file.metrics.high_resolution_telemetry.enable
    }

    pub fn hrt_max_samples_per_min(&self) -> NonZeroU32 {
        self.config_file
            .metrics
            .high_resolution_telemetry
            .max_samples_per_minute
    }

    pub fn builtin_system_metric_collection_enabled(&self) -> bool {
        self.config_file.metrics.system_metric_collection.enable
    }

    pub fn system_metric_config(&self) -> SystemMetricConfig {
        self.config_file.metrics.system_metric_collection.clone()
    }

    pub fn log_extraction_config(&self) -> &LevelMappingConfig {
        &self.config_file.logs.level_mapping
    }

    /// Combines both fluentd_extra_attributes and logs.extra_attributes
    ///
    /// All duplicates will be removed.
    pub fn log_extra_attributes(&self) -> Vec<String> {
        let fluentd_extra_attr = &self.config_file.fluent_bit.extra_fluentd_attributes;
        let logs_extra_attr = &self.config_file.logs.extra_attributes;

        fluentd_extra_attr
            .iter()
            .chain(logs_extra_attr.iter())
            .dedup()
            .cloned()
            .collect()
    }

    /// Gets the max buffered lines configured.
    ///
    /// This prefers any user configured value for fluent-bit to maintain
    /// backwards compatibility.
    pub fn log_max_buffered_lines(&self) -> usize {
        let fluent_bit_max = self.config_file.fluent_bit.max_buffered_lines;
        let log_max = self.config_file.logs.max_buffered_lines;

        fluent_bit_max.unwrap_or(log_max)
    }

    pub fn linux_custom_trace_config(&self) -> LinuxCustomTraceConfig {
        self.config_file.custom_trace.unwrap_or_default()
    }

    pub fn linux_custom_trace_log_compression(&self) -> LinuxCustomTraceLogCompression {
        self.config_file
            .custom_trace
            .map(|config| config.log_compression)
            .unwrap_or(LinuxCustomTraceLogCompression::Gzip)
    }
}

#[cfg(test)]
impl Config {
    pub fn test_fixture() -> Self {
        Config {
            device_info: DeviceInfo::test_fixture(),
            config_file: MemfaultdConfig::test_fixture(),
            config_file_path: PathBuf::from("test_fixture.conf"),
            cached_device_config: Arc::new(RwLock::new(DiskBacked::from_path(&PathBuf::from(
                "/dev/null",
            )))),
        }
    }

    pub fn test_fixture_with_info_overrides(software_version: &str, software_type: &str) -> Self {
        Config {
            device_info: DeviceInfo::test_fixture_with_overrides(software_version, software_type),
            config_file: MemfaultdConfig::test_fixture(),
            config_file_path: PathBuf::from("test_fixture.conf"),
            cached_device_config: Arc::new(RwLock::new(DiskBacked::from_path(&PathBuf::from(
                "/dev/null",
            )))),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::{fs::create_dir_all, path::PathBuf};

    use rstest::{fixture, rstest};

    use crate::{
        config::{device_info::DeviceInfoValue, Config},
        mar::MarEntry,
        network::{
            DeviceConfigResponse, DeviceConfigResponseConfig, DeviceConfigResponseData,
            DeviceConfigResponseResolution, MockNetworkClient,
        },
        util::path::AbsolutePath,
    };

    #[test]
    fn tmp_dir_defaults_to_persist_dir() {
        let config = Config::test_fixture();

        assert_eq!(config.tmp_dir(), config.config_file.persist_dir);
    }

    #[test]
    fn tmp_folder_set() {
        let mut config = Config::test_fixture();
        let abs_path = PathBuf::from("/my/abs/path");
        config.config_file.tmp_dir = Some(AbsolutePath::try_from(abs_path.clone()).unwrap());

        assert_eq!(config.tmp_dir(), abs_path);
    }

    #[test]
    fn test_info_overrides_file() {
        let config =
            Config::test_fixture_with_info_overrides("1.0.0-overridden", "overridden-type");

        assert_eq!(config.software_version(), "1.0.0-overridden");
        assert_eq!(config.software_type(), "overridden-type");
    }

    #[rstest]
    fn generate_mar_device_config_confirmation_when_needed(mut fixture: Fixture) {
        fixture
            .client
            .expect_fetch_device_config()
            .return_once(|| Ok(DEVICE_CONFIG_SAMPLE));
        fixture
            .config
            .refresh_device_config(&fixture.client)
            .unwrap();

        assert_eq!(fixture.count_mar_entries(), 1);
    }

    #[rstest]
    fn do_not_generate_mar_device_config_if_not_needed(mut fixture: Fixture) {
        let mut device_config = DEVICE_CONFIG_SAMPLE;
        device_config.data.completed = Some(device_config.data.revision);

        fixture
            .client
            .expect_fetch_device_config()
            .return_once(move || Ok(device_config));
        fixture
            .config
            .refresh_device_config(&fixture.client)
            .unwrap();

        assert_eq!(fixture.count_mar_entries(), 0);
    }

    #[rstest]
    #[case(Some(DeviceInfoValue::Configured("1.0.0".into())), None, "1.0.0")]
    #[case(Some(DeviceInfoValue::Default("1.0.0".into())), None, "1.0.0")]
    #[case(Some(DeviceInfoValue::Configured("1.0.0".into())), Some("2.0.0"), "1.0.0")]
    #[case(Some(DeviceInfoValue::Default("1.0.0".into())), Some("2.0.0"), "2.0.0")]
    #[case(None, Some("2.0.0"), "2.0.0")]
    #[case(None, None, FALLBACK_SOFTWARE_VERSION)]
    fn software_version_precedence(
        #[case] device_info_swv: Option<DeviceInfoValue>,
        #[case] config_swv: Option<&str>,
        #[case] expected: &str,
    ) {
        let mut config = Config::test_fixture();
        config.device_info.software_version = device_info_swv;
        config.config_file.software_version = config_swv.map(String::from);

        assert_eq!(config.software_version(), expected);
    }

    #[rstest]
    #[case(Some(DeviceInfoValue::Configured("test".into())), None, "test")]
    #[case(Some(DeviceInfoValue::Default("test".into())), None, "test")]
    #[case(Some(DeviceInfoValue::Configured("test".into())), Some("prod"), "test")]
    #[case(Some(DeviceInfoValue::Default("test".into())), Some("prod"), "prod")]
    #[case(None, Some("prod"), "prod")]
    #[case(None, None, FALLBACK_SOFTWARE_TYPE)]
    fn software_type_precedence(
        #[case] device_info_swv: Option<DeviceInfoValue>,
        #[case] config_swv: Option<&str>,
        #[case] expected: &str,
    ) {
        let mut config = Config::test_fixture();
        config.device_info.software_type = device_info_swv;
        config.config_file.software_type = config_swv.map(String::from);

        assert_eq!(config.software_type(), expected);
    }

    #[rstest]
    #[case::both_set(
        vec!["fluentd"],
        vec!["logs"],
        vec!["fluentd", "logs"])]
    #[case::fluentd_set(vec!["fluentd"], vec![], vec!["fluentd"])]
    #[case::logs_set(vec![], vec!["logs"], vec!["logs"])]
    #[case::neither_set(vec![], vec![], vec![])]
    #[case::duplicates(
        vec!["fluentd", "logs"],
        vec!["logs"],
        vec!["fluentd", "logs"])]
    fn log_attr_merge(
        #[case] fluentd_attr: Vec<&str>,
        #[case] log_attr: Vec<&str>,
        #[case] expected_attr: Vec<&str>,
    ) {
        let mut config = Config::test_fixture();
        config.config_file.fluent_bit.extra_fluentd_attributes =
            fluentd_attr.into_iter().map(|s| s.to_string()).collect();
        config.config_file.logs.extra_attributes =
            log_attr.into_iter().map(|s| s.to_string()).collect();

        let mut actual_attr = config.log_extra_attributes();
        actual_attr.sort();
        assert_eq!(actual_attr, expected_attr);
    }

    #[rstest]
    #[case(Some(42), 25, 42)]
    #[case(None, 25, 25)]
    fn log_max_buffered_precedence(
        #[case] fluent_bit_max: Option<usize>,
        #[case] log_max: usize,
        #[case] expected: usize,
    ) {
        let mut config = Config::test_fixture();
        config.config_file.fluent_bit.max_buffered_lines = fluent_bit_max;
        config.config_file.logs.max_buffered_lines = log_max;

        let actual_max = config.log_max_buffered_lines();
        assert_eq!(actual_max, expected);
    }

    #[rstest]
    #[case(Some(true), true)]
    #[case(None, false)]
    #[case(Some(false), false)]
    fn legacy_key_names(#[case] legacy_key_names_enabled: Option<bool>, #[case] expected: bool) {
        let mut config = Config::test_fixture();
        config
            .config_file
            .metrics
            .statsd_server
            .as_mut()
            .unwrap()
            .legacy_key_names = legacy_key_names_enabled;

        assert_eq!(config.statsd_server_legacy_key_names_enabled(), expected);
    }

    #[rstest]
    #[case(
        Some(crate::config::LinuxCustomTraceLogCompression::Gzip),
        crate::config::LinuxCustomTraceLogCompression::Gzip
    )]
    #[case(
        Some(crate::config::LinuxCustomTraceLogCompression::Zlib),
        crate::config::LinuxCustomTraceLogCompression::Zlib
    )]
    #[case(
        Some(crate::config::LinuxCustomTraceLogCompression::None),
        crate::config::LinuxCustomTraceLogCompression::None
    )]
    #[case(None, crate::config::LinuxCustomTraceLogCompression::Gzip)] // Default to Gzip when not specified
    fn linux_custom_trace_log_compression(
        #[case] compression_type: Option<LinuxCustomTraceLogCompression>,
        #[case] expected: crate::config::LinuxCustomTraceLogCompression,
    ) {
        let mut config = Config::test_fixture();
        config.config_file.custom_trace =
            compression_type.map(|log_compression| crate::config::LinuxCustomTraceConfig {
                log_compression,
                rate_limit_count: 5,
                rate_limit_duration: Duration::from_secs(3600),
            });

        assert_eq!(config.linux_custom_trace_log_compression(), expected);
    }

    #[test]
    fn linux_custom_trace_config_is_optional() {
        let mut config = Config::test_fixture();

        // Test that config without linux_custom_trace section works
        config.config_file.custom_trace = None;
        assert_eq!(
            config.linux_custom_trace_log_compression(),
            LinuxCustomTraceLogCompression::Gzip
        );
    }

    #[test]
    fn linux_custom_trace_config_with_gzip_compression() {
        let mut config = Config::test_fixture();
        config.config_file.custom_trace = Some(LinuxCustomTraceConfig {
            log_compression: LinuxCustomTraceLogCompression::Gzip,
            rate_limit_count: 5,
            rate_limit_duration: Duration::from_secs(3600),
        });

        assert_eq!(
            config.linux_custom_trace_log_compression(),
            LinuxCustomTraceLogCompression::Gzip
        );
    }

    #[test]
    fn linux_custom_trace_config_with_zlib_compression() {
        let mut config = Config::test_fixture();
        config.config_file.custom_trace = Some(LinuxCustomTraceConfig {
            log_compression: LinuxCustomTraceLogCompression::Zlib,
            rate_limit_count: 5,
            rate_limit_duration: Duration::from_secs(3600),
        });

        assert_eq!(
            config.linux_custom_trace_log_compression(),
            LinuxCustomTraceLogCompression::Zlib
        );
    }

    #[test]
    fn linux_custom_trace_config_with_no_compression() {
        let mut config = Config::test_fixture();
        config.config_file.custom_trace = Some(LinuxCustomTraceConfig {
            log_compression: LinuxCustomTraceLogCompression::None,
            rate_limit_count: 5,
            rate_limit_duration: Duration::from_secs(3600),
        });

        assert_eq!(
            config.linux_custom_trace_log_compression(),
            LinuxCustomTraceLogCompression::None
        );
    }

    #[rstest]
    #[case(None, LinuxCustomTraceLogCompression::Gzip)]
    #[case(
        Some(LinuxCustomTraceLogCompression::Gzip),
        LinuxCustomTraceLogCompression::Gzip
    )]
    #[case(
        Some(LinuxCustomTraceLogCompression::Zlib),
        LinuxCustomTraceLogCompression::Zlib
    )]
    #[case(
        Some(LinuxCustomTraceLogCompression::None),
        LinuxCustomTraceLogCompression::None
    )]
    fn linux_custom_trace_config_defaults_and_overrides(
        #[case] compression_setting: Option<LinuxCustomTraceLogCompression>,
        #[case] expected: LinuxCustomTraceLogCompression,
    ) {
        let mut config = Config::test_fixture();

        config.config_file.custom_trace =
            compression_setting.map(|log_compression| LinuxCustomTraceConfig {
                log_compression,
                rate_limit_count: 5,
                rate_limit_duration: Duration::from_secs(3600),
            });

        assert_eq!(config.linux_custom_trace_log_compression(), expected);
    }

    #[test]
    fn linux_custom_trace_config_serialization_roundtrip() {
        use serde_json;

        let original_config = LinuxCustomTraceConfig {
            log_compression: LinuxCustomTraceLogCompression::Gzip,
            rate_limit_count: 5,
            rate_limit_duration: Duration::from_secs(3600),
        };

        let json = serde_json::to_string(&original_config).unwrap();
        let deserialized_config: LinuxCustomTraceConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(
            original_config.log_compression,
            deserialized_config.log_compression
        );

        // Test all compression types
        let compression_types = vec![
            LinuxCustomTraceLogCompression::Gzip,
            LinuxCustomTraceLogCompression::Zlib,
            LinuxCustomTraceLogCompression::None,
        ];

        for compression_type in compression_types {
            let config = LinuxCustomTraceConfig {
                log_compression: compression_type,
                rate_limit_count: 5,
                rate_limit_duration: Duration::from_secs(3600),
            };
            let json = serde_json::to_string(&config).unwrap();
            let deserialized: LinuxCustomTraceConfig = serde_json::from_str(&json).unwrap();
            assert_eq!(config, deserialized);
        }
    }

    struct Fixture {
        config: Config,
        _tmp_dir: tempfile::TempDir,
        client: MockNetworkClient,
    }

    #[fixture]
    fn fixture() -> Fixture {
        Fixture::new()
    }

    impl Fixture {
        fn new() -> Self {
            let tmp_dir = tempfile::tempdir().unwrap();
            let mut config = Config::test_fixture();
            config.config_file.persist_dir = tmp_dir.path().to_path_buf().try_into().unwrap();
            create_dir_all(config.mar_tmp_staging_path()).unwrap();
            Self {
                config,
                _tmp_dir: tmp_dir,
                client: MockNetworkClient::new(),
            }
        }

        fn count_mar_entries(self) -> usize {
            MarEntry::iterate_from_container(&self.config.mar_tmp_staging_path())
                .unwrap()
                .count()
        }
    }

    #[rstest]
    #[case(Some(true))]
    #[case(Some(false))]
    #[case(None)]
    fn mar_logs_clean_type(#[case] is_persisted: Option<bool>) {
        let mut config = Config::test_fixture();

        let persist_storage = is_persisted.map(|logs| PersistStorageConfig {
            min_headroom: 1,
            max_usage: 2,
            min_inodes: 3,
            reboots: false,
            coredumps: false,
            metrics: false,
            logs,
        });
        config.config_file.persist_storage = persist_storage;

        let clean_type = is_persisted
            .and_then(|coredumps| coredumps.then_some(MarStagingCleanType::Persist))
            .unwrap_or(MarStagingCleanType::Tmp);

        assert_eq!(config.mar_logs_clean_type(), clean_type);
    }

    const DEVICE_CONFIG_SAMPLE: DeviceConfigResponse = DeviceConfigResponse {
        data: DeviceConfigResponseData {
            completed: None,
            revision: 42,
            config: DeviceConfigResponseConfig {
                memfault: crate::network::DeviceConfigResponseMemfault {
                    sampling: crate::network::DeviceConfigResponseSampling {
                        debugging_resolution: DeviceConfigResponseResolution::High,
                        logging_resolution: DeviceConfigResponseResolution::High,
                        monitoring_resolution: DeviceConfigResponseResolution::High,
                    },
                    data_upload_start_date: None,
                    memfaultd: None,
                },
            },
        },
    };
}