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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273// SPDX-FileCopyrightText: © 2024 Jeffrey C. Ollie <jeff@ocjtech.us>//// SPDX-License-Identifier: MIT
const Message = @This();
const std = @import("std");const assert = std.debug.assert;
const ControlMessage = @import("cmsghdr.zig").ControlMessage;const Logger = @import("Logger.zig");const constants = @import("constants.zig");const Facility = constants.Facility;const Priority = constants.Priority;const MFD = @import("MFD.zig");
const linux = std.os.linux;const F = linux.F;const fd_t = linux.fd_t;const SCM = linux.SCM;const SOL = linux.SOL;
logger: *const Logger,memfd: fd_t,
pub fn init(logger: *const Logger) error{MemFDCreationFailed}!Message { var task = logger.io.async(_init, .{logger}); errdefer cancel: { const msg = task.cancel(logger.io) catch break :cancel; msg.cancel(); } return try task.await(logger.io);}
fn _init(logger: *const Logger) error{MemFDCreationFailed}!Message { const memfd: fd_t = memfd: { const rc = linux.memfd_create( "journalz", MFD.CLOEXEC | MFD.ALLOW_SEALING | MFD.NOEXEC_SEAL, ); switch (linux.errno(rc)) { .SUCCESS => break :memfd @intCast(rc), else => return error.MemFDCreationFailed, } };
return .{ .logger = logger, .memfd = memfd, };}
pub fn writer(self: *const Message, buf: []u8) Writer { return .init(self, buf);}
pub const Writer = struct { pub const Error = error{WriteFailed};
interface: std.Io.Writer, message: *const Message,
pub fn init(message: *const Message, buf: []u8) Writer { return .{ .interface = .{ .buffer = buf, .vtable = &.{ .drain = VTable.drain, .flush = VTable.flush, }, }, .message = message, }; }
pub fn print(self: *Writer, key: []const u8, comptime fmt: []const u8, args: anytype) Error!void { assert(isValidKey(key));
var counter: std.Io.Writer.Discarding = .init(&.{}); try counter.writer.print(fmt, args);
try self.interface.writeAll(key); try self.interface.writeByte('\n'); try self.interface.writeInt(u64, counter.fullCount(), .little); try self.interface.print(fmt, args); try self.interface.writeByte('\n'); }
pub fn writeAll(self: *Writer, key: []const u8, data: []const u8) Error!void { assert(isValidKey(key));
try self.interface.writeAll(key); try self.interface.writeByte('\n'); try self.interface.writeInt(u64, data.len, .little); try self.interface.writeAll(data); try self.interface.writeByte('\n'); }
pub fn writeErrno(self: *Writer, errno: i32) Error!void { try self.print("ERRNO", "{d}", .{errno}); } pub fn writeMessageID(self: *Writer, value: u128) Error!void { try self.print("MESSAGE_ID", "{x:0>16}", .{value}); }
pub fn writeSyslogIdentifier(self: *Writer, value: []const u8) Error!void { try self.writeAll("SYSLOG_IDENTIFIER", value); }
pub fn writeFacility(self: *Writer, value: Facility) Error!void { try self.print("SYSLOG_FACILITY", "{d}", .{@intFromEnum(value)}); }
pub fn writePriority(self: *Writer, value: Priority) Error!void { try self.print("PRIORITY", "{d}", .{@intFromEnum(value)}); }
pub fn writeSrc(self: *Writer, loc: std.builtin.SourceLocation) Error!void { try self.writeAll("CODE_MODULE", loc.module); try self.writeAll("CODE_FILE", loc.file); try self.writeAll("CODE_FUNC", loc.fn_name); try self.print("CODE_LINE", "{d}", .{loc.line}); try self.print("CODE_COLUMN", "{d}", .{loc.column}); }
pub fn flush(self: *Writer) Error!void { try self.interface.flush(); }
// //
const VTable = struct { fn drain(io_writer: *std.Io.Writer, data: []const []const u8, splat: usize) Error!usize { const self: *Writer = @fieldParentPtr("interface", io_writer);
var count: usize = 0;
for (data[0 .. data.len - 1]) |chunk| { self._write(chunk, &count) catch |err| switch (err) { error.ShortWrite => return count, else => |e| return e, }; }
for (0..splat) |_| { self._write(data[data.len - 1], &count) catch |err| switch (err) { error.ShortWrite => return count, else => |e| return e, }; }
return count; }
fn flush(io_writer: *std.Io.Writer) Error!void { const self: *Writer = @fieldParentPtr("interface", io_writer); try self._flush(); } };
fn _write(self: *Writer, chunk: []const u8, count: *usize) error{ ShortWrite, WriteFailed }!void { if (self.interface.buffer.len == 0) { const len = try self.message.write(chunk); count.* += len; if (len < chunk.len) return error.ShortWrite; return; }
var index: usize = 0;
while (index < chunk.len) { const size = @min( self.interface.buffer.len - self.interface.end, chunk.len - index, );
@memcpy( self.interface.buffer[self.interface.end .. self.interface.end + size], chunk[index .. index + size], );
self.interface.end += size; index += size; count.* += size;
if (self.interface.buffer.len == self.interface.end) try self._flush(); } }
fn _flush(self: *Writer) error{WriteFailed}!void { if (self.interface.buffer.len == 0) return; _ = try self.message.write(self.interface.buffer[0..self.interface.end]); self.interface.end = 0; }};
fn write(self: *const Message, data: []const u8) error{WriteFailed}!usize { const rc = linux.write(self.memfd, data.ptr, data.len); switch (linux.errno(rc)) { .SUCCESS => return rc, else => return error.WriteFailed, }}
inline fn isValidKey(key: []const u8) bool { return std.mem.findAny(u8, key, "=\n\x00") == null;}
pub fn send(self: *const Message) error{ SealFailed, SendFailed }!void { const io = self.logger.io; var task = io.async(_send, .{self}); errdefer task.cancel(io) catch {}; try task.await(io);}
fn _send(self: *const Message) error{ SealFailed, SendFailed }!void { { const rc = linux.fcntl( self.memfd, F.ADD_SEALS, F.SEAL_SEAL | F.SEAL_SHRINK | F.SEAL_GROW | F.SEAL_WRITE | F.SEAL_FUTURE_WRITE | F.SEAL_EXEC, ); switch (linux.errno(rc)) { .SUCCESS => {}, else => return error.SealFailed, } }
var control: ControlMessage(fd_t) = .init( SOL.SOCKET, SCM.RIGHTS, self.memfd, );
var msghdr = linux.msghdr_const{ .name = @ptrCast(&self.logger.path), .namelen = @sizeOf(@TypeOf(self.logger.path)), .iov = undefined, .iovlen = 0, .control = control.ptr(), .controllen = control.len(), .flags = 0, };
{ const rc = linux.sendmsg( self.logger.socket, &msghdr, 0, );
switch (linux.errno(rc)) { .SUCCESS => {}, else => return error.SendFailed, } }
errdefer comptime unreachable;
_ = linux.close(self.memfd);}
pub fn cancel(self: *const Message) void { const io = self.logger.io; var task = io.async(_cancel, .{self}); task.await(io);}
fn _cancel(self: *const Message) void { _ = linux.close(self.memfd);}