Something went wrong. Try again.
A Zig library for writing structured log messages directly to the systemd journal over its native datagram socket.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374// SPDX-FileCopyrightText: © 2024 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
//! Tests for the wire format and for a whole message crossing a socket.//!//! Everything here runs against `testing.FakeJournal` rather than the//! machine's own journal, so the suite passes on a host with no systemd and//! inside a Nix build sandbox. What it cannot cover -- that journald itself//! accepts and indexes what is sent -- is covered by the NixOS virtual//! machine check in `tests/nixos`.
const std = @import("std");const testing = std.testing;const Allocator = std.mem.Allocator;
const Logger = @import("Logger.zig");const Message = @import("Message.zig");const constants = @import("constants.zig");const Facility = constants.Facility;const Priority = constants.Priority;const helper = @import("testing.zig");
const linux = std.os.linux;const F = linux.F;
/// A `FakeJournal` and a `Logger` pointed at it, in a directory that goes/// away with the test.const Fixture = struct { tmp: testing.TmpDir, path_buf: [64]u8, journal: helper.FakeJournal, logger: Logger,
fn init(self: *Fixture, identifier: ?[]const u8, facility: ?Facility) !void { self.tmp = testing.tmpDir(.{}); errdefer self.tmp.cleanup();
// A relative path, deliberately: `sun_path` is 108 bytes and the // absolute path of a cache directory is not guaranteed to fit. const path = try std.fmt.bufPrint( &self.path_buf, ".zig-cache/tmp/{s}/journal.sock", .{self.tmp.sub_path}, );
self.journal = try .init(path); errdefer self.journal.deinit();
self.logger = try .initPath(testing.io, identifier, facility, path); }
fn deinit(self: *Fixture) void { self.logger.deinit(); self.journal.deinit(); self.tmp.cleanup(); }};
/// The raw bytes a single field encodes to, with nothing else in the message.fn encodeOne(allocator: Allocator, logger: *const Logger, key: []const u8, value: []const u8) ![]const u8 { const msg: Message = try .init(logger); defer msg.cancel();
var buf: [256]u8 = undefined; var w = msg.writer(&buf); try w.writeAll(key, value); try w.flush();
return helper.readAll(allocator, msg.memfd);}
test "a field is its name, a newline, a little endian u64 length, the value and a newline" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit();
const payload = try encodeOne(testing.allocator, &fixture.logger, "MESSAGE", "hello"); defer testing.allocator.free(payload);
try testing.expectEqualSlices( u8, "MESSAGE\n" ++ [_]u8{ 5, 0, 0, 0, 0, 0, 0, 0 } ++ "hello\n", payload, );}
test "the length is a byte count, so a value holding newlines and NULs survives" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit();
const value = "one\ntwo\x00three\n"; const payload = try encodeOne(testing.allocator, &fixture.logger, "MESSAGE", value); defer testing.allocator.free(payload);
try testing.expectEqualSlices( u8, "MESSAGE\n" ++ [_]u8{ 14, 0, 0, 0, 0, 0, 0, 0 } ++ value ++ "\n", payload, );}
test "print formats the value and counts its bytes" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit();
const msg: Message = try .init(&fixture.logger); defer msg.cancel();
var buf: [256]u8 = undefined; var w = msg.writer(&buf); try w.print("COUNT", "{d} of {d}", .{ 7, 100 }); try w.flush();
const payload = try helper.readAll(testing.allocator, msg.memfd); defer testing.allocator.free(payload);
try testing.expectEqualSlices( u8, "COUNT\n" ++ [_]u8{ 8, 0, 0, 0, 0, 0, 0, 0 } ++ "7 of 100\n", payload, );}
test "a value larger than the writer's buffer is not truncated or reordered" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit();
const big: [10_000]u8 = @splat('x');
const msg: Message = try .init(&fixture.logger); defer msg.cancel();
// Deliberately far smaller than the value, so the write has to drain // through the buffer many times. var buf: [64]u8 = undefined; var w = msg.writer(&buf); try w.writeAll("MESSAGE", &big); try w.writeAll("AFTER", "tail"); try w.flush();
var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
const fields = try helper.decodeMemfd(arena.allocator(), msg.memfd); try testing.expectEqual(@as(usize, 2), fields.len); try testing.expectEqualStrings("MESSAGE", fields[0].key); try testing.expectEqualStrings(&big, fields[0].value); try testing.expectEqualStrings("AFTER", fields[1].key); try testing.expectEqualStrings("tail", fields[1].value);}
test "an unbuffered writer writes straight through" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit();
const msg: Message = try .init(&fixture.logger); defer msg.cancel();
var w = msg.writer(&.{}); try w.writeAll("MESSAGE", "unbuffered"); try w.flush();
const payload = try helper.readAll(testing.allocator, msg.memfd); defer testing.allocator.free(payload);
try testing.expectEqualSlices( u8, "MESSAGE\n" ++ [_]u8{ 10, 0, 0, 0, 0, 0, 0, 0 } ++ "unbuffered\n", payload, );}
test "writeSrc records where the message was logged" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit();
const msg: Message = try .init(&fixture.logger); defer msg.cancel();
var buf: [512]u8 = undefined; var w = msg.writer(&buf); const src = @src(); try w.writeSrc(src); try w.flush();
var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
const fields = try helper.decodeMemfd(arena.allocator(), msg.memfd); const entry: helper.Entry = .{ .arena = .init(testing.allocator), .fields = fields, .seals = 0 };
try testing.expectEqualStrings(src.file, entry.get("CODE_FILE").?); try testing.expectEqualStrings(src.fn_name, entry.get("CODE_FUNC").?);
var line_buf: [16]u8 = undefined; try testing.expectEqualStrings( try std.fmt.bufPrint(&line_buf, "{d}", .{src.line}), entry.get("CODE_LINE").?, );}
test "the logger's identifier, facility and priority lead the message" { var fixture: Fixture = undefined; try fixture.init("journalz-test", .DAEMON); defer fixture.deinit();
const msg = try fixture.logger.message(.WARNING); defer msg.cancel();
var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
const fields = try helper.decodeMemfd(arena.allocator(), msg.memfd); try testing.expectEqual(@as(usize, 3), fields.len); try testing.expectEqualStrings("SYSLOG_IDENTIFIER", fields[0].key); try testing.expectEqualStrings("journalz-test", fields[0].value); try testing.expectEqualStrings("SYSLOG_FACILITY", fields[1].key); try testing.expectEqualStrings("3", fields[1].value); try testing.expectEqualStrings("PRIORITY", fields[2].key); try testing.expectEqualStrings("4", fields[2].value);}
test "a logger with no identifier or facility writes neither field" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit();
const msg = try fixture.logger.message(.INFO); defer msg.cancel();
var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
const fields = try helper.decodeMemfd(arena.allocator(), msg.memfd); try testing.expectEqual(@as(usize, 1), fields.len); try testing.expectEqualStrings("PRIORITY", fields[0].key);}
test "a sent message arrives over the socket with its fields intact" { var fixture: Fixture = undefined; try fixture.init("journalz-test", .USER); defer fixture.deinit();
const msg = try fixture.logger.message(.INFO); errdefer msg.cancel();
var buf: [512]u8 = undefined; var w = msg.writer(&buf); try w.writeAll("MESSAGE", "over the wire"); try w.print("ANSWER", "{d}", .{42}); try w.flush();
try msg.send();
var entry = try fixture.journal.receive(testing.allocator); defer entry.deinit();
try testing.expectEqualStrings("journalz-test", entry.get("SYSLOG_IDENTIFIER").?); try testing.expectEqualStrings("1", entry.get("SYSLOG_FACILITY").?); try testing.expectEqualStrings("6", entry.get("PRIORITY").?); try testing.expectEqualStrings("over the wire", entry.get("MESSAGE").?); try testing.expectEqualStrings("42", entry.get("ANSWER").?);}
test "the payload is sealed against writing before it is handed over" { var fixture: Fixture = undefined; try fixture.init("journalz-test", .USER); defer fixture.deinit();
fixture.logger.info("sealed", .{});
var entry = try fixture.journal.receive(testing.allocator); defer entry.deinit();
// journald trusts the payload it is given; these are what stop the // sender changing it afterwards. for ([_]u32{ F.SEAL_SEAL, F.SEAL_SHRINK, F.SEAL_GROW, F.SEAL_WRITE, F.SEAL_FUTURE_WRITE, }) |seal| { try testing.expect(entry.seals & seal != 0); }}
test "each convenience method sends its own priority" { var fixture: Fixture = undefined; try fixture.init("journalz-test", .USER); defer fixture.deinit();
fixture.logger.err("an error", .{}); fixture.logger.warn("a warning", .{}); fixture.logger.info("a notice", .{}); fixture.logger.debug("a debug", .{});
const expected = [_]struct { priority: []const u8, message: []const u8 }{ .{ .priority = "3", .message = "an error" }, .{ .priority = "4", .message = "a warning" }, .{ .priority = "6", .message = "a notice" }, .{ .priority = "7", .message = "a debug" }, };
// A datagram socket preserves order, so these arrive as they were sent. for (expected) |want| { var entry = try fixture.journal.receive(testing.allocator); defer entry.deinit();
try testing.expectEqualStrings(want.priority, entry.get("PRIORITY").?); try testing.expectEqualStrings(want.message, entry.get("MESSAGE").?); }}
test "arguments are formatted into the MESSAGE field" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit();
fixture.logger.info("listening on port {d} as {s}", .{ 8080, "journalz" });
var entry = try fixture.journal.receive(testing.allocator); defer entry.deinit();
try testing.expectEqualStrings( "listening on port 8080 as journalz", entry.get("MESSAGE").?, );}
test "a cancelled message is never sent" { var fixture: Fixture = undefined; try fixture.init(null, null); defer fixture.deinit();
const msg = try fixture.logger.message(.INFO); msg.cancel();
fixture.logger.info("the only one", .{});
var entry = try fixture.journal.receive(testing.allocator); defer entry.deinit();
try testing.expectEqualStrings("the only one", entry.get("MESSAGE").?);}
test "initPath refuses a path too long for sun_path" { const long: [108]u8 = @splat('/'); try testing.expectError( error.PathTooLong, Logger.initPath(testing.io, null, null, &long), );}
test "facility and priority carry the syslog numbers" { // These cross the wire as decimal numbers and journald reads them as // syslog's, so the values are part of the protocol rather than an // internal detail. try testing.expectEqual(@as(u5, 0), @backingInt(Facility.KERN)); try testing.expectEqual(@as(u5, 11), @backingInt(Facility.FTP)); try testing.expectEqual(@as(u5, 16), @backingInt(Facility.LOCAL0)); try testing.expectEqual(@as(u5, 23), @backingInt(Facility.LOCAL7));
try testing.expectEqual(@as(u3, 0), @backingInt(Priority.EMERG)); try testing.expectEqual(@as(u3, 3), @backingInt(Priority.ERROR)); try testing.expectEqual(@as(u3, 7), @backingInt(Priority.DEBUG));}