Skip to content

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

Add OpenTelemetry Lua library (#17621)

Julian Gonzalez Calderon0105e82a31e2
diff --git a/resources/prosody-plugins/mod_test_observer_http.lua b/resources/prosody-plugins/mod_test_observer_http.lua
index f648607036..e2748cbd11 100644
--- a/resources/prosody-plugins/mod_test_observer_http.lua
+++ b/resources/prosody-plugins/mod_test_observer_http.lua
@@ -24,6 +24,11 @@ local jid_lib = require "util.jid";
-- Reset to the default (allow, 200) between tests via POST /test-observer/access-manager.
local access_manager_state = { access = true, status = 200, non_json = false };
+-- Mock OTLP trace receiver for mod_trace tests. Stores every exported
+-- resource_spans payload POSTed by the module's Exporter so tests can assert
+-- a span was (or was not) exported without needing a real OTLP collector.
+local otlp_traces = {};
+
-- ASAP public key servers: serve test RSA public keys so that Prosody can
-- fetch them when verifying RS256 tokens signed by the matching private keys.
-- util.lib.lua constructs the URL as: <asap_key_server>/<sha256hex(kid)>.pem
@@ -381,6 +386,39 @@ module:provides("http", {
};
end;
+ -- POST /test-observer/otlp-traces
+ -- Called by mod_trace's Exporter. Body is the raw OTLP
+ -- ExportTraceServiceRequest JSON; stored verbatim for test assertions.
+ ["POST /otlp-traces"] = function(event)
+ local data = json.decode(event.request.body or "{}");
+ if data then
+ table.insert(otlp_traces, data);
+ end
+ return {
+ status_code = 200;
+ headers = { ["Content-Type"] = "application/json" };
+ body = "{}";
+ };
+ end;
+
+ -- GET /test-observer/otlp-traces
+ -- Returns every ExportTraceServiceRequest body received so far.
+ ["GET /otlp-traces"] = function()
+ local body = #otlp_traces == 0 and "[]" or json.encode(otlp_traces);
+ return {
+ status_code = 200;
+ headers = { ["Content-Type"] = "application/json" };
+ body = body;
+ };
+ end;
+
+ -- DELETE /test-observer/otlp-traces
+ -- Clears the recorded export list. Call before each test.
+ ["DELETE /otlp-traces"] = function()
+ otlp_traces = {};
+ return { status_code = 204 };
+ end;
+
-- GET /test-observer/access-manager
-- Mock access-manager endpoint called by mod_muc_auth_ban.
-- Returns {"access": true} or {"access": false} based on the current
diff --git a/resources/prosody-plugins/mod_trace.lua b/resources/prosody-plugins/mod_trace.lua
new file mode 100644
index 0000000000..13479ced17
--- /dev/null
+++ b/resources/prosody-plugins/mod_trace.lua
@@ -0,0 +1,46 @@
+local otel = module:require "otel"
+local http = require "net.http"
+
+local otlp_endpoint = module:get_option("otlp_endpoint")
+
+if not otlp_endpoint then
+ module:log("warn", "module disabled: otlp_endpoint unset")
+ return
+end
+
+local exporter = otel.Exporter.new(http.request, otlp_endpoint)
+local processor = otel.Processor.new(exporter)
+local tracer = otel.Tracer.new(processor, "prosody", "muc")
+
+local function find_tag(tags, name)
+ for _, tag in ipairs(tags) do
+ if tag.name == name then
+ return tag
+ end
+ end
+ return nil
+end
+
+module:hook("iq/full", function(event)
+ local iq_element = event.stanza.tags[1]
+ if not iq_element then
+ return
+ end
+
+ if iq_element.name ~= "conference-modify" or iq_element.attr.xmlns ~= "jitsi:colibri2" then
+ return
+ end
+
+ local traceparent = find_tag(iq_element.tags, "traceparent")
+ if not traceparent then
+ return
+ end
+
+ local span = tracer:start_span("colibri.conference-modify", {
+ trace_id = traceparent.attr.trace_id,
+ span_id = traceparent.attr.parent_id,
+ })
+ span:end_span()
+
+ traceparent.attr.parent_id = span.span_id
+end, 1)
diff --git a/resources/prosody-plugins/otel.lib.lua b/resources/prosody-plugins/otel.lib.lua
new file mode 100644
index 0000000000..d774a1f1c7
--- /dev/null
+++ b/resources/prosody-plugins/otel.lib.lua
@@ -0,0 +1,203 @@
+-- This opentelemetry library was inspired by https://github.com/yangxikun/opentelemetry-lua,
+-- but simplified and adapted to the Prosody ecosystem.
+
+local json = require "util.json"
+local array = require "util.array"
+local time = require "util.time"
+local random = require "util.random"
+local hex = require "util.hex"
+
+local m = {}
+
+--------------------------------------------------
+-- Util --
+--------------------------------------------------
+
+local function random_hex(n)
+ return hex.to(random.bytes(n))
+end
+local function to_nanoseconds(t)
+ return tostring(math.floor(t * 1e9))
+end
+
+
+--------------------------------------------------
+-- Attribute --
+--------------------------------------------------
+
+local Attribute = {}
+m.Attribute = Attribute
+
+function Attribute.string(value)
+ return {
+ string_value = value
+ }
+end
+
+--------------------------------------------------
+-- Span --
+--------------------------------------------------
+
+local SpanStatus = {
+ UNSET = 0,
+ OK = 1,
+ ERROR = 2,
+}
+
+local SpanKind = {
+ UNSPECIFIED = 0,
+ INTERNAL = 1,
+ SERVER = 2,
+ CLIENT = 3,
+ PRODUCER = 4,
+ CONSUMER = 5,
+}
+
+local Span = {}
+Span.__index = Span
+m.Span = Span
+
+function Span.new(name, tracer, opts)
+ local self = {
+ name = name,
+ tracer = tracer,
+ parent_context = opts.context,
+ trace_id = opts.context and opts.context.trace_id or random_hex(16),
+ span_id = random_hex(8),
+ start_time = time.now(),
+ attributes = array {},
+ }
+
+ return setmetatable(self, Span)
+end
+
+function Span:set_attribute(k, v)
+ table.insert(self.attributes, { key = k, value = v })
+ return self
+end
+
+function Span:end_span()
+ self.end_time = time.now()
+ self.tracer.processor:add(self)
+end
+
+function Span:encode()
+ return {
+ trace_id = self.trace_id,
+ span_id = self.span_id,
+ parent_span_id = self.parent_context and self.parent_context.span_id,
+ name = self.name,
+ start_time_unix_nano = to_nanoseconds(self.start_time),
+ end_time_unix_nano = to_nanoseconds(self.end_time),
+ attributes = self.attributes,
+ kind = self.kind or SpanKind.INTERNAL,
+ status = {
+ code = self.status or SpanStatus.OK
+ }
+ }
+end
+
+--------------------------------------------------
+-- Processor --
+--------------------------------------------------
+
+local Processor = {}
+Processor.__index = Processor
+m.Processor = Processor
+
+function Processor.new(exporter)
+ local self = {
+ exporter = exporter
+ }
+ return setmetatable(self, Processor)
+end
+
+function Processor:add(span)
+ self.exporter:export({ span })
+end
+
+--------------------------------------------------
+-- Exporter --
+--------------------------------------------------
+
+local Exporter = {}
+Exporter.__index = Exporter
+m.Exporter = Exporter
+
+function Exporter.new(request_fn, endpoint)
+ local self = {
+ request_fn = request_fn,
+ endpoint = endpoint,
+ }
+ return setmetatable(self, Exporter)
+end
+
+function Exporter:export(spans)
+ local body = {
+ resource_spans = {
+ {
+ resource = spans[1].tracer.resource,
+ scope_spans = {
+ {
+ scope = {
+ name = spans[1].tracer.name,
+ },
+ spans = {}
+ },
+ },
+ }
+ }
+ }
+
+
+ for _, span in ipairs(spans) do
+ table.insert(
+ body.resource_spans[1].scope_spans[1].spans,
+ span:encode()
+ )
+ end
+
+ self.request_fn(
+ self.endpoint, {
+ method = "POST",
+ headers = {
+ ["Content-Type"] = "application/json",
+ },
+ body = json.encode(body),
+ },
+ function(body, code, response)
+ if code ~= 200 then
+ module:log("error", json.encode(body))
+ end
+ end
+ )
+end
+
+--------------------------------------------------
+-- Tracer --
+--------------------------------------------------
+
+local Tracer = {}
+Tracer.__index = Tracer
+m.Tracer = Tracer
+
+function Tracer.new(processor, service, name)
+ return setmetatable({
+ processor = processor,
+ resource = {
+ attributes = {
+ {
+ key = "service.name",
+ value = Attribute.string(service)
+ }
+ }
+ },
+ name = name,
+ }, Tracer)
+end
+
+function Tracer:start_span(name, context)
+ return Span.new(name, self, { context = context })
+end
+
+return m
diff --git a/tests/prosody/docker/cfg/virtualhosts.cfg.lua b/tests/prosody/docker/cfg/virtualhosts.cfg.lua
index 47d7e49187..ac12cf6123 100644
--- a/tests/prosody/docker/cfg/virtualhosts.cfg.lua
+++ b/tests/prosody/docker/cfg/virtualhosts.cfg.lua
@@ -123,3 +123,17 @@ VirtualHost "shared-secret.localhost"
VirtualHost "whitelist.localhost"
authentication = "anonymous"
+
+-- VirtualHost for mod_trace tests, with otlp_endpoint configured so the
+-- module is active. Points at the mock OTLP receiver served by
+-- mod_test_observer_http on the main VirtualHost.
+VirtualHost "trace.localhost"
+ authentication = "anonymous"
+ modules_enabled = { "trace" }
+ otlp_endpoint = "http://localhost:5280/test-observer/otlp-traces"
+
+-- VirtualHost for mod_trace tests with otlp_endpoint left unset: the module
+-- must log a warning and no-op rather than hook anything.
+VirtualHost "trace-disabled.localhost"
+ authentication = "anonymous"
+ modules_enabled = { "trace" }
diff --git a/tests/prosody/helpers/test_observer.js b/tests/prosody/helpers/test_observer.js
index 4456a90677..9e2458e2ef 100644
--- a/tests/prosody/helpers/test_observer.js
+++ b/tests/prosody/helpers/test_observer.js
@@ -310,6 +310,32 @@ export async function getAudioTranslationRequests(roomJid) {
return res.json();
}
+/**
+ * Returns every OTLP ExportTraceServiceRequest body received by the mock
+ * receiver (mod_test_observer_http) so far. Used by mod_trace tests.
+ * @returns {Promise<Array<object>>}
+ */
+export async function getOtlpTraces() {
+ const res = await fetch(`${BASE}/otlp-traces`);
+
+ if (!res.ok) {
+ throw new Error(`GET /otlp-traces failed: ${res.status}`);
+ }
+
+ return res.json();
+}
+
+/**
+ * Clears the recorded OTLP export list.
+ */
+export async function clearOtlpTraces() {
+ const res = await fetch(`${BASE}/otlp-traces`, { method: 'DELETE' });
+
+ if (res.status !== 204) {
+ throw new Error(`DELETE /otlp-traces failed: ${res.status}`);
+ }
+}
+
/**
* Returns room state from Prosody's internal MUC state.
* @param {string} roomJid e.g. '[email protected]'
diff --git a/tests/prosody/helpers/xmpp_client.js b/tests/prosody/helpers/xmpp_client.js
index 25c0a16513..3542ff0a6e 100644
--- a/tests/prosody/helpers/xmpp_client.js
+++ b/tests/prosody/helpers/xmpp_client.js
@@ -438,6 +438,36 @@ export async function createXmppClient({ host = 'localhost', domain, params, use
);
},
+ /**
+ * Sends a colibri2 conference-modify IQ to the given full JID, optionally
+ * carrying a <traceparent> extension (as jicofo/JVB do when tracing is
+ * enabled). Fire-and-forget — mod_trace does not reply; assert on the
+ * recipient's own stanza queue (waitForIq) and/or the OTLP mock receiver.
+ *
+ * @param {string} to Destination full JID.
+ * @param {object} [opts]
+ * @param {string} [opts.traceId] 32-hex-char trace id. Omit to send no <traceparent>.
+ * @param {string} [opts.parentId] 16-hex-char parent span id. Required when traceId is set.
+ */
+ sendConferenceModifyIq(to, { traceId, parentId } = {}) {
+ const children = traceId === undefined
+ ? []
+ : [ xml('traceparent', {
+ // eslint-disable-next-line camelcase
+ trace_id: traceId,
+ // eslint-disable-next-line camelcase
+ parent_id: parentId
+ }) ];
+
+ return xmpp.send(
+ xml('iq', { type: 'set',
+ to,
+ id: `cm-${++_counter}` },
+ xml('conference-modify', { xmlns: 'jitsi:colibri2' }, ...children)
+ )
+ );
+ },
+
/**
* Sends a disco#info IQ and resolves with the response stanza.
* @param {string} targetJid
diff --git a/tests/prosody/lua/otel_spec.lua b/tests/prosody/lua/otel_spec.lua
new file mode 100644
index 0000000000..665a02f58e
--- /dev/null
+++ b/tests/prosody/lua/otel_spec.lua
@@ -0,0 +1,113 @@
+-- Unit tests for otel.lib.lua
+-- Run with busted from resources/prosody-plugins/:
+-- busted spec/lua/
+-- Requires: lua-cjson
+--
+-- Stubs every Prosody dependency so no Prosody installation is needed.
+
+local os = require "os"
+local cjson = require "cjson"
+
+package.preload['util.json'] = function()
+ return {
+ encode = function(x)
+ return cjson.encode(x)
+ end
+ }
+end
+package.preload['util.array'] = function()
+ return function(t) return t end
+end
+package.preload['util.time'] = function()
+ return {
+ now = function()
+ return os.time();
+ end
+ }
+end
+package.preload['util.random'] = function()
+ return {
+ bytes = function(n)
+ local out = {}
+ for i = 1, n do
+ out[i] = string.char(math.random(0, 255))
+ end
+ return table.concat(out)
+ end
+ }
+end
+package.preload['util.hex'] = function()
+ return {
+ to = function(bytes)
+ local out = {}
+ for i = 1, #bytes do
+ out[i] = string.format("%02x", bytes:byte(i))
+ end
+ return table.concat(out)
+ end
+ }
+end
+
+
+-- Guard: skip the whole suite if the module's hard dependencies aren't installed.
+local ok, M = pcall(dofile, "otel.lib.lua")
+if not ok then
+ describe("otel", function()
+ it("skipped", function()
+ pending(tostring(M):match("([^\n]+)"))
+ end)
+ end)
+ return
+end
+
+describe("otel", function()
+ describe("span", function()
+ it("create and export span", function()
+ local request
+ local request_fn = function(url, options, callback) request = options end
+
+ local exporter = M.Exporter.new(request_fn, "endpoint")
+ local processor = M.Processor.new(exporter)
+ local tracer = M.Tracer.new(processor, "service", "scope")
+
+ local span = tracer:start_span("name", {
+ trace_id = "deadbeefdeadbeefdeadbeefdeadbeef",
+ span_id = "deadbeefdeadbeef",
+ })
+ span:set_attribute("key", M.Attribute.string("value"))
+ span:end_span()
+
+ local body = cjson.decode(request.body)
+ assert.are.same(
+ {
+ attributes = {
+ { key = "service.name", value = { string_value = "service" } }
+ }
+ },
+ body.resource_spans[1].resource)
+ assert.are.same(
+ {
+ name = "scope"
+ },
+ body.resource_spans[1].scope_spans[1].scope
+ )
+
+ local span = body.resource_spans[1].scope_spans[1].spans[1]
+ assert.are.same(
+ { { key = "key", value = { string_value = "value" } } },
+ span.attributes
+ )
+ assert.are.same(
+ "deadbeefdeadbeefdeadbeefdeadbeef",
+ span.trace_id
+ )
+ assert.are.same(
+ "deadbeefdeadbeef",
+ span.parent_span_id
+ )
+ assert.are.same(1, span.kind)
+ assert.are.same("name", span.name)
+ assert.are.same({ code = 1 }, span.status)
+ end)
+ end)
+end) -- otel
diff --git a/tests/prosody/mod_trace_spec.js b/tests/prosody/mod_trace_spec.js
new file mode 100644
index 0000000000..9cfed680fa
--- /dev/null
+++ b/tests/prosody/mod_trace_spec.js
@@ -0,0 +1,123 @@
+import assert from 'assert';
+
+import { clearOtlpTraces, getOtlpTraces } from './helpers/test_observer.js';
+import { createXmppClient } from './helpers/xmpp_client.js';
+
+// Sender lives on a separate, plain VirtualHost from the receiver under test.
+// mod_trace's iq/full hook fires once per host whose event bus a stanza
+// passes through (once for the sender's own outbound processing, once for
+// delivery to the recipient) — using two different hosts here means the
+// hook (loaded only on the receiver's host) fires exactly once, matching
+// real jicofo/JVB topology where sender and receiver are never the same host.
+const SENDER_DOMAIN = 'whitelist.localhost';
+
+/**
+ * Connects a sender client (on SENDER_DOMAIN) and a receiver client (on the
+ * given domain) and registers both for afterEach cleanup.
+ *
+ * @param {string} receiverDomain
+ * @param {Array} clients Cleanup array; both new clients are appended.
+ * @returns {Promise<[object, object]>}
+ */
+async function connectPair(receiverDomain, clients) {
+ const a = await createXmppClient({ domain: SENDER_DOMAIN });
+ const b = await createXmppClient({ domain: receiverDomain });
+
+ clients.push(a, b);
+
+ return [ a, b ];
+}
+
+describe('mod_trace', () => {
+
+ const clients = [];
+
+ beforeEach(() => clearOtlpTraces());
+
+ afterEach(async () => {
+ await Promise.all(clients.map(c => c.disconnect()));
+ clients.length = 0;
+ });
+
+ describe('when otlp_endpoint is unset', () => {
+
+ it('leaves a conference-modify IQ with traceparent unmodified and exports nothing', async () => {
+ const [ a, b ] = await connectPair('trace-disabled.localhost', clients);
+ const traceId = 'd'.repeat(32);
+ const parentId = 'e'.repeat(16);
+
+ await a.sendConferenceModifyIq(b.jid, { traceId,
+ parentId });
+
+ const iq = await b.waitForIq(s => s.getChild('conference-modify', 'jitsi:colibri2'));
+ const cm = iq.getChild('conference-modify', 'jitsi:colibri2');
+ const tp = cm.getChild('traceparent');
+
+ assert.ok(tp, 'traceparent element should still be present');
+ assert.strictEqual(tp.attrs.trace_id, traceId);
+ assert.strictEqual(tp.attrs.parent_id, parentId,
+ 'parent_id must be left untouched when the module is disabled');
+
+ const traces = await getOtlpTraces();
+
+ assert.strictEqual(traces.length, 0, 'no span should be exported when otlp_endpoint is unset');
+ });
+ });
+
+ describe('when otlp_endpoint is set', () => {
+
+ it('leaves a conference-modify IQ without traceparent unmodified and exports nothing', async () => {
+ const [ a, b ] = await connectPair('trace.localhost', clients);
+
+ await a.sendConferenceModifyIq(b.jid);
+
+ const iq = await b.waitForIq(s => s.getChild('conference-modify', 'jitsi:colibri2'));
+ const cm = iq.getChild('conference-modify', 'jitsi:colibri2');
+
+ assert.ok(!cm.getChild('traceparent'),
+ 'no traceparent should be added when the sender did not include one' );
+
+ // Give Prosody a moment to (not) export before asserting the negative.
+ await new Promise(r => setTimeout(r, 300));
+
+ const traces = await getOtlpTraces();
+
+ assert.strictEqual(traces.length, 0);
+ });
+
+ it('rewrites the traceparent parent_id and exports a span for a conference-modify IQ', async () => {
+ const [ a, b ] = await connectPair('trace.localhost', clients);
+ const traceId = 'a'.repeat(32);
+ const parentId = 'b'.repeat(16);
+
+ await a.sendConferenceModifyIq(b.jid, { traceId,
+ parentId });
+
+ const iq = await b.waitForIq(s => s.getChild('conference-modify', 'jitsi:colibri2'));
+ const cm = iq.getChild('conference-modify', 'jitsi:colibri2');
+ const tp = cm.getChild('traceparent');
+
+ assert.ok(tp, 'traceparent element should still be present');
+ assert.strictEqual(tp.attrs.trace_id, traceId, 'trace_id must be preserved');
+ assert.notStrictEqual(tp.attrs.parent_id, parentId, 'parent_id must be rewritten to the new span id');
+ assert.match(tp.attrs.parent_id, /^[0-9a-f]{16}$/, 'rewritten parent_id must be a 16-hex-char span id');
+
+ // Give Prosody a moment to POST the export before polling.
+ await new Promise(r => setTimeout(r, 300));
+
+ const traces = await getOtlpTraces();
+
+ assert.strictEqual(traces.length, 1, 'exactly one export request should have been made');
+
+ const [ resourceSpan ] = traces[0].resource_spans;
+ const [ scopeSpan ] = resourceSpan.scope_spans;
+ const [ span ] = scopeSpan.spans;
+
+ assert.strictEqual(scopeSpan.scope.name, 'muc');
+ assert.strictEqual(span.name, 'colibri.conference-modify');
+ assert.strictEqual(span.trace_id, traceId);
+ assert.strictEqual(span.parent_span_id, parentId,
+ 'exported span must record the original parent_id as its own parent');
+ });
+ });
+});