systemd-journal-sdk 0.7.2

Pure-Rust systemd journal reader and writer SDK
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
use super::*;
use journal_core::file::{JournalFileOptions, JournalWriter, MmapMut};
use journal_core::repository::File as RepoFile;
use journal_core::seal::SealOptions;
use serde_json::Value;
use std::path::{Path, PathBuf};

struct TempPath(PathBuf);

impl Drop for TempPath {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.0);
    }
}

#[test]
fn parse_match_bytes_accepts_binary_values() {
    let data = b"MESSAGE=\xff\x00binary";
    assert_eq!(parse_match_bytes(data).unwrap(), data);
}

#[test]
fn parse_match_bytes_rejects_invalid_field_names() {
    assert!(parse_match_bytes(b"lower=value").is_err());
    assert!(parse_match_bytes(b"1FIELD=value").is_err());
    assert!(parse_match_bytes(b"=value").is_err());
}

#[test]
fn json_entry_includes_monotonic_timestamp_and_preserves_utf8() {
    let mut fields = HashMap::new();
    fields.insert("MESSAGE".to_string(), "héllo".as_bytes().to_vec());

    let mut field_values = HashMap::new();
    field_values.insert("MESSAGE".to_string(), vec!["héllo".as_bytes().to_vec()]);
    field_values.insert("BINARY".to_string(), vec![vec![0xff, 0x00]]);
    field_values.insert("CONTROL".to_string(), vec![b"abc\x07def".to_vec()]);

    let entry = Entry {
        fields,
        field_values,
        payloads: Vec::new(),
        seqnum: 7,
        realtime: 100,
        monotonic: 42,
        boot_id: [1; 16],
        cursor: "s=1;j=1;c=64;n=7".to_string(),
    };

    let Value::Object(json) = json_entry(&entry) else {
        panic!("entry JSON should be an object");
    };

    assert_eq!(
        json.get("__MONOTONIC_TIMESTAMP"),
        Some(&Value::String("42".to_string()))
    );
    assert_eq!(
        json.get("MESSAGE"),
        Some(&Value::String("héllo".to_string()))
    );
    assert_eq!(
        json.get("BINARY"),
        Some(&Value::Array(vec![Value::from(255), Value::from(0)]))
    );
    assert_eq!(
        json.get("CONTROL"),
        Some(&Value::Array(vec![
            Value::from(97),
            Value::from(98),
            Value::from(99),
            Value::from(7),
            Value::from(100),
            Value::from(101),
            Value::from(102),
        ]))
    );
}

#[test]
fn no_rtc_fixtures_drain_without_tail_object_errors() {
    let fixture_dir = repo_root().join("fixtures/systemd/test-data/no-rtc");
    let mut total_entries = 0usize;
    for entry in std::fs::read_dir(&fixture_dir).expect("fixture directory exists") {
        let path = entry.expect("fixture directory entry").path();
        if !is_journal_file_name(&path) {
            continue;
        }
        let mut reader = FileReader::open(&path).expect("open journal fixture");
        let mut file_entries = 0usize;
        while reader.next().expect("fixture drains cleanly") {
            reader.get_entry().expect("entry is readable");
            file_entries += 1;
        }
        assert!(
            file_entries > 0,
            "expected at least one readable entry in {}",
            path.display()
        );
        total_entries += file_entries;
    }
    assert_eq!(total_entries, 10757);
}

fn repo_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../../..")
        .canonicalize()
        .expect("repo root")
}

fn test_uuid(n: u8) -> uuid::Uuid {
    let mut bytes = [0u8; 16];
    bytes[15] = n;
    uuid::Uuid::from_bytes(bytes)
}

fn test_seal_opts() -> SealOptions {
    SealOptions::new([0u8; 12], 1_000_000, 1_000_000)
}

fn create_facade_test_writer(path: &Path) -> (JournalFile<MmapMut>, JournalWriter) {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).expect("create journal parent");
    }
    let repo_file = RepoFile::from_path(path)
        .unwrap_or_else(|| panic!("test journal path should parse: {}", path.display()));
    let mut journal_file = JournalFile::<MmapMut>::create(
        &repo_file,
        JournalFileOptions::new(test_uuid(1), test_uuid(2), test_uuid(3)),
    )
    .expect("create journal");
    let writer = JournalWriter::new(&mut journal_file, 1, test_uuid(4)).expect("create writer");
    (journal_file, writer)
}

fn create_facade_compressed_test_writer(path: &Path) -> (JournalFile<MmapMut>, JournalWriter) {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).expect("create journal parent");
    }
    let repo_file = RepoFile::from_path(path)
        .unwrap_or_else(|| panic!("test journal path should parse: {}", path.display()));
    let mut journal_file = JournalFile::<MmapMut>::create(
        &repo_file,
        JournalFileOptions::new(test_uuid(1), test_uuid(2), test_uuid(3))
            .with_compression(Compression::Zstd)
            .with_compress_threshold(8),
    )
    .expect("create compressed journal");
    let writer = JournalWriter::new_with_compression(
        &mut journal_file,
        1,
        test_uuid(4),
        Compression::Zstd,
        8,
    )
    .expect("create compressed writer");
    (journal_file, writer)
}

fn write_facade_test_journal(path: &Path) {
    let (mut journal_file, mut writer) = create_facade_test_writer(path);
    writer
        .add_entry(
            &mut journal_file,
            &[
                b"MESSAGE=first".as_slice(),
                b"REPEAT=one".as_slice(),
                b"REPEAT=two".as_slice(),
                b"BIN=\x00\xff".as_slice(),
            ],
            1000,
            11,
        )
        .expect("write first entry");
    writer
        .add_entry(
            &mut journal_file,
            &[b"MESSAGE=second".as_slice(), b"REPEAT=three".as_slice()],
            1001,
            12,
        )
        .expect("write second entry");
    journal_file.sync().expect("sync journal");
}

fn write_single_entry_journal(
    path: &Path,
    seqnum: u64,
    realtime: u64,
    monotonic: u64,
    payload: &[u8],
) {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).expect("create journal parent");
    }
    let repo_file = RepoFile::from_path(path)
        .unwrap_or_else(|| panic!("test journal path should parse: {}", path.display()));
    let mut journal_file = JournalFile::<MmapMut>::create(
        &repo_file,
        JournalFileOptions::new(test_uuid(1), test_uuid(2), test_uuid(3)),
    )
    .expect("create journal");
    let mut writer =
        JournalWriter::new(&mut journal_file, seqnum, test_uuid(4)).expect("create writer");
    writer
        .add_entry(&mut journal_file, &[payload], realtime, monotonic)
        .expect("write entry");
    journal_file.sync().expect("sync journal");
}

fn write_facade_single_message_journal(path: &Path, message: &[u8], realtime: u64) {
    let (mut journal_file, mut writer) = create_facade_test_writer(path);
    let payload = [b"MESSAGE=".as_slice(), message].concat();
    writer
        .add_entry(&mut journal_file, &[payload.as_slice()], realtime, 21)
        .expect("write single message");
    journal_file.sync().expect("sync journal");
}

fn journalctl_verify_fails_if_available(path: &Path, expected_text: &str) {
    let available = std::process::Command::new("journalctl")
        .arg("--version")
        .output()
        .map(|output| output.status.success())
        .unwrap_or(false);
    if !available {
        return;
    }

    let output = std::process::Command::new("journalctl")
        .arg("--verify")
        .arg("--file")
        .arg(path)
        .output()
        .expect("run journalctl --verify");
    assert!(
        !output.status.success(),
        "journalctl --verify unexpectedly passed for {}",
        path.display()
    );
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    )
    .to_lowercase();
    assert!(
        combined.contains(&expected_text.to_lowercase()),
        "journalctl --verify output missing {expected_text:?}: {combined}"
    );
}

#[test]
fn raw_writer_backward_monotonic_pass_through_fails_verification() {
    let dir = tempfile::tempdir().expect("create temp dir");
    let path = dir.path().join("journals/raw-backward-monotonic.journal");
    let (mut journal_file, mut writer) = create_facade_test_writer(&path);
    writer
        .add_entry(
            &mut journal_file,
            &[b"MESSAGE=raw monotonic first".as_slice()],
            1_700_003_000_000_000,
            10,
        )
        .expect("write first entry");
    writer
        .add_entry(
            &mut journal_file,
            &[b"MESSAGE=raw monotonic second".as_slice()],
            1_700_003_000_000_001,
            5,
        )
        .expect("write second entry");
    journal_file.sync().expect("sync journal");

    let err = verify_file(&path)
        .expect_err("expected same-boot backward monotonic timestamps to fail verification");
    let msg = err.to_string().to_lowercase();
    assert!(
        msg.contains("monotonic"),
        "expected monotonic verification failure, got: {err}"
    );
    journalctl_verify_fails_if_available(&path, "timestamp out of synchronization");
}

#[test]
fn raw_writer_explicit_zero_monotonic_pass_through() {
    let dir = tempfile::tempdir().expect("create temp dir");
    let path = dir.path().join("journals/raw-zero-monotonic.journal");
    let (mut journal_file, mut writer) = create_facade_test_writer(&path);
    writer
        .add_entry(
            &mut journal_file,
            &[b"MESSAGE=raw zero monotonic".as_slice()],
            1_700_003_000_100_000,
            0,
        )
        .expect("write entry");
    journal_file.sync().expect("sync journal");
    verify_file(&path).expect("zero monotonic first entry should verify");

    let mut journal =
        SdJournalOpenFiles(&[path.to_str().expect("utf8 path")], 0).expect("open files");
    assert_eq!(SdJournalNext(&mut journal).expect("next"), 1);
    let (monotonic, _boot_id) = SdJournalGetMonotonicUsec(&mut journal).expect("monotonic");
    assert_eq!(monotonic, 0);
}

#[test]
fn snapshot_reader_handles_final_partial_mmap_window() {
    let dir = tempfile::tempdir().expect("create temp dir");
    let path = dir.path().join("journals/system.journal");
    write_facade_test_journal(&path);

    let options = ReaderOptions::snapshot().with_window_size(32 * 1024 * 1024);
    let mut reader = FileReader::open_with_options(&path, options).expect("open snapshot reader");
    assert!(reader.next().expect("first entry"));

    let mut payloads = Vec::new();
    reader
        .visit_entry_payloads(|payload| {
            payloads.push(payload.to_vec());
            Ok(())
        })
        .expect("visit current entry payloads");
    assert!(payloads.iter().any(|payload| payload == b"MESSAGE=first"));
    assert!(payloads.iter().any(|payload| payload == b"BIN=\x00\xff"));
}

#[test]
fn snapshot_header_is_fixed_while_live_header_refreshes() {
    let dir = tempfile::tempdir().expect("create temp dir");
    let path = dir.path().join("journals/system.journal");
    let (mut journal_file, mut writer) = create_facade_test_writer(&path);

    writer
        .add_entry(
            &mut journal_file,
            &[b"MESSAGE=first".as_slice()],
            1_700_005_000_000_000,
            10,
        )
        .expect("write first entry");
    journal_file.sync().expect("sync first entry");

    let snapshot_reader =
        FileReader::open_with_options(&path, ReaderOptions::snapshot()).expect("open snapshot");
    let live_reader =
        FileReader::open_with_options(&path, ReaderOptions::live()).expect("open live");

    assert_eq!(snapshot_reader.header().tail_entry_seqnum, 1);
    assert_eq!(live_reader.header().tail_entry_seqnum, 1);

    writer
        .add_entry(
            &mut journal_file,
            &[b"MESSAGE=second".as_slice()],
            1_700_005_000_000_001,
            11,
        )
        .expect("write second entry");
    journal_file.sync().expect("sync second entry");

    assert_eq!(
        snapshot_reader.header().tail_entry_seqnum,
        1,
        "snapshot header should remain fixed at open time"
    );
    assert_eq!(
        live_reader.header().tail_entry_seqnum,
        2,
        "live header should refresh from the mapped file"
    );
}

#[test]
fn default_reader_options_use_production_window_size() {
    let options = ReaderOptions::default();
    assert_eq!(options.bounds, ReaderBounds::Live);
    assert_eq!(options.mmap_strategy, ExperimentalMmapStrategy::Windowed);
    assert_eq!(options.window_size, DEFAULT_READER_WINDOW_SIZE);
    assert_eq!(options.window_size, 32 * 1024 * 1024);
}

#[test]
fn reader_options_with_bounds_sets_bounds() {
    let options = ReaderOptions::default().with_bounds(ReaderBounds::Snapshot);
    assert_eq!(options.bounds, ReaderBounds::Snapshot);
}

#[test]
fn directory_reader_uses_sequential_path_for_non_overlapping_files() {
    let dir = tempfile::tempdir().expect("create temp dir");
    let first_path = dir.path().join("journals/first.journal");
    let second_path = dir.path().join("journals/second.journal");

    write_single_entry_journal(&first_path, 1, 1_700_004_000_000_000, 10, b"MESSAGE=first");
    write_single_entry_journal(
        &second_path,
        2,
        1_700_004_000_000_001,
        20,
        b"MESSAGE=second",
    );

    let mut reader = DirectoryReader::open_files([&first_path, &second_path]).expect("open files");
    assert!(
        reader.non_overlapping,
        "test files should qualify for sequential directory reads"
    );

    reader.seek_head();
    assert!(reader.next().expect("first entry"));
    assert_eq!(
        reader.get_realtime_usec().expect("first realtime"),
        1_700_004_000_000_000
    );
    assert!(reader.next().expect("second entry"));
    assert_eq!(
        reader.get_realtime_usec().expect("second realtime"),
        1_700_004_000_000_001
    );
    assert!(!reader.next().expect("end"));

    reader.seek_tail();
    assert!(reader.previous().expect("tail entry"));
    assert_eq!(
        reader.get_realtime_usec().expect("tail realtime"),
        1_700_004_000_000_001
    );
    assert!(reader.previous().expect("previous entry"));
    assert_eq!(
        reader.get_realtime_usec().expect("previous realtime"),
        1_700_004_000_000_000
    );
    assert!(!reader.previous().expect("start"));
}

mod facade;
mod verification;