Write a Lua decoder#
A decoder turns a snapshot of one map into the record that shirudo exports: the body of an OTLP log record, or a list of OTLP metrics. It is a Lua function that the BPF source declares and the build signs into the upatch, so it has the same signer as the program whose data it reads. This page shows how to declare one, write it, check it and run it.
Before you begin#
A upatch source with the map to export, and the layout of that map: the records its serializer writes, or its key and value types. Maps, arenas and serializers covers serializers.
The test VM or another target to run the decoder on, as Test a upatch on a target describes.
Familiarity with Lua 5.1, the language LuaJIT runs. LuaJIT and the decoder sandbox covers what shirudo uses it for.
Declare the decoder#
Decide on the signal. A log decoder returns a table that becomes the body of one log record per snapshot. A metric decoder returns OTLP metrics with names, units and data points of its choosing.
Include
decoder.haftervmlinux.hand declare a manifest in.rodata.kernel-obsdeclares this one, through a macro, forwatch_stat, a per-CPU array whose one value holds two__u64counters,checkedandmatched:#include "decoder.h" const struct decoder_manifest watch_stat_decoder SEC(".rodata") = { .magic = DECODER_MANIFEST_MAGIC, .version = UPATCH_DECODER_VERSION, .language = UPATCH_DECODER_LANG_LUA, .api_version = 1, .input_format = UPATCH_DECODER_INPUT_MAP_V1, .export_signal = UPATCH_DECODER_EXPORT_METRIC, .upatch = "kernel-obs", .map = "watch_stat", .source = "decoders/watch_stat.lua", .entrypoint = "decode", };
The builder finds manifests by their magic in the object’s
.rodata, so declare the manifestconst. It also passes over a manifest with an emptymap,sourceorentrypoint, a string field without a terminating NUL, or a zerolanguage,api_version,input_formatorexport_signal, without an error, so check the result as step 6 shows. Set the fields as follows:Field
Value
magic,versionThe constants shown. With any other value the builder does not recognize the manifest and builds the upatch without it.
language,api_,version input_format The constants shown. Any other value fails the build with
unsupported decoder ABI for '<upatch>/.<map>' export_signal UPATCH_orDECODER_ EXPORT_ LOG UPATCH_.DECODER_ EXPORT_ METRIC upatchEmpty, or the upatch name, which the field holds up to 63 characters. In a package that is the source’s base name. Leave it out for a longer name: one of 64 characters or more leaves no room for the terminating NUL. The decoder belongs to the upatch whose signed data carries it either way.
mapThe name of a map of the object, at most 15 characters. One decoder per map.
sourceThe Lua file, at most 63 characters, relative to the directory of the
.bpf.file, or to the current directory when the input is ac .bpf.. No leadingo /, no.or..component, no backslash. Not empty, at most 16 MiB.entrypointThe function to call, at most 31 characters.
Write the function#
Create the Lua file. The chunk either defines a global function with the entrypoint’s name, returns a function, or returns a table that has one under that name. shirudo calls it with one argument, the input table:
Field
Content
schema1upatch,mapthe upatch and map names
startTimeUnixNanowhen the upatch was loaded, as a decimal string
timeUnixNanothe time of the snapshot, as a decimal string
data.,name data.type the map’s name and type, such as
percpu_array data.,max_ entries data.n_ entries the map’s capacity and the entries read
data.,key_ size data.,value_ size data.n_ cpus sizes in bytes, and the number of CPUs for a per-CPU map
data.truncated whether the read stopped at the entry limit
data.,entries[i]. key_ hex .value_hex a directly read entry in hex. A per-CPU value holds one 8-byte aligned slot per CPU.
data.,serialized data.,serialized_ pages data.serialized_ bytes whether a serializer produced the snapshot, and its size
data.pages[i] one serializer page:
page_,index cursor,next_,cursor done,flags,chunks,bytesanddata_hex Lua numbers cannot hold a 64-bit value exactly, so shirudo passes timestamps as decimal strings, and these host functions exchange 64-bit values as decimal strings too:
Function
Returns
shirudo.page_ slots(page, size) the page’s payload cut into slots of
sizebytes, in order, respecting chunk boundariesshirudo.fixed_ records(pages, size) the slots of all pages, indexed by each page’s
cursorplus the slot’s positionslot:,u8(off) slot:,u16(off) slot:u32(off) a little-endian integer at
off, 0 when out of rangeslot:u64(off) a little-endian 64-bit value as a decimal string
slot:cstring(off, len) the bytes from
offup to the first NUL, at mostlenshirudo.,u64_ add(a, b) shirudo.u64_ sub(a, b) exact sum and difference of two decimal strings. The sum stops at the largest value and the difference at 0.
shirudo.hex_ u64(hex, off) the little-endian 64-bit value at byte
offof a hex string, as a decimal stringThe
watch_statdecoder adds up both counters over all CPUs and returns one monotonic sum with a data point for each:-- SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause -- Copyright (c) 2026 Authors of shirudo local function metric_point(input, value, outcome) return { startTimeUnixNano = input.startTimeUnixNano, timeUnixNano = input.timeUnixNano, asInt = value, attributes = { {key = "outcome", value = {stringValue = outcome}}, }, } end function decode(input) local data = input.data local entry = data.entries and data.entries[1] if not entry then error("missing watch counter entry") end local stride = math.ceil((data.value_size or 16) / 8) * 8 local cpus = data.n_cpus or 1 local checked, matched = "0", "0" for cpu = 0, cpus - 1 do local base = cpu * stride checked = shirudo.u64_add(checked, shirudo.hex_u64(entry.value_hex, base)) matched = shirudo.u64_add(matched, shirudo.hex_u64(entry.value_hex, base + 8)) end return { {name = "kernel_obs.watch_attempts", unit = "1", description = "socket-level destination checks against the watch list", sum = { aggregationTemporality = 2, isMonotonic = true, dataPoints = { metric_point(input, checked, "checked"), metric_point(input, matched, "matched"), }, }}, } end
Return the record. A log decoder returns a table. With
--otelit becomes the log record’s body: a table whose keys are 1 to n becomes an array, any other table a key-value list, a whole number up to 2^53 anintValueand any other number adoubleValue. A metric decoder returns an array of OTLPMetricobjects, exactly as they appear in themetricsarray of ascopeMetricsentry. A string or a key that is not valid UTF-8 is exported with U+FFFD in place of each bad byte and of each NUL.To turn a timestamp a serializer took on the boot-time clock into wall clock time, subtract its age from
timeUnixNano. Thekernel-obsdecoders do it with the time the serializer ran, which their page header carries:shirudo.u64_sub(input.timeUnixNano, shirudo.u64_sub(boot_now, ts))
The decoder runs in a restricted LuaJIT state:
It is loaded as source text. LuaJIT does not verify bytecode, so a precompiled chunk is refused.
The JIT compiler is off, so that the instruction count sees every instruction. One snapshot may take 1,000,000 virtual machine instructions, loading the chunk included, and 32 MiB of memory, and the result may nest 32 levels deep.
pcallcatches the error the limit raises, but from then on every instruction raises it again.io,os,package,require,debug,jit,ffi,dofile,loadfile,load,loadstring,module,collectgarbage,newproxy,xpcallandprintare removed, and so are the pattern functionsstring.find,string.match,string.gmatchandstring.gsub, whose backtracking on a recorded string the instruction count never sees. The rest of the base library and thestring,table,mathandbitlibraries remain.shirudo reads the decoder from the archived copy of the upatch,
/var/lib/shirudo/upatches/<name>.upatch, opens it as sealed state and runs it only when its bytes are the payload loaded, as the digest on the pin directory records. A decoder that did not arrive inside the signed artifact of the loaded upatch never runs.
An error raised in the decoder drops that snapshot with a message on standard error, its control characters replaced. It never produces a partial record.
Build and check it#
Build the upatch as usual. The builder reads each manifest, resolves
sourceand embeds the file in the signedDCDBsection. It refuses the build when a manifest names another upatch, a map the object does not have, a second decoder for the same map, or a source it cannot read.Confirm that the decoder is in the artifact:
operator$ shirudo upatch info <file>.upatch
<file>is your upatch. TheDecoderssection lists each decoder with its target as<upatch>/<map>,<upatch>empty where the manifest leaves it out, the language and API version, the input formatshirudo.map.v1, the export signal, and the source file with its entry point and size.
Run it on a target#
Load the upatch on the target, then run the decoder against the live map without draining it:
target# shirudo-runtime upatch map <upatch> <map> --json --peek
shirudo-runtimeis the command in the test VM, as Test a upatch on a target explains.<upatch>is the upatch name and<map>the map’s. The command prints what the decoder returned as one JSON document. A failure prints one ofupatch map: decoder load failed: <message>,upatch map: decoder entrypoint '<name>' not found,upatch map: decoder failed: <message>orupatch map: decoder encode failed: <message>, and the instruction limit shows asdecoder instruction limit exceeded.Send one snapshot to a collector:
target# shirudo-runtime upatch map <upatch> <map> --peek --otel \ --otel-endpoint=<url>
<url>is the collector’s OTLP/HTTP base URL. A log decoder’s record goes to<url>/v1/logs, a metric decoder’s metrics to<url>/v1/metrics.
A map without a decoder is exported over OTLP as a log record whose body
lists its entries or serializer pages in hex, and --json reports No
data available for it. An unsigned per-CPU integer map without a decoder
is classified as a metric and then fails to export over OTLP with the same
message, so give such a map a metric decoder.
Next steps#
Monitor and export telemetry to export every map on a schedule
OTLP documents for the documents on the wire
The decoders under
upatches/kernel-obs/decoders/for complete log decoders over arena tables, timestamps included