feat(docs): add the documentation site

- Astro and Starlight site in docs/ for
  https://fairrootgroup.github.io/FairMQ/
- 64 pages in eight groups: start, concepts, guides, shared memory,
  examples, tools, reference and project
- API reference and source browser from the Doxygen XML of fairmq/
- Code samples are snippets of the repository files; the build fails
  when a snippet does not match
- Option tables take the names, types and defaults from the code
- Interactive diagrams: state machine, zero-copy transfer, region
  acknowledgements, session objects, topology and channel anatomy
- The 404 page sends the URLs of the Doxygen site to the new pages
- scripts/check-pages.mjs checks pages, snippets and links without a
  build; scripts/check-links.mjs checks all links in dist/

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Claude
2026-11-05 00:17:41 +00:00
committed by Dennis Klein
parent 866f39f54e
commit 992db82b91
120 changed files with 27931 additions and 0 deletions

View File

@@ -0,0 +1,44 @@
---
// A small button that copies a text to the clipboard.
interface Props {
text: string;
label?: string;
}
const { text, label = 'Copy' } = Astro.props;
---
<button type="button" class="fmq-copy" data-copy={text} aria-label={label} title={label}>Copy</button>
<script>
document.addEventListener('click', async (e) => {
const btn = (e.target as HTMLElement).closest<HTMLButtonElement>('button.fmq-copy');
if (!btn) return;
const text = btn.dataset.copy ?? '';
const done = (msg: string) => {
btn.textContent = msg;
setTimeout(() => (btn.textContent = 'Copy'), 1400);
};
try {
await navigator.clipboard.writeText(text);
done('Copied');
} catch {
done('Not copied');
}
});
</script>
<style>
.fmq-copy {
font: 500 0.75rem/1 var(--fmq-font-body);
border: 1px solid var(--fmq-rule-strong);
background: var(--fmq-paper);
color: var(--fmq-ink-2);
border-radius: 3px;
padding: 0.3rem 0.5rem;
cursor: pointer;
}
.fmq-copy:hover {
border-color: var(--fmq-ink-3);
color: var(--fmq-ink);
}
</style>

View File

@@ -0,0 +1,21 @@
---
// The FairMQ mark: two devices and a message on the channel between them.
interface Props {
size?: number;
}
const { size = 28 } = Astro.props;
---
<svg class="fmq-glyph" width={size} height={Math.round((size * 18) / 30)} viewBox="0 0 30 18" aria-hidden="true">
<rect x="1" y="4" width="10" height="10" fill="none" stroke="currentColor" stroke-width="1.6"></rect>
<rect x="19" y="4" width="10" height="10" fill="none" stroke="currentColor" stroke-width="1.6"></rect>
<line x1="11" y1="9" x2="19" y2="9" stroke="currentColor" stroke-width="1.6"></line>
<rect x="13" y="7" width="4" height="4" fill="var(--fmq-saffron)" stroke="var(--fmq-bar)" stroke-width="0.6"></rect>
</svg>
<style>
.fmq-glyph {
flex: none;
color: var(--fmq-ink);
}
</style>

View File

@@ -0,0 +1,263 @@
---
// Table of command-line options, read from the C++ code at build time.
//
// <OptionsTable /> all options of a device made with runDevice.h
// <OptionsTable groups={['Shared memory']} /> only some groups, without the filter
// <OptionsTable file="fairmq/shmem/runMonitor.cxx" texts={...} /> the options of a tool
import { paths } from 'virtual:fairmq/data';
import { deviceOptions, readOptions } from '../../scripts/options.mjs';
import { deviceOptionTexts } from '../data/option-texts.mjs';
interface Props {
file?: string;
groups?: string[];
texts?: Record<string, string>;
filter?: boolean;
id?: string;
}
const { file, groups, texts, filter, id = 'opt' } = Astro.props;
const base = import.meta.env.BASE_URL.replace(/\/$/, '');
let options = file
? readOptions(paths.repoRoot, [{ file, source: file.split('/').pop(), group: 'Options' }])
: deviceOptions(paths.repoRoot);
const curated = texts ?? (file ? {} : deviceOptionTexts);
for (const key of Object.keys(curated)) {
if (!options.some((o: any) => o.name === key)) throw new Error(`OptionsTable: no option --${key} in the code (${file ?? 'device options'})`);
}
if (groups) options = options.filter((o: any) => groups.includes(o.group));
const order = ['Device', 'Shared memory', 'Control', 'Logging', 'Plugins', 'General', 'Options'];
const allGroups = [...new Set(options.map((o: any) => o.group))].sort((a: any, b: any) => order.indexOf(a) - order.indexOf(b));
const showFilter = filter ?? (!groups && options.length > 12);
const sorted = [...options].sort((a: any, b: any) => order.indexOf(a.group) - order.indexOf(b.group));
const fmt = (v: string | undefined) => (v === undefined ? undefined : v === '' ? '""' : v);
---
<div class="fmq-opts not-content" data-opts>
{
showFilter && (
<div class="fmq-opts-bar" role="group" aria-label="Filter options">
<input type="search" placeholder="Filter, for example shm or timeout" aria-label="Filter options" />
<div class="fmq-opts-groups">
<button type="button" data-g="" aria-pressed="true">
All
</button>
{allGroups.map((g) => (
<button type="button" data-g={g} aria-pressed="false">
{g}
</button>
))}
</div>
<p class="fmq-opts-count" aria-live="polite">
{options.length} options
</p>
</div>
)
}
<div class="fmq-opts-scroll">
<table>
<thead>
<tr>
<th scope="col">Option</th>
<th scope="col">Default</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
{
sorted.map((o: any) => (
<tr id={`${id}-${o.name}`} data-g={o.group} data-q={`${o.name} ${o.short} ${o.description} ${curated[o.name] ?? ''}`.toLowerCase()}>
<td class="o-name">
<a href={`#${id}-${o.name}`}>
<code>
{o.short && `-${o.short}, `}--{o.name}
</code>
</a>
<span class="o-type">{o.flag ? 'flag' : o.type}{o.multitoken ? ', several values' : ''}</span>
</td>
<td class="o-def">
{fmt(o.default) !== undefined ? <code>{fmt(o.default)}</code> : o.implicit !== undefined ? <span class="o-none">no value: {o.implicit}</span> : <span class="o-none">—</span>}
</td>
<td class="o-desc">
<Fragment set:html={curated[o.name] ?? o.description.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\n/g, '<br>')} />
<a class="o-src" href={`${base}/source/${o.file}/#L${o.line}`} title={`Defined in ${o.file}:${o.line}`}>
{o.source}
</a>
</td>
</tr>
))
}
<tr class="o-empty" hidden>
<td colspan="3">No option matches. Clear the filter or choose All.</td>
</tr>
</tbody>
</table>
</div>
</div>
<script>
for (const root of document.querySelectorAll<HTMLElement>('[data-opts]')) {
const input = root.querySelector<HTMLInputElement>('input[type=search]');
if (!input) continue;
const buttons = [...root.querySelectorAll<HTMLButtonElement>('button[data-g]')];
const rows = [...root.querySelectorAll<HTMLTableRowElement>('tbody tr[data-g]')];
const empty = root.querySelector<HTMLTableRowElement>('tr.o-empty')!;
const count = root.querySelector('.fmq-opts-count')!;
let group = '';
const apply = () => {
const q = input.value.trim().toLowerCase();
let n = 0;
for (const r of rows) {
const ok = (!group || r.dataset.g === group) && (!q || (r.dataset.q ?? '').includes(q));
r.hidden = !ok;
if (ok) n++;
}
empty.hidden = n > 0;
count.textContent = n === rows.length ? `${rows.length} options` : `${n} of ${rows.length} options`;
};
input.addEventListener('input', apply);
for (const b of buttons)
b.addEventListener('click', () => {
group = b.dataset.g ?? '';
for (const o of buttons) o.setAttribute('aria-pressed', String(o === b));
apply();
});
}
</script>
<style>
.fmq-opts {
margin-block: 1.25rem;
}
.fmq-opts-bar {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
margin-bottom: 0.5rem;
}
.fmq-opts-bar input {
flex: 1 1 16rem;
max-width: 22rem;
font: 400 0.9375rem var(--fmq-font-body);
color: var(--fmq-ink);
background: var(--fmq-paper-2);
border: 1px solid var(--fmq-rule-strong);
border-radius: 4px;
padding: 0.4rem 0.6rem;
}
.fmq-opts-groups {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.fmq-opts-groups button {
font: 500 0.8125rem/1 var(--fmq-font-body);
border: 1px solid var(--fmq-rule-strong);
border-radius: 3px;
background: var(--fmq-paper);
color: var(--fmq-ink-2);
padding: 0.4rem 0.6rem;
cursor: pointer;
}
.fmq-opts-groups button:hover {
border-color: var(--fmq-ink-3);
color: var(--fmq-ink);
}
.fmq-opts-groups button[aria-pressed='true'] {
background: var(--fmq-saffron-tint);
border-color: var(--fmq-bar);
color: var(--fmq-ink);
}
.fmq-opts-count {
flex-basis: 100%;
margin: 0;
font-size: 0.8125rem;
color: var(--fmq-ink-3);
}
.fmq-opts-scroll {
overflow-x: auto;
border-top: 1px solid var(--fmq-rule-strong);
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.9rem;
min-width: 40rem;
}
th {
text-align: start;
font: 600 0.7rem/1.2 var(--fmq-font-body);
font-stretch: 88%;
letter-spacing: 0.1em;
text-transform: uppercase;
color: var(--fmq-ink-3);
padding: 0.55rem 0.6rem;
border-bottom: 1px solid var(--fmq-rule-strong);
}
td {
padding: 0.55rem 0.6rem;
border-bottom: 1px solid var(--fmq-rule);
vertical-align: top;
line-height: 1.5;
}
tr:target {
background: var(--fmq-saffron-tint);
}
tr[id] {
scroll-margin-top: 6rem;
}
code {
font-family: var(--fmq-font-mono);
font-size: 0.82rem;
}
.o-name a {
color: var(--fmq-ink);
text-decoration: none;
font-weight: 600;
white-space: nowrap;
}
.o-name a:hover {
color: var(--fmq-link);
}
.o-type {
display: block;
font: 400 0.72rem var(--fmq-font-mono);
color: var(--fmq-ink-3);
margin-top: 0.15rem;
}
.o-def code {
white-space: nowrap;
background: var(--fmq-paper-3);
border: 1px solid var(--fmq-rule);
border-radius: 3px;
padding: 0.05em 0.35em;
}
.o-none {
color: var(--fmq-ink-3);
font-size: 0.8125rem;
}
.o-desc :global(code) {
background: var(--fmq-paper-3);
border: 1px solid var(--fmq-rule);
border-radius: 3px;
padding: 0.05em 0.3em;
}
.o-src {
margin-inline-start: 0.4rem;
font: 500 0.7rem var(--fmq-font-mono);
color: var(--fmq-ink-3);
text-decoration: none;
white-space: nowrap;
}
.o-src:hover {
color: var(--fmq-link);
}
.o-empty td {
text-align: center;
color: var(--fmq-ink-3);
padding: 1.25rem;
}
tr[hidden] {
display: none;
}
</style>

View File

@@ -0,0 +1,68 @@
---
// Shows code from a file of the repository, so that samples are code that CI compiles.
//
// <Snippet file="examples/1-1/sampler.cxx" /> whole file, without the license header
// <Snippet file="examples/1-1/sampler.cxx" region="run" /> lines between the markers //! [run]
// <Snippet file="examples/1-1/sampler.cxx" lines="20-34" /> a line range (1-based, inclusive)
// <Snippet file="examples/1-1/sampler.cxx" start="bool ConditionalRun()" />
// from the first line that contains the text to the line that closes its braces
// <Snippet file="examples/1-1/sampler.cxx" start="void addCustomOptions" end="^}" />
// from the start line to the next line that matches end (text, or /regex/ like "^}")
//
// The build fails if the file, the region, the lines or the start text do not exist.
import { Code } from '@astrojs/starlight/components';
import path from 'node:path';
import { paths, build } from 'virtual:fairmq/data';
import { extractSnippet } from '../../scripts/snippet.mjs';
interface Props {
file: string;
region?: string;
lines?: string;
start?: string;
end?: string;
lang?: string;
title?: string;
mark?: string | string[];
link?: boolean;
}
const { file, region, lines, start, end, lang, title, mark, link = true } = Astro.props;
const { code, first, last: lastLine } = extractSnippet(paths.repoRoot, { file, region, lines, start, end });
const ext = path.extname(file).slice(1);
const language =
lang ?? ({ cxx: 'cpp', cpp: 'cpp', h: 'cpp', hpp: 'cpp', sh: 'sh', json: 'json', cmake: 'cmake', txt: 'cmake', py: 'python', in: 'sh' } as Record<string, string>)[ext] ?? 'text';
const base = import.meta.env.BASE_URL.replace(/\/$/, '');
const sourceLink = /^fairmq\/.*\.(h|cxx)$/.test(file) ? `${base}/source/${file}/#L${first}-L${lastLine}` : `${build.repo}/blob/${build.commit}/${file}#L${first}-L${lastLine}`;
---
<div class="fmq-snippet">
<Code code={code} lang={language} title={title ?? file} mark={mark} />
{
link && (
<a class="fmq-snippet-src" href={sourceLink}>
{file}:{first}–{lastLine}
</a>
)
}
</div>
<style>
.fmq-snippet {
margin-block: 1rem;
}
.fmq-snippet :global(.expressive-code) {
margin-block: 0 !important;
}
.fmq-snippet-src {
display: block;
text-align: end;
margin-top: 0.3rem;
font: 500 0.72rem var(--fmq-font-mono);
color: var(--fmq-ink-3);
text-decoration: none;
}
.fmq-snippet-src:hover {
color: var(--fmq-link);
}
</style>

View File

@@ -0,0 +1,109 @@
---
// One member of a class or namespace: signature, comment, parameters, source line.
import { base } from '../../lib/model.mjs';
import { family } from '../../lib/families.mjs';
interface Props {
m: any;
owner?: any;
}
const { m, owner } = Astro.props;
const badges: { text: string; cls?: string }[] = [];
if (m.template) badges.push({ text: 'template' });
if (m.static && m.kind === 'function') badges.push({ text: 'static' });
if (m.virt === 'pure-virtual') badges.push({ text: 'pure virtual' });
else if (m.virt === 'virtual') badges.push({ text: 'virtual' });
if (m.prot === 'protected') badges.push({ text: 'protected' });
if (m.deprecated) badges.push({ text: 'deprecated', cls: 'deprecated' });
if (m.since) badges.push({ text: `since ${m.since}`, cls: 'since' });
const src = `${base}/source/${m.file}/#L${m.line}`;
const fileName = m.file.split('/').pop();
const fam = owner ? family(m, owner) : '';
const Heading = m.overload > 1 ? 'p' : 'h3';
const hasDetails = m.params.length || m.tparams.length || m.returns || m.retvals.length || m.throws.length;
---
<article class="mem" data-family={fam} data-name={m.name.toLowerCase()}>
<div class="mem-h">
<Heading id={m.anchor} class="mem-name"><a href={`#${m.anchor}`}>{m.name}</a></Heading>
{badges.map((b) => <span class:list={['fmq-badge', b.cls]}>{b.text}</span>)}
<a class="mem-src" href={src}>{fileName}:{m.line}</a>
</div>
<pre class="mem-sig"><code set:html={m.sigHtml} /></pre>
{m.deprecated && <div class="doc-aside caution"><b>Deprecated</b><Fragment set:html={m.deprecated} /></div>}
{m.brief && <p class="mem-brief" set:html={m.brief} />}
{m.detail && <div class="mem-detail" set:html={m.detail} />}
{
hasDetails ? (
<dl class="mem-params">
{m.tparams.map((p: any) => (
<>
<dt>
<code>{p.name}</code> <span class="mem-pk">template parameter</span>
</dt>
<dd set:html={p.html || '—'} />
</>
))}
{m.params.map((p: any) => (
<>
<dt>
<code>{p.name}</code>
{p.dir && <span class="mem-pk">{p.dir}</span>}
</dt>
<dd set:html={p.html || '—'} />
</>
))}
{m.returns && (
<>
<dt class="mem-ret">Returns</dt>
<dd set:html={m.returns} />
</>
)}
{m.retvals.map((p: any) => (
<>
<dt>
<code>{p.name}</code> <span class="mem-pk">return value</span>
</dt>
<dd set:html={p.html} />
</>
))}
{m.throws.map((p: any) => (
<>
<dt>
<code>{p.name}</code> <span class="mem-pk">throws</span>
</dt>
<dd set:html={p.html} />
</>
))}
</dl>
) : null
}
{
m.values && m.values.length > 0 && (
<div class="doc-table">
<table class="enum-values">
<thead>
<tr>
<th>Enumerator</th>
<th>Value</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{m.values.map((v: any) => (
<tr id={`${m.anchor}-${v.anchor}`}>
<td>
<code>{v.name}</code>
</td>
<td>{v.init ? <code>{v.init}</code> : <span class="muted">—</span>}</td>
<td set:html={v.html || '<span class="muted">—</span>'} />
</tr>
))}
</tbody>
</table>
</div>
)
}
{m.see.length > 0 && <p class="mem-see">See also: <Fragment set:html={m.see.join(', ')} /></p>}
{!m.documented && <p class="mem-none">No comment in the header yet.</p>}
</article>

View File

@@ -0,0 +1,124 @@
---
// A device with two channels. A channel is a vector of sub-channels; each sub-channel owns one socket.
// Facts: fairmq/Device.h (fChannels: name → std::vector<Channel>, GetChannel(name, index)),
// fairmq/Channel.h (type, method, address, transport).
const subs = [
{ x: 28, ch: 'data-in', i: 0, type: 'pull', method: 'connect', addr: 'tcp://sampler:5555', side: 'in' },
{ x: 336, ch: 'data-out', i: 0, type: 'push', method: 'bind', addr: 'tcp://*:5556', side: 'out' },
{ x: 486, ch: 'data-out', i: 1, type: 'push', method: 'bind', addr: 'tcp://*:5557', side: 'out' },
];
---
<figure class="fmq-chan not-content">
<svg viewBox="0 0 660 250" role="img" aria-label="A device with the channel data-in (one sub-channel) and the channel data-out (two sub-channels). Each sub-channel owns one socket.">
<rect class="dev" x="10" y="10" width="640" height="190" rx="3"></rect>
<text class="dev-l" x="24" y="32">device · --id processor1</text>
<rect class="ch" x="20" y="44" width="162" height="146" rx="2"></rect>
<text class="ch-l" x="30" y="62">channel "data-in"</text>
<rect class="ch" x="328" y="44" width="312" height="146" rx="2"></rect>
<text class="ch-l" x="338" y="62">channel "data-out"</text>
{
subs.map((s) => (
<g>
<rect class="sub" x={s.x} y="72" width="146" height="108" rx="2" />
<text class="sub-l" x={s.x + 10} y="90">
sub-channel [{s.i}]
</text>
<text class="kv" x={s.x + 10} y="112">
<tspan class="k">type</tspan> {s.type}
</text>
<text class="kv" x={s.x + 10} y="130">
<tspan class="k">method</tspan> {s.method}
</text>
<text class="kv addr" x={s.x + 10} y="148">
{s.addr}
</text>
<rect class="sock" x={s.x + 10} y="158" width="10" height="10" />
<text class="kv k" x={s.x + 26} y="167">
1 socket
</text>
</g>
))
}
<path class="lead" d="M101 180 V 212"></path>
<path class="lead" d="M409 180 V 212"></path>
<path class="lead" d="M600 180 V 230"></path>
<text class="code" x="28" y="224">GetChannel("data-in")</text>
<text class="code" x="336" y="224">GetChannel("data-out", 0)</text>
<text class="code" x="490" y="242">GetChannel("data-out", 1)</text>
</svg>
<figcaption>
A channel has a name and one or more sub-channels. Each sub-channel owns one socket, with its own type, method and address. The index of the sub-channel is the
second argument of <code>GetChannel()</code>, and the third argument of <code>Send()</code> and <code>Receive()</code>. The default index is 0.
</figcaption>
</figure>
<style>
.fmq-chan {
margin: 1.5rem 0;
}
svg {
width: 100%;
height: auto;
display: block;
}
.dev {
fill: var(--fmq-paper-2);
stroke: var(--fmq-ink-2);
stroke-width: 1.2;
}
.ch {
fill: var(--fmq-paper);
stroke: var(--fmq-rule-strong);
stroke-width: 1.2;
}
.sub {
fill: var(--fmq-paper);
stroke: var(--fmq-ink-3);
stroke-dasharray: 4 3;
}
.sock {
fill: var(--fmq-saffron);
stroke: var(--fmq-bar);
}
.lead {
fill: none;
stroke: var(--fmq-ink-3);
stroke-width: 1;
stroke-dasharray: 2 3;
}
.dev-l {
font: 700 13px var(--fmq-font-mono);
fill: var(--fmq-ink);
}
.ch-l {
font: 600 12px var(--fmq-font-mono);
fill: var(--fmq-ink);
}
.sub-l {
font: 600 11px var(--fmq-font-mono);
fill: var(--fmq-ink-2);
}
.kv {
font: 400 11px var(--fmq-font-mono);
fill: var(--fmq-ink);
}
.k {
fill: var(--fmq-ink-3);
}
.addr {
fill: var(--fmq-accent-ink);
}
.code {
font: 600 11px var(--fmq-font-mono);
fill: var(--fmq-link);
}
figcaption {
font-size: 0.85rem;
color: var(--fmq-ink-3);
margin-top: 0.5rem;
}
figcaption code {
font-size: 0.8em;
}
</style>

View File

@@ -0,0 +1,331 @@
---
// A step-by-step explainer: a dark stage with an SVG, a caption, a line of code and controls.
// The slot holds the SVG. It must have the attribute data-stage. For step n (1-based), the
// script sets the classes r1 … rn and now<n> on the SVG, so CSS can show each step. Elements
// with data-slot="name" get the text of step.set[name].
interface Step {
cap: string;
code?: string;
set?: Record<string, string>;
}
interface Props {
title: string;
meta?: string;
steps: Step[];
}
const { title, meta, steps } = Astro.props;
---
<div class="fmq-ex not-content" tabindex="0" aria-label={`${title}. Explainer in ${steps.length} steps. Use the arrow keys to step.`} data-steps={JSON.stringify(steps)}>
<div class="ex-top">
<b>{title}</b>
{meta && <span>{meta}</span>}
</div>
<slot />
<div class="ex-foot">
<p class="ex-cap" aria-live="polite">{steps[0].cap}</p>
<code class="ex-line">{steps[0].code}</code>
</div>
<div class="ex-ctl">
<button class="ex-b" type="button" data-act="restart" aria-label="Start again"
><svg viewBox="0 0 14 14" aria-hidden="true"><path d="M3 2v10" stroke="currentColor" stroke-width="1.6"></path><path d="M12 2L5 7l7 5z" fill="currentColor"></path></svg></button
>
<button class="ex-b" type="button" data-act="prev" aria-label="Previous step"
><svg viewBox="0 0 14 14" aria-hidden="true"><path d="M10 2L4 7l6 5z" fill="currentColor"></path></svg></button
>
<button class="ex-b" type="button" data-act="play" aria-label="Play" data-state="play"
><svg class="i-play" viewBox="0 0 14 14" aria-hidden="true"><path d="M3 2l9 5-9 5z" fill="currentColor"></path></svg><svg
class="i-pause"
viewBox="0 0 14 14"
aria-hidden="true"><path d="M3 2h3v10H3zM8 2h3v10H8z" fill="currentColor"></path></svg
></button
>
<button class="ex-b" type="button" data-act="next" aria-label="Next step"
><svg viewBox="0 0 14 14" aria-hidden="true"><path d="M4 2l6 5-6 5z" fill="currentColor"></path></svg></button
>
<div class="ex-ticks">
{
steps.map((_, k) => (
<button type="button" aria-label={`Step ${k + 1}`} data-step={k}>
{k + 1}
</button>
))
}
</div>
<span class="ex-count">1 / {steps.length}</span>
</div>
<details class="ex-text">
<summary>All steps as text</summary>
<ol>
{
steps.map((s) => (
<li>
{s.cap}
{s.code && (
<>
{' '}
<code>{s.code}</code>
</>
)}
</li>
))
}
</ol>
</details>
</div>
<script>
for (const root of document.querySelectorAll<HTMLElement>('.fmq-ex')) {
const steps: { cap: string; code?: string; set?: Record<string, string> }[] = JSON.parse(root.dataset.steps!);
const svg = root.querySelector<SVGSVGElement>('svg[data-stage]')!;
const baseClass = svg.getAttribute('class') ?? '';
const cap = root.querySelector('.ex-cap')!;
const line = root.querySelector<HTMLElement>('.ex-line')!;
const play = root.querySelector<HTMLButtonElement>('[data-act=play]')!;
const count = root.querySelector('.ex-count')!;
const ticks = [...root.querySelectorAll<HTMLButtonElement>('[data-step]')];
const slots = [...svg.querySelectorAll<SVGElement>('[data-slot]')];
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
let i = 0;
let playing = false;
let timer = 0;
let seen = false;
const show = (n: number) => {
i = Math.max(0, Math.min(steps.length - 1, n));
const st = i + 1;
const c = [baseClass];
for (let k = 1; k <= st; k++) c.push('r' + k);
c.push('now' + st);
svg.setAttribute('class', c.join(' ').trim());
cap.textContent = steps[i].cap;
line.textContent = steps[i].code ?? '';
line.hidden = !steps[i].code;
for (const el of slots) el.textContent = steps[i].set?.[el.dataset.slot!] ?? '';
ticks.forEach((b, k) => {
b.classList.toggle('done', k < i);
b.classList.toggle('on', k === i);
if (k === i) b.setAttribute('aria-current', 'step');
else b.removeAttribute('aria-current');
});
count.textContent = `${st} / ${steps.length}`;
};
const pause = () => {
playing = false;
clearTimeout(timer);
play.dataset.state = 'play';
play.setAttribute('aria-label', 'Play');
};
const step = () => {
if (!playing) return;
if (i >= steps.length - 1) return pause();
show(i + 1);
timer = window.setTimeout(step, 4200);
};
const start = () => {
if (i >= steps.length - 1) show(0);
playing = true;
play.dataset.state = 'pause';
play.setAttribute('aria-label', 'Pause');
clearTimeout(timer);
timer = window.setTimeout(step, 3400);
};
root.addEventListener('click', (e) => {
const b = (e.target as HTMLElement).closest('button');
if (!b) return;
const act = b.dataset.act;
if (act === 'play') return playing ? pause() : start();
pause();
if (act === 'prev') show(i - 1);
else if (act === 'next') show(i + 1);
else if (act === 'restart') show(0);
else if (b.dataset.step) show(Number(b.dataset.step));
});
root.addEventListener('keydown', (e) => {
if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
e.preventDefault();
pause();
show(i + (e.key === 'ArrowRight' ? 1 : -1));
}
});
show(0);
if (!reduce && 'IntersectionObserver' in window) {
new IntersectionObserver(
(es) => {
for (const e of es) {
if (e.isIntersecting && !seen) {
seen = true;
start();
} else if (!e.isIntersecting && playing) pause();
}
},
{ threshold: 0.6 }
).observe(svg);
}
}
</script>
<style>
.fmq-ex {
background: var(--fmq-stage);
color: var(--fmq-stage-ink);
border: 1px solid var(--fmq-stage-rule);
border-radius: 6px;
overflow: hidden;
margin-block: 1.5rem;
}
.fmq-ex:focus-visible {
outline: 2px solid var(--fmq-sky-bright);
outline-offset: 2px;
}
.ex-top {
display: flex;
justify-content: space-between;
gap: 0.6rem;
align-items: center;
padding: 0.75rem 1rem 0;
flex-wrap: wrap;
}
.ex-top b {
font: 800 0.95rem/1.2 var(--fmq-font-body);
font-stretch: 110%;
}
.ex-top span {
font: 500 0.75rem/1 var(--fmq-font-mono);
color: var(--fmq-stage-dim);
}
.fmq-ex :global(svg[data-stage]) {
width: 100%;
height: auto;
display: block;
}
.fmq-ex :global(svg[data-stage] text) {
font-family: var(--fmq-font-mono);
}
.ex-foot {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 0.6rem;
padding: 0.25rem 1.1rem 1rem;
}
.ex-cap {
font-size: 1.05rem;
line-height: 1.5;
margin: 0;
min-height: 4.6em;
max-width: 66ch;
color: var(--fmq-stage-ink);
}
code.ex-line {
font: 500 0.8125rem/1.4 var(--fmq-font-mono);
color: var(--fmq-saffron);
background: var(--fmq-stage-2);
border: 1px solid var(--fmq-stage-rule);
border-radius: 3px;
padding: 0.4rem 0.6rem;
justify-self: start;
max-width: 100%;
overflow-x: auto;
white-space: nowrap;
}
code.ex-line[hidden] {
display: block;
visibility: hidden;
}
.ex-ctl {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
border-top: 1px solid var(--fmq-stage-rule);
padding: 0.6rem 0.9rem;
background: var(--fmq-stage-2);
}
.ex-b {
width: 34px;
height: 32px;
display: inline-grid;
place-items: center;
border: 1px solid var(--fmq-stage-line);
background: transparent;
color: var(--fmq-stage-ink);
border-radius: 4px;
cursor: pointer;
padding: 0;
}
.ex-b:hover {
border-color: var(--fmq-stage-dim);
}
.ex-b svg {
width: 14px;
height: 14px;
}
.ex-b .i-pause {
display: none;
}
.ex-b[data-state='pause'] .i-pause {
display: block;
}
.ex-b[data-state='pause'] .i-play {
display: none;
}
.ex-ticks {
display: flex;
gap: 5px;
margin-inline-start: 0.4rem;
flex-wrap: wrap;
}
.ex-ticks button {
width: 24px;
height: 24px;
border: 1px solid var(--fmq-stage-line);
background: transparent;
color: var(--fmq-stage-dim);
font: 600 0.66rem/1 var(--fmq-font-mono);
cursor: pointer;
padding: 0;
border-radius: 2px;
}
.ex-ticks button:global(.done) {
background: var(--fmq-stage-line);
color: var(--fmq-stage-ink);
}
.ex-ticks button:global(.on) {
background: var(--fmq-saffron);
border-color: var(--fmq-saffron);
color: var(--fmq-on-saffron);
}
.ex-count {
margin-inline-start: auto;
font: 500 0.75rem/1 var(--fmq-font-mono);
color: var(--fmq-stage-dim);
}
.ex-text {
border-top: 1px solid var(--fmq-stage-rule);
padding: 0.55rem 1rem;
font-size: 0.875rem;
color: var(--fmq-stage-dim);
}
.ex-text summary {
cursor: pointer;
font-weight: 500;
}
.ex-text ol {
margin: 0.5rem 0 0.25rem;
padding-inline-start: 1.4rem;
color: var(--fmq-stage-ink);
line-height: 1.55;
}
.ex-text li + li {
margin-top: 0.35rem;
}
.ex-text code {
font: 500 0.78rem var(--fmq-font-mono);
color: var(--fmq-saffron);
overflow-wrap: anywhere;
}
@media print {
.ex-ctl {
display: none;
}
}
</style>

View File

@@ -0,0 +1,125 @@
---
// The four common socket patterns. Socket types: fairmq/Channel.cxx (Validate).
// shmem rejects pub and sub: fairmq/shmem/Socket.h.
const patterns = [
{ a: 'push', b: 'pull', fan: true, cap: 'push → pull', m: 'round-robin', both: 1 },
{ a: 'pub', b: 'sub', fan: true, cap: 'pub → sub', m: 'a copy to each', both: 2, note: 'zeromq only' },
{ a: 'req', b: 'rep', fan: false, cap: 'req ⇄ rep', m: 'request, then reply' },
{ a: 'pair', b: 'pair', fan: false, cap: 'pair ⇄ pair', m: 'two peers only' },
];
---
<figure class="fmq-pat not-content">
<svg viewBox="0 0 600 150" role="img" aria-label="Four socket patterns: push to pull, pub to sub, req and rep, pair and pair.">
<defs>
<marker id="pat-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"
><path d="M0 0L10 5L0 10z" class="ah"></path></marker
>
</defs>
{
patterns.map((p, i) => (
<g transform={`translate(${i * 152} 0)`}>
<rect class="box" x="4" y="40" width="46" height="26" />
<text class="t" x="27" y="57" text-anchor="middle">
{p.a}
</text>
{p.fan ? (
<>
<rect class="box" x="92" y="10" width="46" height="26" />
<text class="t" x="115" y="27" text-anchor="middle">
{p.b}
</text>
<rect class="box" x="92" y="70" width="46" height="26" />
<text class="t" x="115" y="87" text-anchor="middle">
{p.b}
</text>
<path class="line" d="M50 50 L92 24" marker-end="url(#pat-a)" />
<path class="line" d="M50 56 L92 82" marker-end="url(#pat-a)" />
<rect class="msg" x="67" y="32" width="7" height="7" />
{p.both === 2 && <rect class="msg" x="67" y="66" width="7" height="7" />}
</>
) : (
<>
<rect class="box" x="92" y="40" width="46" height="26" />
<text class="t" x="115" y="57" text-anchor="middle">
{p.b}
</text>
<path class="line" d="M50 47 L92 47" marker-end="url(#pat-a)" />
<path class="line" d="M92 59 L50 59" marker-end="url(#pat-a)" />
</>
)}
<text class="cap" x="4" y="118">
{p.cap}
</text>
<text class="m" x="4" y="134">
{p.m}
</text>
{p.note && (
<text class="note" x="4" y="148">
{p.note}
</text>
)}
</g>
))
}
</svg>
<figcaption>
FairMQ also accepts <code>dealer</code>, <code>router</code>, <code>xpub</code> and <code>xsub</code>. The shmem transport does not support <code>pub</code> and <code>sub</code>.
</figcaption>
</figure>
<style>
.fmq-pat {
margin: 1.5rem 0;
border-top: 1px solid var(--fmq-rule);
border-bottom: 1px solid var(--fmq-rule);
padding: 0.9rem 0 0.6rem;
}
svg {
width: 100%;
height: auto;
display: block;
}
.box {
fill: var(--fmq-paper);
stroke: var(--fmq-ink-2);
stroke-width: 1.2;
}
.line {
stroke: var(--fmq-ink-3);
stroke-width: 1.2;
fill: none;
}
.ah {
fill: var(--fmq-ink-3);
}
.msg {
fill: var(--fmq-saffron);
stroke: var(--fmq-bar);
stroke-width: 1;
}
.t {
font: 600 11.5px var(--fmq-font-mono);
fill: var(--fmq-ink);
}
.m {
font: 400 10.5px var(--fmq-font-mono);
fill: var(--fmq-ink-3);
}
.note {
font: 600 10px var(--fmq-font-mono);
fill: var(--fmq-ruby);
}
.cap {
font: 600 12px var(--fmq-font-body);
fill: var(--fmq-ink);
}
figcaption {
font-size: 0.85rem;
color: var(--fmq-ink-3);
margin-top: 0.5rem;
}
figcaption code {
font-size: 0.8em;
}
</style>

View File

@@ -0,0 +1,352 @@
---
// How the creator of an unmanaged region learns that its blocks are free again.
// Facts: fairmq/shmem/UnmanagedRegion.h (ReleaseBlock, SendAcks, ReceiveAcks, fAckBunchSize = 256,
// wait_for 500 ms, queue name "rgq", bulk callback or one call per block), Manager.h (with a callback the
// creator starts an ack receiver and an ack sender; a device that opens a remote region starts an ack
// sender), Message.h (GetData opens the region, Deallocate).
import Explainer from './Explainer.astro';
const steps = [
{
cap: 'The sampler creates an unmanaged region and gives a bulk callback. The memory of the region belongs to the sampler. Because of the callback, FairMQ starts an ack receiver in the sampler. It also starts an ack sender there, for messages that come back.',
code: 'auto region = NewUnmanagedRegionFor("data", 0, 10000000, callback);',
set: { a: 'NewUnmanagedRegionFor(…)' },
},
{
cap: 'The sampler writes data into the region and makes messages that point to it. The transport allocates no memory in the managed segment for these messages.',
code: 'auto msg = NewMessageFor("data", 0, region, ptr, size, hint);',
set: { a: 'NewMessageFor(…)' },
},
{
cap: 'Send() puts only a MetaHeader for each message into the socket. The data stays in the region.',
code: 'Send(parts, "data");',
set: { a: 'Send(parts, "data")' },
},
{
cap: 'The sink receives the messages. At the first GetData(), the sink opens the region and reads the data in place. FairMQ starts an ack sender in the sink.',
code: 'Receive(parts, "data");',
set: { b: 'Receive(parts, "data")' },
},
{
cap: 'The sink destroys the messages. The transport puts each block, with its size and its hint, into a list in the sink.',
code: '} // parts are destroyed: the blocks go into the list',
set: { b: '~Message()' },
},
{
cap: 'The ack sender sends the list as one bunch into the region queue. It sends when the list holds 256 blocks, or after 500 ms.',
code: 'fmq_<shmId>_rgq_<regionId>',
},
{
cap: 'The ack receiver of the sampler gets the bunch. It calls the bulk callback one time with all blocks of the bunch: pointer, size and hint. A RegionCallback runs one time for each block.',
code: '[](const std::vector<fair::mq::RegionBlock>& blocks) { … }',
set: { a: 'callback(blocks)' },
},
{
cap: 'In the callback, the sampler marks the blocks as free. Then it can write new data into them.',
code: 'fNumUnackedMsgs -= blocks.size();',
set: { a: 'blocks are free' },
},
];
const blocks = [96, 196, 296, 396];
---
<Explainer title="Free blocks of an unmanaged region" meta="sampler → sink · same host" steps={steps}>
<svg class="ra" data-stage viewBox="0 0 720 330" role="img" aria-label="The acknowledgement of unmanaged region blocks">
<defs>
<pattern id="ra-cells" width="16" height="72" patternUnits="userSpaceOnUse"><line x1="0.5" y1="0" x2="0.5" y2="72" class="cell"></line></pattern>
<pattern id="ra-stripes" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="3" height="8" class="stripe"></rect></pattern>
<marker id="ra-arr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"
><path d="M0 0L10 5L0 10z" class="arrhead"></path></marker
>
<marker id="ra-arr-sky" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"
><path d="M0 0L10 5L0 10z" class="arrhead-sky"></path></marker
>
</defs>
<!-- channel and region queue -->
<line x1="260" y1="58" x2="460" y2="58" class="chan"></line>
<text x="360" y="48" text-anchor="middle" class="sub">channel "data"</text>
<g class="queue">
<rect x="262" y="104" width="196" height="22" rx="2" class="qbox"></rect>
<path d="M440 115 H 282" class="qdir" marker-end="url(#ra-arr)"></path>
<text x="360" y="96" text-anchor="middle" class="sub">region queue</text>
</g>
<!-- mappings -->
<line x1="150" y1="140" x2="150" y2="206" class="map map-a"></line>
<line x1="570" y1="140" x2="570" y2="206" class="map map-b"></line>
<!-- region -->
<g class="region">
<rect x="40" y="206" width="640" height="72" rx="2" class="segbox"></rect>
<rect x="40" y="206" width="640" height="72" fill="url(#ra-cells)"></rect>
<text x="40" y="298" class="sub">/dev/shm/fmq_&lt;shmId&gt;_rg_&lt;regionId&gt;</text>
<text x="680" y="298" text-anchor="end" class="sub">unmanaged region · memory of the sampler</text>
</g>
{
blocks.map((x) => (
<g class="rb">
<rect x={x} y="224" width="80" height="36" class="rb-free" />
<rect x={x} y="224" width="80" height="36" class="rb-data" />
<rect x={x} y="224" width="80" height="36" fill="url(#ra-stripes)" class="rb-rel" />
</g>
))
}
<text class="lbl-data sub" x="536" y="247">data</text>
<text class="lbl-rel sub ruby" x="496" y="247">released by the sink</text>
<text class="lbl-free sub mint" x="496" y="247">free again</text>
<path class="hdl" d="M556 140 C 540 180, 500 196, 470 222" marker-end="url(#ra-arr-sky)"></path>
<text class="hdllabel sub sky" x="530" y="196" text-anchor="end">read in place</text>
<!-- processes -->
<g class="proc">
<rect x="40" y="20" width="220" height="120" rx="3"></rect>
<text x="58" y="46" class="name">sampler</text>
<text x="58" y="64" class="sub">creates the region</text>
<text x="58" y="90" class="code" data-slot="a"></text>
<g class="thr thr-a">
<rect x="58" y="104" width="112" height="22" rx="11"></rect>
<text x="114" y="119" text-anchor="middle">ack receiver</text>
</g>
<g class="cb">
<rect x="178" y="104" width="68" height="22" rx="3"></rect>
<text x="212" y="119" text-anchor="middle">callback</text>
</g>
</g>
<g class="proc">
<rect x="460" y="20" width="220" height="120" rx="3"></rect>
<text x="478" y="46" class="name">sink</text>
<text x="478" y="64" class="sub">opens the region</text>
<text x="478" y="90" class="code" data-slot="b"></text>
<g class="thr thr-b">
<rect x="478" y="104" width="100" height="22" rx="11"></rect>
<text x="528" y="119" text-anchor="middle">ack sender</text>
</g>
</g>
<!-- list of released blocks in the sink -->
<g class="list">
<rect x="590" y="108" width="14" height="14" class="lst"></rect>
<rect x="608" y="108" width="14" height="14" class="lst"></rect>
<rect x="626" y="108" width="14" height="14" class="lst"></rect>
<rect x="644" y="108" width="14" height="14" class="lst"></rect>
</g>
<!-- the bunch on its way through the queue -->
<g class="bunch">
<rect x="590" y="108" width="68" height="14" class="lst"></rect>
<text x="624" y="146" text-anchor="middle" class="sub sky">bunch · ≤ 256 blocks</text>
</g>
<!-- MetaHeaders on the channel -->
<g class="metas">
<rect x="248" y="51" width="14" height="14" class="metabox"></rect>
<rect x="230" y="51" width="14" height="14" class="metabox m2"></rect>
</g>
</svg>
</Explainer>
<style>
.name {
fill: var(--fmq-stage-ink);
font-size: 16px;
font-weight: 700;
}
.sub {
fill: var(--fmq-stage-dim);
font-size: 11.5px;
}
.code {
fill: var(--fmq-saffron);
font-size: 11.5px;
font-weight: 600;
}
.sky {
fill: var(--fmq-sky-bright);
}
.mint {
fill: var(--fmq-mint);
font-weight: 700;
}
.ruby {
fill: var(--fmq-ruby);
font-weight: 700;
}
.proc > rect {
fill: var(--fmq-stage-2);
stroke: var(--fmq-stage-line);
stroke-width: 1.2;
}
.chan {
stroke: var(--fmq-stage-line);
stroke-width: 1.5;
}
.qbox {
fill: var(--fmq-stage-2);
stroke: var(--fmq-stage-line);
}
.qdir {
stroke: var(--fmq-stage-line);
stroke-width: 1.2;
fill: none;
}
.arrhead {
fill: var(--fmq-stage-line);
}
.map {
stroke: var(--fmq-stage-line);
stroke-dasharray: 4 4;
stroke-width: 1.2;
}
.segbox {
fill: var(--fmq-stage-2);
stroke: var(--fmq-stage-line);
}
.cell {
stroke: var(--fmq-stage-cell);
stroke-width: 1;
}
.stripe {
fill: var(--fmq-ruby);
opacity: 0.55;
}
.rb-free {
fill: none;
stroke: var(--fmq-stage-line);
stroke-dasharray: 3 3;
}
.rb-data {
fill: var(--fmq-saffron);
}
.rb-rel {
stroke: var(--fmq-ruby);
stroke-width: 1.5;
}
.thr rect {
fill: none;
stroke: var(--fmq-sky-bright);
stroke-width: 1.2;
}
.thr text,
.cb text {
font-size: 10.5px;
font-weight: 600;
fill: var(--fmq-sky-bright);
}
.cb rect {
fill: none;
stroke: var(--fmq-stage-line);
stroke-width: 1.2;
transition:
fill 0.4s,
stroke 0.4s;
}
.cb text {
fill: var(--fmq-stage-dim);
transition: fill 0.4s;
}
.ra.now7 .cb rect {
fill: var(--fmq-saffron);
stroke: var(--fmq-saffron);
}
.ra.now7 .cb text {
fill: var(--fmq-on-saffron);
}
.lst {
fill: var(--fmq-ruby);
}
.metabox {
fill: var(--fmq-sky-bright);
}
.hdl {
fill: none;
stroke: var(--fmq-sky-bright);
stroke-width: 1.6;
stroke-dasharray: 5 4;
}
.arrhead-sky {
fill: var(--fmq-sky-bright);
}
/* Choreography. Hidden first, then shown by step. */
.region,
.map-a,
.thr-a,
.cb,
.rb,
.map-b,
.thr-b,
.hdl,
.hdllabel,
.lbl-data,
.lbl-rel,
.lbl-free,
.list,
.bunch,
.metas,
.rb-data,
.rb-rel {
opacity: 0;
transition: opacity 0.5s;
}
.ra.r1 .region,
.ra.r1 .map-a,
.ra.r1 .thr-a,
.ra.r1 .cb,
.ra.r1 .rb {
opacity: 1;
}
.ra.r2 .rb-data,
.ra.now2 .lbl-data,
.ra.now3 .lbl-data,
.ra.now4 .lbl-data {
opacity: 1;
}
.metas {
transform: translate(0, 0);
transition:
transform 1.6s cubic-bezier(0.45, 0, 0.2, 1),
opacity 0.35s;
}
.ra.now3 .metas {
opacity: 1;
transform: translate(196px, 0);
}
.ra.r4 .map-b,
.ra.r4 .thr-b,
.ra.now4 .hdl,
.ra.now4 .hdllabel {
opacity: 1;
}
.ra.r5 .rb-rel,
.ra.now5 .lbl-rel,
.ra.now6 .lbl-rel,
.ra.now7 .lbl-rel,
.ra.now5 .list {
opacity: 1;
}
.bunch {
transform: translate(0, 0);
transition:
transform 1.8s cubic-bezier(0.45, 0, 0.2, 1),
opacity 0.35s;
}
.ra.now6 .bunch {
opacity: 1;
transform: translate(-216px, 0);
}
.ra.now7 .bunch {
opacity: 1;
transform: translate(-330px, 0);
}
.ra.r8 .rb-data,
.ra.r8 .rb-rel {
opacity: 0;
}
.ra.now8 .lbl-free {
opacity: 1;
}
@media (prefers-reduced-motion: reduce) {
.ra * {
transition: none !important;
}
}
</style>

View File

@@ -0,0 +1,162 @@
---
// The shared memory objects of one session. Names: fairmq/shmem/Common.h (MakeShmName) and the
// callers in Manager.h, UnmanagedRegion.h and Monitor.cxx. Sizes: kManagementSegmentSize,
// --shm-segment-size, RegionConfig::rcSegmentSize.
const rows = [
{ name: 'fmq_eca859e3_mng', kind: 'management segment', size: '6.25 MiB', w: 18, what: 'The session info, the heartbeat, the counters of devices, events and automatic region IDs, and the lists of segments and regions.' },
{ name: 'fmq_eca859e3_m_0', kind: 'managed segment', size: '--shm-segment-size, 2 GiB', w: 100, what: 'The buffers of NewMessage(). More segments are possible: _m_1, _m_2 …', accent: true },
{ name: 'fmq_eca859e3_rg_<id>', kind: 'unmanaged region', size: 'size from the creator', w: 60, what: 'Memory that a device creates with NewUnmanagedRegion() and fills itself.', accent: true },
{ name: 'fmq_eca859e3_rrc_<id>', kind: 'reference counts', size: 'rcSegmentSize, 100 MB', w: 34, what: 'The reference counts of copied region messages. It exists only if rcSegmentSize is more than 0.' },
{ name: 'fmq_eca859e3_rgq_<id>', kind: 'message queue', size: '1024 bunches of up to 6 KiB', w: 18, what: 'The acknowledgements of region blocks, back to the creator of the region.' },
{ name: 'sem.fmq_eca859e3_ms', kind: 'named mutex', size: '', w: 2, what: 'fairmq-shmmonitor creates it. It shows that a monitor runs for the session.' },
];
---
<figure class="fmq-map not-content">
<div class="map-id">
<span>user ID <code>1000</code></span>
<span class="op">+</span>
<span>session <code>default</code></span>
<span class="op">→ SHA-256 → first 4 bytes →</span>
<span>shmId <code class="hl">eca859e3</code></span>
</div>
<ol class="map-rows">
{
rows.map((r) => (
<li class={r.accent ? 'accent' : ''}>
<div class="map-name">
<code>/dev/shm/{r.name}</code>
<span class="map-kind">{r.kind}</span>
</div>
<div class="map-bar" aria-hidden="true">
<i style={`width:${r.w}%`} />
</div>
<p class="map-what">
{r.what} {r.size && <span class="map-size">{r.size}</span>}
</p>
</li>
))
}
</ol>
<figcaption>
All devices with the same session name and the same user open the same objects. The last device that leaves removes them, unless <code>--shm-no-cleanup</code> is true. It does not remove the
mutex of the monitor. A region with a path is a file in that path, not an object in <code>/dev/shm</code>. Bars show the size only roughly.
</figcaption>
</figure>
<style>
.fmq-map {
margin: 1.5rem 0;
border: 1px solid var(--fmq-rule);
border-radius: 6px;
background: var(--fmq-paper);
overflow: hidden;
}
.map-id {
display: flex;
flex-wrap: wrap;
gap: 0.35rem 0.6rem;
align-items: baseline;
padding: 0.75rem 1rem;
background: var(--fmq-paper-2);
border-bottom: 1px solid var(--fmq-rule);
font-size: 0.875rem;
color: var(--fmq-ink-2);
}
.map-id .op {
color: var(--fmq-ink-3);
font-size: 0.8125rem;
}
code {
font-family: var(--fmq-font-mono);
font-size: 0.8125rem;
color: var(--fmq-ink);
}
code.hl {
background: var(--fmq-saffron-tint);
border: 1px solid var(--fmq-bar);
border-radius: 3px;
padding: 0 0.3em;
}
.map-rows {
list-style: none;
margin: 0;
padding: 0;
}
.map-rows li {
display: grid;
grid-template-columns: minmax(0, 17rem) minmax(0, 1fr);
gap: 0.25rem 1rem;
padding: 0.65rem 1rem;
border-bottom: 1px solid var(--fmq-rule);
margin: 0;
}
.map-rows li:last-child {
border-bottom: 0;
}
.map-name {
display: flex;
flex-direction: column;
gap: 0.15rem;
min-width: 0;
}
.map-name code {
font-weight: 600;
overflow-wrap: anywhere;
}
.map-kind {
font: 600 0.66rem/1.3 var(--fmq-font-body);
letter-spacing: 0.1em;
text-transform: uppercase;
color: var(--fmq-ink-3);
}
.map-bar {
grid-column: 2;
grid-row: 1;
align-self: center;
height: 10px;
border: 1px solid var(--fmq-rule-strong);
border-radius: 2px;
background: var(--fmq-paper-2);
}
.map-bar i {
display: block;
height: 100%;
min-width: 3px;
background: var(--fmq-ink-3);
}
.accent .map-bar i {
background: var(--fmq-saffron);
}
.map-what {
grid-column: 2;
margin: 0;
font-size: 0.875rem;
color: var(--fmq-ink-2);
line-height: 1.45;
}
.map-size {
font: 500 0.75rem var(--fmq-font-mono);
color: var(--fmq-ink-3);
white-space: nowrap;
}
figcaption {
font-size: 0.85rem;
color: var(--fmq-ink-3);
padding: 0.6rem 1rem 0.75rem;
border-top: 1px solid var(--fmq-rule);
}
figcaption code {
font-size: 0.8em;
}
@media (max-width: 40rem) {
.map-rows li {
grid-template-columns: minmax(0, 1fr);
}
.map-bar,
.map-what {
grid-column: 1;
grid-row: auto;
}
}
</style>

View File

@@ -0,0 +1,580 @@
---
// Interactive state machine of a FairMQ device.
// The layout follows the diagram that `--control interactive` prints (fairmq/plugins/control/Control.cxx).
// States and transitions come from fairmq/States.h and fairmq/StateMachine.cxx.
const H = 38;
type Kind = 'idle' | 'work' | 'end' | 'error';
const N: Record<string, [number, number, number, Kind]> = {
IDLE: [16, 24, 296, 'idle'],
EXITING: [344, 24, 60, 'end'],
'INITIALIZING DEVICE': [16, 86, 236, 'work'],
'RESETTING DEVICE': [276, 86, 128, 'work'],
INITIALIZED: [16, 148, 236, 'idle'],
BINDING: [16, 210, 236, 'work'],
BOUND: [16, 272, 236, 'idle'],
CONNECTING: [16, 334, 236, 'work'],
'DEVICE READY': [16, 396, 388, 'idle'],
'INITIALIZING TASK': [16, 458, 236, 'work'],
'RESETTING TASK': [276, 458, 128, 'work'],
READY: [16, 520, 388, 'idle'],
RUNNING: [16, 582, 388, 'work'],
ERROR: [16, 652, 388, 'error'],
};
// [from, to, transition, key, path points, label position]
const E: [string, string, string, string, number[][], number[]][] = [
['IDLE', 'INITIALIZING DEVICE', 'InitDevice', 'i', [[134, 62], [134, 86]], [148, 74]],
['IDLE', 'EXITING', 'End', 'q', [[312, 43], [344, 43]], [328, 43]],
['INITIALIZING DEVICE', 'INITIALIZED', 'CompleteInit', '', [[134, 124], [134, 148]], [142, 139]],
['INITIALIZED', 'BINDING', 'Bind', 'b', [[134, 186], [134, 210]], [148, 198]],
['INITIALIZED', 'RESETTING DEVICE', 'ResetDevice', 'd', [[252, 167], [340, 167], [340, 124]], [296, 167]],
['BINDING', 'BOUND', 'Auto', '', [[134, 248], [134, 272]], [142, 263]],
['BOUND', 'CONNECTING', 'Connect', 'x', [[134, 310], [134, 334]], [148, 322]],
['BOUND', 'RESETTING DEVICE', 'ResetDevice', 'd', [[252, 291], [340, 291], [340, 124]], [296, 291]],
['CONNECTING', 'DEVICE READY', 'Auto', '', [[134, 372], [134, 396]], [142, 387]],
['DEVICE READY', 'INITIALIZING TASK', 'InitTask', 'j', [[134, 434], [134, 458]], [148, 446]],
['DEVICE READY', 'RESETTING DEVICE', 'ResetDevice', 'd', [[340, 396], [340, 124]], [354, 382]],
['INITIALIZING TASK', 'READY', 'Auto', '', [[134, 496], [134, 520]], [142, 511]],
['READY', 'RESETTING TASK', 'ResetTask', 't', [[340, 520], [340, 496]], [354, 508]],
['RESETTING TASK', 'DEVICE READY', 'Auto', '', [[340, 458], [340, 434]], [348, 449]],
['READY', 'RUNNING', 'Run', 'r', [[134, 558], [134, 582]], [148, 570]],
['RUNNING', 'READY', 'Stop', 's', [[300, 582], [300, 558]], [314, 570]],
['RESETTING DEVICE', 'IDLE', 'Auto', '', [[296, 86], [296, 62]], [304, 77]],
];
const I: Record<string, [string, string, string]> = {
IDLE: [
'Idling state',
'The state machine starts here. The device has no channels yet. The config plugin reads --mq-config or --channel-config when INITIALIZING DEVICE starts.',
'—',
],
'INITIALIZING DEVICE': [
'Working state',
'The device waits for CompleteInit. A controller can set properties now. Then the device calls Init(), reads rate, init-timeout and transport, and makes the transports and the channels.',
'Init()',
],
INITIALIZED: ['Idling state', 'The configuration is complete and the channels exist. Nothing is bound or connected yet.', '—'],
BINDING: ['Working state', 'The device binds all channels with the method bind. Then it calls Bind().', 'Bind()'],
BOUND: ['Idling state', 'All channels with the method bind have an endpoint.', '—'],
CONNECTING: [
'Working state',
'The device connects all channels with the method connect. If an address is not valid yet, it tries again every 50 ms. After init-timeout (default 120 s), it goes to ERROR. When all channels are connected, it calls Connect().',
'Connect()',
],
'DEVICE READY': ['Idling state', 'All channels are bound or connected.', '—'],
'INITIALIZING TASK': ['Working state', 'The device prepares the task. Read your own options and allocate resources here.', 'InitTask()'],
READY: ['Idling state', 'The task is ready. The device waits for Run.', '—'],
RUNNING: [
'Working state',
'The device calls PreRun(). Then it calls your OnData() callbacks, or it calls ConditionalRun() until it returns false or a transition is pending, and then Run(). If no transition is pending, the device requests Stop. It calls PostRun() and then goes to READY.',
'PreRun() · OnData() or ConditionalRun() and Run() · PostRun()',
],
'RESETTING TASK': ['Working state', 'The device calls ResetTask(). Undo the work of InitTask() here.', 'ResetTask()'],
'RESETTING DEVICE': ['Working state', 'The device resets and removes its transports, calls Reset(), and removes all channels.', 'Reset()'],
EXITING: ['Final state', 'The state machine stops. The device process can end.', '—'],
ERROR: [
'Error state',
'An exception in a hook, or the transition ErrorFound, moves the device here. No transition leaves ERROR. The controller stops without the shutdown sequence, so ResetTask() and Reset() do not run. The process ends with the exit code 1.',
'—',
],
};
const data = JSON.stringify({ N, E: E.map(([f, t, n, k]) => [f, t, n, k]), I });
const d = (pts: number[][]) => 'M' + pts.map((p) => p.join(' ')).join(' L');
---
<div class="fmq-sm not-content" data-sm={data}>
<div class="sm-fig">
<svg viewBox="0 0 420 700" role="group" aria-label="State machine of a FairMQ device">
<defs>
<marker id="sm-arr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"
><path d="M0 0L10 5L0 10z" class="sm-ah"></path></marker
>
<marker id="sm-arr-on" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"
><path d="M0 0L10 5L0 10z" class="sm-ah-on"></path></marker
>
</defs>
<g>
{E.map((e, i) => <path d={d(e[4])} class="sm-e" marker-end="url(#sm-arr)" data-edge={i} />)}
</g>
<g>
{
Object.entries(N).map(([name, [x, y, w, k]]) => (
<g class={`sm-n sm-${k}`} tabindex="0" role="button" aria-label={`${name}: show details`} data-state={name}>
<rect x={x} y={y} width={w} height={H} rx="2" />
{k === 'work' && <rect x={x + 3} y={y + 3} width={w - 6} height={H - 6} rx="1" class="sm-inner" />}
<text x={x + w / 2} y={y + H / 2 + 4} text-anchor="middle">
{name}
</text>
</g>
))
}
</g>
<g aria-hidden="true">
<text x="210" y="643" text-anchor="middle" class="sm-auto">any state → ERROR on ErrorFound</text>
{
E.map((e) => {
const [x, y] = e[5];
return e[3] ? (
<g class="sm-key">
<rect x={x - 7} y={y - 7} width="14" height="14" rx="2" />
<text x={x} y={y + 3.5} text-anchor="middle">
{e[3]}
</text>
</g>
) : (
<text x={x} y={y} class="sm-auto">
{e[2] === 'Auto' ? 'auto' : e[2]}
</text>
);
})
}
</g>
</svg>
</div>
<div class="sm-side">
<div class="sm-panel">
<div class="sm-ph">
<div class="sm-kind"><i></i><span data-kind>Idling state</span></div>
<p class="sm-name" data-name>IDLE</p>
</div>
<div class="sm-body">
<p class="sm-h">What happens</p>
<p data-does>{I.IDLE[1]}</p>
<p class="sm-h">Your code</p>
<p class="sm-hook" data-hook>—</p>
<p class="sm-h">Leave with</p>
<div class="sm-leave" data-leave></div>
</div>
<div class="sm-ctrl" data-ctrl></div>
<pre class="sm-log" aria-live="polite" data-log></pre>
</div>
<p class="sm-tip">
Select a state to read about it. The buttons and the keys <kbd>i</kbd>
<kbd>b</kbd>
<kbd>x</kbd>
<kbd>j</kbd>
<kbd>r</kbd>
<kbd>s</kbd>
<kbd>t</kbd>
<kbd>d</kbd>
<kbd>q</kbd> work like the interactive controller (<code>--control interactive</code>). <kbd>q</kbd> runs the shutdown sequence (Stop, ResetTask, ResetDevice, End) from RUNNING and from each idling state. <kbd>c</kbd> prints the current state.
</p>
</div>
</div>
<script>
for (const root of document.querySelectorAll<HTMLElement>('.fmq-sm')) {
const { N, E, I } = JSON.parse(root.dataset.sm!);
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
const $ = <T extends HTMLElement>(s: string) => root.querySelector<T>(s)!;
const nodes = new Map<string, SVGGElement>();
root.querySelectorAll<SVGGElement>('[data-state]').forEach((g) => nodes.set(g.dataset.state!, g));
const edges = [...root.querySelectorAll<SVGPathElement>('[data-edge]')];
const log = $('[data-log]');
const ctrl = $('[data-ctrl]');
let cur = 'IDLE';
let sel = 'IDLE';
let busy = false;
let stopping = false;
let timer = 0;
// The key q of the controller runs the shutdown sequence from each state (Control.cxx RunShutdownSequence()).
// In this diagram, q works in RUNNING and in the idling states.
const SHUT: Record<string, string> = {
RUNNING: 'Stop',
READY: 'ResetTask',
'DEVICE READY': 'ResetDevice',
BOUND: 'ResetDevice',
INITIALIZED: 'ResetDevice',
IDLE: 'End',
};
const step = () => {
const e = outs(cur).find((x: string[]) => x[2] === SHUT[cur]);
if (!e) {
stopping = false;
render();
return;
}
timer = window.setTimeout(() => go(e[1]), reduce ? 250 : 650);
};
const shutdown = () => {
if (busy || stopping || !SHUT[cur]) return;
stopping = true;
render();
step();
};
const esc = (s: string) => s.replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]!);
const write = (s: string, sev = 'STATE') => {
const div = document.createElement('div');
div.innerHTML = `<span class="${sev === 'STATE' ? 'st' : 'er'}">[${sev}]</span> ${esc(s)}`;
log.appendChild(div);
while (log.children.length > 12) log.firstChild!.remove();
log.scrollTop = log.scrollHeight;
};
const outs = (s: string) => E.filter((e: string[]) => e[0] === s);
const go = (to: string) => {
write(`${cur} ---> ${to}`);
cur = to;
sel = to;
const o = outs(cur);
busy = o.length === 1 && (o[0][2] === 'Auto' || o[0][2] === 'CompleteInit');
render();
if (busy) {
timer = window.setTimeout(() => {
busy = false;
go(o[0][1]);
}, reduce ? 250 : 950);
} else if (stopping) step();
};
const act = (e: string[]) => {
if (!busy && !stopping) go(e[1]);
};
const render = () => {
nodes.forEach((g, n) => {
g.classList.toggle('cur', n === cur);
g.classList.toggle('sel', n === sel && n !== cur);
g.setAttribute('aria-pressed', String(n === sel));
});
E.forEach((e: string[], i: number) => {
const live = e[0] === cur;
edges[i].classList.toggle('live', live);
edges[i].setAttribute('marker-end', live ? 'url(#sm-arr-on)' : 'url(#sm-arr)');
});
const [kind, does, hook] = I[sel];
$('[data-kind]').textContent = kind;
root.querySelector('.sm-kind i')!.className = N[sel][3] === 'work' ? 'work' : '';
$('[data-name]').textContent = sel;
$('[data-does]').textContent = does;
$('[data-hook]').textContent = hook;
const lv = outs(sel);
$('[data-leave]').innerHTML = lv.length
? lv.map((e: string[]) => `<span>${e[3] ? `<kbd>${e[3]}</kbd>` : ''}${e[2]} → ${e[1]}</span>`).join('')
: '<span>none</span>';
const lock = busy || stopping ? ' disabled' : '';
let h = `<span class="now">Device: <b>${cur}</b>${busy ? ' · working' : stopping ? ' · shutting down' : ''}</span>`;
outs(cur)
.filter((e: string[]) => e[2] !== 'Auto' && e[2] !== 'CompleteInit')
.forEach((e: string[]) => {
h += `<button class="sm-btn" type="button" data-e="${E.indexOf(e)}"${lock}><kbd>${e[3]}</kbd>${e[2]}</button>`;
});
if (cur !== 'IDLE' && SHUT[cur]) h += `<button class="sm-btn" type="button" data-q="1"${lock}><kbd>q</kbd>Shut down</button>`;
if (cur !== 'EXITING' && cur !== 'ERROR')
h += `<button class="sm-btn warn" type="button" data-err="1"${lock}>Throw in a hook</button>`;
else h += '<button class="sm-btn" type="button" data-reset="1">Start again</button>';
ctrl.innerHTML = h;
};
const reset = () => {
clearTimeout(timer);
busy = false;
stopping = false;
log.innerHTML = '';
cur = 'IDLE';
sel = 'IDLE';
write('Starting FairMQ state machine --> IDLE');
render();
};
ctrl.addEventListener('click', (ev) => {
const b = (ev.target as HTMLElement).closest('button');
if (!b) return;
if (b.dataset.e) act(E[Number(b.dataset.e)]);
else if (b.dataset.q) shutdown();
else if (b.dataset.err) {
clearTimeout(timer);
busy = false;
stopping = false;
// An exception in a hook sets ERROR without a [STATE] line (StateMachine.cxx ProcessWork()).
// The exception reaches DeviceRunner, which logs it.
cur = 'ERROR';
sel = 'ERROR';
render();
write('Uncaught exception reached the top of DeviceRunner: <what()>', 'ERROR');
} else if (b.dataset.reset) reset();
});
nodes.forEach((g, n) => {
g.addEventListener('click', () => {
sel = n;
render();
});
g.addEventListener('keydown', (ev) => {
if (ev.key === 'Enter' || ev.key === ' ') {
ev.preventDefault();
sel = n;
render();
}
});
});
root.addEventListener('keydown', (ev) => {
if ((ev.target as HTMLElement).closest('input,textarea') || ev.ctrlKey || ev.metaKey || ev.altKey) return;
const k = ev.key.toLowerCase();
if (k === 'c') {
write(cur);
return;
}
if (k === 'q') {
ev.preventDefault();
shutdown();
return;
}
const m = outs(cur).find((x: string[]) => x[3] === k);
if (m) {
ev.preventDefault();
act(m);
}
});
reset();
}
</script>
<style>
.fmq-sm {
display: grid;
grid-template-columns: minmax(0, 26rem) minmax(0, 1fr);
gap: 1.25rem;
align-items: start;
margin-block: 1.5rem;
}
@media (max-width: 52rem) {
.fmq-sm {
grid-template-columns: minmax(0, 1fr);
}
}
.sm-fig {
border: 1px solid var(--fmq-rule);
border-radius: 4px;
background: var(--fmq-paper);
padding: 0.5rem;
}
svg {
width: 100%;
height: auto;
display: block;
}
.sm-n {
cursor: pointer;
outline: none;
}
.sm-n rect {
fill: var(--fmq-paper);
stroke: var(--fmq-ink-3);
stroke-width: 1.2;
transition: fill 0.25s, stroke 0.25s;
}
.sm-n rect.sm-inner {
fill: none;
stroke-width: 1;
}
.sm-n text {
font: 600 10.5px var(--fmq-font-mono);
letter-spacing: 0.04em;
fill: var(--fmq-ink);
pointer-events: none;
}
.sm-n:hover rect:first-of-type,
.sm-n:focus-visible rect:first-of-type {
stroke: var(--fmq-link);
stroke-width: 2;
}
.sm-n.sel rect:first-of-type {
stroke: var(--fmq-ink);
stroke-width: 2.2;
}
.sm-n.cur rect:first-of-type {
fill: var(--fmq-saffron);
stroke: var(--fmq-bar);
}
.sm-n.cur rect.sm-inner {
stroke: var(--fmq-bar);
}
.sm-n.cur text {
fill: var(--fmq-on-saffron);
}
.sm-error rect:first-of-type {
stroke: var(--fmq-ruby);
}
.sm-end rect:first-of-type {
stroke-dasharray: 3 3;
}
.sm-e {
fill: none;
stroke: var(--fmq-rule-strong);
stroke-width: 1.2;
transition: stroke 0.25s;
}
.sm-e.live {
stroke: var(--fmq-ink);
stroke-width: 1.8;
stroke-dasharray: 5 4;
animation: smdash 1s linear infinite;
}
@keyframes smdash {
to {
stroke-dashoffset: -18;
}
}
.sm-ah {
fill: var(--fmq-rule-strong);
}
.sm-ah-on {
fill: var(--fmq-ink);
}
.sm-key rect {
fill: var(--fmq-paper-2);
stroke: var(--fmq-rule-strong);
}
.sm-key text {
font: 600 9.5px var(--fmq-font-mono);
fill: var(--fmq-ink);
}
.sm-auto {
font: italic 400 9.5px var(--fmq-font-mono);
fill: var(--fmq-ink-3);
}
.sm-panel {
border: 1px solid var(--fmq-rule);
border-radius: 4px;
background: var(--fmq-paper);
min-width: 0;
}
.sm-ph {
padding: 0.85rem 1rem 0.75rem;
border-bottom: 1px solid var(--fmq-rule);
}
.sm-kind {
font: 600 0.66rem/1.2 var(--fmq-font-body);
letter-spacing: 0.12em;
text-transform: uppercase;
color: var(--fmq-ink-3);
display: flex;
align-items: center;
gap: 0.5rem;
}
.sm-kind i {
width: 14px;
height: 10px;
border: 1px solid var(--fmq-ink-3);
}
.sm-kind i.work {
outline: 1px solid var(--fmq-ink-3);
outline-offset: 2px;
width: 10px;
height: 6px;
margin: 0 2px;
}
.sm-name {
font: 800 1.3rem/1.15 var(--fmq-font-body);
font-stretch: 108%;
margin: 0.35rem 0 0;
letter-spacing: -0.01em;
color: var(--fmq-ink);
}
.sm-body {
padding: 0.6rem 1rem 0.85rem;
font-size: 0.9rem;
}
.sm-body p {
margin: 0;
}
.sm-h {
font: 600 0.66rem/1.2 var(--fmq-font-body);
letter-spacing: 0.12em;
text-transform: uppercase;
color: var(--fmq-ink-3);
margin: 0.75rem 0 0.25rem !important;
}
.sm-hook {
font: 600 0.8125rem/1.5 var(--fmq-font-mono);
color: var(--fmq-accent-ink);
}
.sm-leave {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
}
.sm-leave :global(span) {
font: 500 0.75rem/1 var(--fmq-font-mono);
border: 1px solid var(--fmq-rule);
border-radius: 3px;
padding: 0.3rem 0.45rem;
color: var(--fmq-ink-2);
display: inline-flex;
gap: 0.35rem;
align-items: center;
}
.sm-ctrl {
padding: 0.75rem 1rem;
border-top: 1px solid var(--fmq-rule);
background: var(--fmq-paper-2);
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
}
.sm-ctrl :global(.now) {
font: 600 0.75rem/1.2 var(--fmq-font-mono);
color: var(--fmq-ink-2);
flex-basis: 100%;
}
.sm-ctrl :global(.now b) {
color: var(--fmq-ink);
}
.sm-ctrl :global(.sm-btn) {
display: inline-flex;
align-items: center;
gap: 0.45rem;
font: 500 0.8125rem/1 var(--fmq-font-body);
padding: 0.45rem 0.6rem;
border: 1px solid var(--fmq-rule-strong);
border-radius: 4px;
background: var(--fmq-paper);
color: var(--fmq-ink);
cursor: pointer;
}
.sm-ctrl :global(.sm-btn:hover) {
border-color: var(--fmq-ink-3);
}
.sm-ctrl :global(.sm-btn:disabled) {
opacity: 0.5;
cursor: default;
}
.sm-ctrl :global(.sm-btn.warn) {
color: var(--fmq-ruby);
}
.fmq-sm :global(kbd) {
display: inline-grid;
place-items: center;
min-width: 18px;
height: 18px;
font: 600 0.65rem/1 var(--fmq-font-mono);
border: 1px solid var(--fmq-rule-strong);
border-bottom-width: 2px;
border-radius: 3px;
background: var(--fmq-paper-2);
color: var(--fmq-ink);
padding: 0 4px;
}
.sm-log {
margin: 0;
padding: 0.6rem 0.75rem;
background: var(--fmq-code-bg);
color: var(--fmq-code-ink);
font: 400 0.75rem/1.6 var(--fmq-font-mono);
border-radius: 0 0 4px 4px;
height: 7.4rem;
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
border: 0;
}
.sm-log :global(.st) {
color: var(--fmq-c-kw);
}
.sm-log :global(.er) {
color: var(--fmq-c-num);
}
.sm-tip {
font-size: 0.8125rem;
color: var(--fmq-ink-3);
margin: 0.5rem 0.1rem 0;
line-height: 1.9;
}
.sm-tip code {
font-size: 0.8em;
}
</style>

View File

@@ -0,0 +1,348 @@
---
// A topology like example 1-n-1, animated: a sampler, three processors and a sink.
// (The start script of example 1-n-1 runs two processors.)
// The switch shows what the shmem transport changes: only a MetaHeader goes through each socket.
---
<div class="fmq-topo not-content">
<div class="tp-head">
<div class="tp-switch" role="group" aria-label="Transport">
<button type="button" data-mode="zeromq" aria-pressed="true">zeromq</button>
<button type="button" data-mode="shmem" aria-pressed="false">shmem</button>
</div>
<span>1 sampler · 3 processors · 1 sink</span>
</div>
<svg class="tp" viewBox="0 0 560 296" role="img" aria-label="A sampler sends messages round-robin to three processors. The processors send them to a sink.">
<g class="tp-edges">
<path d="M130 140 H178 V62 H225"></path><path d="M130 140 H225"></path><path d="M130 140 H178 V218 H225"></path>
<path d="M335 62 H382 V140 H430"></path><path d="M335 140 H430"></path><path d="M335 218 H382 V140 H430"></path>
</g>
<g class="tp-seg">
<rect x="20" y="260" width="520" height="28"></rect>
<text x="22" y="254" class="tp-addr">shared memory segment · session "default"</text>
</g>
<g class="tp-blocks"></g>
<g class="tp-dev">
<rect x="20" y="112" width="110" height="56"></rect>
<rect class="tp-port" x="126" y="136" width="8" height="8"></rect>
<text x="32" y="136" class="tp-name">sampler</text>
<text x="32" y="154" class="tp-sub">push · bind</text>
</g>
<g class="tp-dev">
{
[40, 118, 196].map((y, i) => (
<>
<rect x="225" y={y} width="110" height="44" class="tp-proc" data-p={i} />
<rect class="tp-port" x="221" y={y + 18} width="8" height="8" />
<rect class="tp-port" x="331" y={y + 18} width="8" height="8" />
<text x="238" y={y + 20} class="tp-name">
processor
</text>
<text x="238" y={y + 35} class="tp-sub">
pull → push
</text>
</>
))
}
</g>
<g class="tp-dev">
<rect x="430" y="112" width="110" height="56"></rect>
<rect class="tp-port" x="426" y="136" width="8" height="8"></rect>
<text x="442" y="136" class="tp-name">sink</text>
<text x="442" y="154" class="tp-sub">pull · bind</text>
</g>
<text x="22" y="104" class="tp-addr">tcp://*:5555</text>
<text x="538" y="104" text-anchor="end" class="tp-addr">tcp://*:5556</text>
<g class="tp-parts"></g>
</svg>
<p class="tp-cap" aria-live="polite">zeromq: the payload goes through each socket.</p>
</div>
<script>
for (const root of document.querySelectorAll<HTMLElement>('.fmq-topo')) {
const svg = root.querySelector<SVGSVGElement>('svg.tp')!;
const NS = 'http://www.w3.org/2000/svg';
const parts = svg.querySelector('.tp-parts')!;
const blocks = svg.querySelector('.tp-blocks')!;
const cap = root.querySelector('.tp-cap')!;
const buttons = [...root.querySelectorAll<HTMLButtonElement>('[data-mode]')];
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
// A route: segments with start time and duration. The hop through the processor is slow.
const mk = (pts: number[][], slow: number) => {
const segs: { x1: number; y1: number; x2: number; y2: number; t0: number; d: number; slow: boolean }[] = [];
let T = 0;
for (let i = 1; i < pts.length; i++) {
const [x1, y1] = pts[i - 1];
const [x2, y2] = pts[i];
const l = Math.hypot(x2 - x1, y2 - y1);
if (l < 0.5) continue;
const d = l / (i - 1 === slow ? 58 : 170);
segs.push({ x1, y1, x2, y2, t0: T, d, slow: i - 1 === slow });
T += d;
}
return { segs, T };
};
const routes = [62, 140, 218].map((py) =>
mk(
[
[130, 140],
[178, 140],
[178, py],
[225, py],
[335, py],
[382, py],
[382, 140],
[430, 140],
],
3
)
);
type Route = (typeof routes)[number];
// Position at time t, and whether the message is inside the processor.
const at = (r: Route, t: number): [number, number, boolean] => {
for (const s of r.segs) {
if (t <= s.t0 + s.d) {
const u = (t - s.t0) / s.d;
return [s.x1 + (s.x2 - s.x1) * u, s.y1 + (s.y2 - s.y1) * u, s.slow];
}
}
const s = r.segs[r.segs.length - 1];
return [s.x2, s.y2, false];
};
const procs = [...svg.querySelectorAll<SVGRectElement>('.tp-proc')];
const busy = [0, 0, 0];
type Part = { r: Route; p: number; t: number; e: SVGRectElement; s: number; blk: SVGRectElement | null; slot: number; inside: boolean };
let mode = 'zeromq';
let list: Part[] = [];
let last = 0;
let acc = 0;
let rr = 0;
let running = false;
let raf = 0;
const slots = new Array(16).fill(false);
const rect = (a: Record<string, string | number>, p: Element) => {
const e = document.createElementNS(NS, 'rect');
for (const k in a) e.setAttribute(k, String(a[k]));
p.appendChild(e);
return e;
};
const setInside = (p: Part, inside: boolean) => {
if (p.inside === inside) return;
p.inside = inside;
busy[p.p] += inside ? 1 : -1;
procs[p.p].classList.toggle('busy', busy[p.p] > 0);
p.e.style.visibility = inside ? 'hidden' : '';
};
const place = (p: Part) => {
const [x, y, inside] = at(p.r, p.t);
p.e.setAttribute('x', (x - p.s / 2).toFixed(1));
p.e.setAttribute('y', (y - p.s / 2).toFixed(1));
setInside(p, inside);
};
const spawn = (t0 = 0) => {
const r = routes[rr];
const pi = rr;
rr = (rr + 1) % 3;
const shm = mode === 'shmem';
const s = shm ? 6 : 10;
let blk: SVGRectElement | null = null;
let slot = -1;
if (shm) {
slot = slots.indexOf(false);
if (slot < 0) return;
slots[slot] = true;
blk = rect({ x: 28 + slot * 32, y: 267, width: 24, height: 14, class: 'tp-blk' }, blocks);
}
const e = rect({ width: s, height: s, class: shm ? 'tp-meta' : 'tp-pay' }, parts);
const p: Part = { r, p: pi, t: t0, e, s, blk, slot, inside: false };
place(p);
list.push(p);
};
const clear = () => {
list.forEach((p) => {
setInside(p, false);
p.e.remove();
p.blk?.remove();
});
list = [];
slots.fill(false);
blocks.replaceChildren();
};
const frame = (ts: number) => {
if (!running) return;
const dt = Math.min(0.05, (ts - (last || ts)) / 1000);
last = ts;
acc += dt;
if (acc > 0.55) {
acc = 0;
spawn();
}
list.forEach((p) => {
p.t += dt;
place(p);
});
list = list.filter((p) => {
if (p.t < p.r.T) return true;
setInside(p, false);
p.e.remove();
if (p.blk) {
const b = p.blk;
const sl = p.slot;
b.style.opacity = '0';
setTimeout(() => {
b.remove();
slots[sl] = false;
}, 420);
}
return false;
});
raf = requestAnimationFrame(frame);
};
const still = () => {
clear();
[0.5, 1.4, 2.2, 2.9, 3.5, 1.0].forEach((t) => spawn(t));
};
const setMode = (m: string) => {
mode = m;
svg.classList.toggle('shm', m === 'shmem');
buttons.forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.mode === m)));
clear();
cap.textContent =
m === 'shmem'
? 'shmem: the payload stays in the shared memory segment. Only a MetaHeader of 40 bytes goes through each socket.'
: 'zeromq: the payload goes through each socket.';
if (reduce || !running) still();
};
buttons.forEach((b) => b.addEventListener('click', () => setMode(b.dataset.mode!)));
still();
if (!reduce && 'IntersectionObserver' in window) {
new IntersectionObserver(
(es) => {
for (const e of es) {
if (e.isIntersecting && !running) {
clear();
running = true;
last = 0;
raf = requestAnimationFrame(frame);
} else if (!e.isIntersecting && running) {
running = false;
cancelAnimationFrame(raf);
}
}
},
{ threshold: 0.2 }
).observe(svg);
}
}
</script>
<style>
.fmq-topo {
min-width: 0;
border: 1px solid var(--fmq-rule);
background: var(--fmq-paper);
border-radius: 6px;
padding: 0.75rem 0.75rem 0.6rem;
}
.tp-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.6rem;
flex-wrap: wrap;
}
.tp-head span {
font-size: 0.78rem;
color: var(--fmq-ink-3);
}
.tp-switch {
display: inline-flex;
border: 1px solid var(--fmq-rule-strong);
border-radius: 4px;
overflow: hidden;
}
.tp-switch button {
font: 600 0.78rem/1 var(--fmq-font-mono);
border: 0;
background: var(--fmq-paper);
color: var(--fmq-ink-2);
padding: 0.5rem 0.9rem;
cursor: pointer;
}
.tp-switch button + button {
border-inline-start: 1px solid var(--fmq-rule-strong);
}
.tp-switch button[aria-pressed='true'] {
background: var(--fmq-ink);
color: var(--fmq-paper);
}
svg {
width: 100%;
height: auto;
display: block;
margin-top: 0.4rem;
}
.tp-edges path {
fill: none;
stroke: var(--fmq-rule-strong);
stroke-width: 1.4;
}
.tp-dev rect {
fill: var(--fmq-paper);
stroke: var(--fmq-ink-2);
stroke-width: 1.2;
}
.tp-dev rect.tp-port {
fill: var(--fmq-ink-2);
}
.tp-dev rect.tp-proc {
transition:
fill 0.2s,
stroke 0.2s;
}
.tp-dev rect.tp-proc:global(.busy) {
fill: var(--fmq-saffron-tint);
stroke: var(--fmq-bar);
}
.tp-name {
font: 600 12.5px var(--fmq-font-mono);
fill: var(--fmq-ink);
}
.tp-sub,
.tp-addr {
font: 400 10.5px var(--fmq-font-mono);
fill: var(--fmq-ink-3);
}
.tp-seg {
opacity: 0;
transition: opacity 0.4s;
}
.tp-seg rect {
fill: var(--fmq-paper-2);
stroke: var(--fmq-rule-strong);
stroke-dasharray: 3 3;
}
svg.shm .tp-seg {
opacity: 1;
}
.tp-parts :global(.tp-pay) {
fill: var(--fmq-saffron);
stroke: var(--fmq-bar);
stroke-width: 1;
}
.tp-parts :global(.tp-meta) {
fill: var(--fmq-sky);
}
.tp-blocks :global(.tp-blk) {
fill: var(--fmq-saffron);
stroke: var(--fmq-bar);
stroke-width: 1;
transition: opacity 0.4s;
}
.tp-cap {
margin: 0.4rem 0.15rem 0;
font-size: 0.85rem;
color: var(--fmq-ink-2);
min-height: 2.8em;
}
</style>

View File

@@ -0,0 +1,274 @@
---
// One message through the shmem transport, step by step.
// Facts: fairmq/shmem/Common.h (MetaHeader, MakeShmName, makeShmIdStr), Socket.h (Send, Receive),
// Message.h (Deallocate), plugins/config/Config.cxx (--shm-segment-size default 2 GiB).
import Explainer from './Explainer.astro';
const steps = [
{
cap: 'Two devices run on one host. Both map the same managed segment. FairMQ makes the name of the segment from the session name and the user ID.',
code: '--transport shmem --session default',
},
{
cap: 'The sampler asks for a message of 1 MiB. The transport allocates a block in the segment.',
code: 'auto msg = NewMessage(1 << 20);',
set: { a: 'NewMessage(1 << 20)' },
},
{
cap: 'The sampler writes the payload into the block. The payload stays in the segment.',
code: 'std::memcpy(msg->GetData(), src, msg->GetSize());',
set: { a: 'write the payload' },
},
{
cap: 'Send() puts only a MetaHeader of 40 bytes into a ZeroMQ message. It holds the size, the hint, the handle of the block, the handle of the reference count of a copied region block, the IDs of the region and the segment, and a flag for segment or region. The message of the sampler no longer owns the block.',
code: 'Send(msg, "data");',
set: { a: 'Send(msg, "data")' },
},
{
cap: 'The sink receives the MetaHeader. At the first GetData(), it changes the handle into an address in its own mapping of the segment.',
code: 'Receive(msg, "data");',
set: { b: 'Receive(msg, "data")' },
},
{
cap: 'The sink reads the payload in place. The transport copied no byte of the payload.',
code: 'auto* data = static_cast<char*>(msg->GetData());',
set: { b: 'msg->GetData()' },
},
{
cap: 'The message of the sink goes out of scope. The transport gives the block back to the segment.',
code: '} // msg is destroyed: the block is free again',
set: { b: '~Message()' },
},
{
cap: 'Compare: with the zeromq transport, the full payload goes through the socket on each hop.',
code: '--transport zeromq',
set: { a: 'Send(msg, "data")', b: 'Receive(msg, "data")' },
},
];
---
<Explainer title="One message, no copy" meta="sampler → sink · same host" steps={steps}>
<svg class="zc" data-stage viewBox="0 0 720 318" role="img" aria-label="Zero-copy transfer with the shmem transport">
<defs>
<pattern id="zc-cells" width="16" height="76" patternUnits="userSpaceOnUse"><line x1="0.5" y1="0" x2="0.5" y2="76" class="cell"></line></pattern>
<pattern id="zc-stripes" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="3" height="8" class="stripe"></rect></pattern>
<marker id="zc-arr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"
><path d="M0 0L10 5L0 10z" class="arrhead"></path></marker
>
</defs>
<line x1="240" y1="64" x2="480" y2="64" class="chan"></line>
<text x="360" y="88" text-anchor="middle" class="sub">channel "data" · push → pull</text>
<g class="maps">
<line x1="140" y1="116" x2="140" y2="204" class="map"></line>
<line x1="580" y1="116" x2="580" y2="204" class="map"></line>
<text x="150" y="166" class="sub">maps</text>
<text x="590" y="166" class="sub">maps</text>
</g>
<g class="seg">
<rect x="40" y="204" width="640" height="76" rx="2" class="segbox"></rect>
<rect x="40" y="204" width="640" height="76" fill="url(#zc-cells)"></rect>
<text x="40" y="300" class="sub">/dev/shm/fmq_&lt;shmId&gt;_m_0</text>
<text x="680" y="300" text-anchor="end" class="sub">managed segment · 2 GiB</text>
</g>
<g class="block">
<rect x="300" y="222" width="140" height="40" class="blk"></rect>
<rect class="fill" x="300" y="222" width="140" height="40" fill="url(#zc-stripes)"></rect>
<text class="blklabel" x="370" y="247" text-anchor="middle">1 MiB payload</text>
</g>
<rect class="blkline" x="298.5" y="220.5" width="143" height="43"></rect>
<text class="read sub mint" x="370" y="214" text-anchor="middle">read in place</text>
<text class="freed sub" x="370" y="247" text-anchor="middle">the block is free again</text>
<path class="hdl" d="M560 116 C 548 168, 480 190, 446 222" marker-end="url(#zc-arr)"></path>
<text class="hdllabel sub sky" x="470" y="184" text-anchor="end">handle → address</text>
<g class="proc">
<rect x="40" y="28" width="200" height="88" rx="3"></rect>
<text x="58" y="56" class="name">sampler</text>
<text x="58" y="76" class="sub">process A</text>
<text x="58" y="100" class="code" data-slot="a"></text>
</g>
<g class="proc">
<rect x="480" y="28" width="200" height="88" rx="3"></rect>
<text x="498" y="56" class="name">sink</text>
<text x="498" y="76" class="sub">process B</text>
<text x="498" y="100" class="code" data-slot="b"></text>
</g>
<g class="meta">
<rect x="232" y="56" width="16" height="16" class="metabox"></rect>
<text class="metalabel sub sky" x="240" y="46" text-anchor="middle">MetaHeader · 40 B</text>
</g>
<g class="zmq">
<rect x="236" y="50" width="56" height="28" class="blk"></rect>
<text x="264" y="69" text-anchor="middle" class="blklabel">1 MiB</text>
</g>
</svg>
</Explainer>
<style>
.name {
fill: var(--fmq-stage-ink);
font-size: 16px;
font-weight: 700;
}
.sub {
fill: var(--fmq-stage-dim);
font-size: 11.5px;
}
.code {
fill: var(--fmq-saffron);
font-size: 11.5px;
font-weight: 600;
}
.proc rect {
fill: var(--fmq-stage-2);
stroke: var(--fmq-stage-line);
stroke-width: 1.2;
}
.chan {
stroke: var(--fmq-stage-line);
stroke-width: 1.5;
}
.map {
stroke: var(--fmq-stage-line);
stroke-dasharray: 4 4;
stroke-width: 1.2;
}
.segbox {
fill: var(--fmq-stage-2);
stroke: var(--fmq-stage-line);
}
.cell {
stroke: var(--fmq-stage-cell);
stroke-width: 1;
}
.blk {
fill: var(--fmq-saffron);
}
.stripe {
fill: rgb(26 26 26 / 0.22);
}
.blklabel {
fill: var(--fmq-on-saffron);
font-size: 12px;
font-weight: 700;
}
.metabox {
fill: var(--fmq-sky-bright);
}
.hdl {
fill: none;
stroke: var(--fmq-sky-bright);
stroke-width: 1.6;
stroke-dasharray: 5 4;
}
.arrhead,
.sky {
fill: var(--fmq-sky-bright);
}
.mint {
fill: var(--fmq-mint);
font-weight: 700;
}
.block {
transform-box: fill-box;
transform-origin: left center;
transform: scaleX(0);
transition:
transform 0.9s cubic-bezier(0.2, 0, 0.1, 1),
opacity 0.7s;
}
.zc.r2 .block {
transform: scaleX(1);
}
.zc.r7 .block {
opacity: 0;
}
.fill,
.blklabel {
opacity: 0;
transition: opacity 0.8s;
}
.zc.r3 .fill,
.zc.r3 .blklabel,
.zmq .blklabel {
opacity: 1;
}
.blkline {
fill: none;
stroke: var(--fmq-mint);
stroke-width: 3;
opacity: 0;
transition: opacity 0.5s;
}
.zc.now6 .blkline {
opacity: 1;
}
.meta {
opacity: 0;
transform: translate(0, 0);
transition:
transform 1.5s cubic-bezier(0.45, 0, 0.2, 1),
opacity 0.35s;
}
.zc.r4 .meta {
opacity: 1;
transform: translate(112px, 0);
}
.zc.r5 .meta {
transform: translate(216px, 0);
}
.metalabel {
transition: opacity 0.4s;
}
.zc.r5 .metalabel {
opacity: 0;
}
.zc.r6 .meta {
opacity: 0;
}
.hdl,
.hdllabel {
opacity: 0;
transition: opacity 0.6s;
}
.zc.r5 .hdl,
.zc.r5 .hdllabel {
opacity: 1;
}
.zc.r7 .hdl,
.zc.r7 .hdllabel {
opacity: 0;
}
.read,
.freed {
opacity: 0;
transition: opacity 0.5s;
}
.zc.now6 .read,
.zc.now7 .freed {
opacity: 1;
}
.zmq {
opacity: 0;
transform: translate(0, 0);
transition:
transform 2.4s cubic-bezier(0.45, 0, 0.2, 1),
opacity 0.35s;
}
.zc.now8 .zmq {
opacity: 1;
transform: translate(176px, 0);
}
.maps,
.seg {
transition: opacity 0.5s;
}
.zc.now8 .maps,
.zc.now8 .seg {
opacity: 0.22;
}
@media (prefers-reduced-motion: reduce) {
.zc * {
transition: none !important;
}
}
</style>

View File

@@ -0,0 +1,94 @@
---
// "A complete device": the smallest program that runs with runDevice.h, and its log.
import { Code } from '@astrojs/starlight/components';
const base = import.meta.env.BASE_URL.replace(/\/$/, '');
const device = `#include <fairmq/Device.h>
#include <fairmq/runDevice.h>
struct Sampler : fair::mq::Device
{
bool ConditionalRun() override
{
auto msg = NewSimpleMessage("Hello");
LOG(info) << "Sending \\"Hello\\"";
return Send(msg, "data") >= 0; // false ends RUNNING
}
};
void addCustomOptions(boost::program_options::options_description&) {}
std::unique_ptr<fair::mq::Device> getDevice(fair::mq::ProgOptions&)
{
return std::make_unique<Sampler>();
}`;
const run = `fairmq-ex-1-1-sampler --id sampler1 --rate 1 \\
--channel-config "name=data,type=push,method=bind,address=tcp://*:5555,rateLogging=0"`;
const log = `[10:42:07][STATE] IDLE ---> INITIALIZING DEVICE
...
[10:42:07][STATE] READY ---> RUNNING
[10:42:07][INFO] fair::mq::Device running...
[10:42:07][INFO] Sending "Hello"
[10:42:08][INFO] Sending "Hello"`;
---
<section class="fmq-homecode not-content" aria-labelledby="home-code">
<div class="hc-text">
<h2 id="home-code">A complete device</h2>
<p>Derive from <code>fair::mq::Device</code> and override one hook. <code>runDevice.h</code> adds the <code>main()</code> function. It parses the command line, loads the plugins and runs the state machine.</p>
<p>In the state RUNNING, the device calls <code>ConditionalRun()</code> in a loop, at the rate of <code>--rate</code>. Each call sends one message. When the function returns <code>false</code>, the device leaves the state RUNNING.</p>
<a href={`${base}/start/first-device/`}>Your first device →</a>
</div>
<div class="hc-code">
<Code code={device} lang="cpp" title="sampler.cxx" />
<Code code={`$ ${run}\n${log}`} lang="txt" frame="terminal" title="Run example 1-1" />
</div>
</section>
<style>
.fmq-homecode {
display: grid;
grid-template-columns: minmax(0, 0.8fr) minmax(0, 1.2fr);
gap: 2rem;
margin-block: 0 2rem;
}
@media (max-width: 60rem) {
.fmq-homecode {
grid-template-columns: minmax(0, 1fr);
gap: 1rem;
}
}
h2 {
font-size: 1.5rem;
font-weight: 800;
font-stretch: 112%;
line-height: 1.15;
margin: 0 0 0.75rem;
color: var(--fmq-ink);
}
.hc-text p {
margin: 0 0 0.9rem;
color: var(--fmq-ink-2);
max-width: 44ch;
}
.hc-text code {
font-size: 0.85em;
background: var(--fmq-paper-3);
border: 1px solid var(--fmq-rule);
border-radius: 3px;
padding: 0.05em 0.3em;
}
.hc-text a {
font-weight: 600;
color: var(--fmq-link);
text-decoration: none;
}
.hc-code {
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.9rem;
}
.hc-code :global(.expressive-code) {
margin: 0 !important;
}
</style>

View File

@@ -0,0 +1,96 @@
---
// Three ways into the docs, below the hero of the home page.
const base = import.meta.env.BASE_URL.replace(/\/$/, '');
const cols = [
{
label: 'Start',
links: [
['Install', '/start/install/'],
['Your first device', '/start/first-device/'],
['Use FairMQ in a CMake project', '/start/cmake/'],
],
},
{
label: 'Understand',
links: [
['Device states', '/concepts/states/'],
['Channels and sockets', '/concepts/channels/'],
['How shared memory works', '/shmem/how-it-works/'],
],
},
{
label: 'Operate',
links: [
['Command-line options', '/reference/options/'],
['Sessions and segments', '/shmem/sessions/'],
['Built-in devices', '/tools/builtin-devices/'],
],
},
];
---
<nav class="fmq-paths not-content" aria-label="Ways into the documentation">
{
cols.map((c) => (
<div>
<p class="fmq-eyebrow">{c.label}</p>
{c.links.map(([t, l]) => (
<a href={base + l}>{t}</a>
))}
</div>
))
}
</nav>
<style>
.fmq-paths {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
border-top: 1px solid var(--fmq-rule);
border-bottom: 1px solid var(--fmq-rule);
margin-block: 0 2.5rem;
}
.fmq-paths > div {
padding: 1.4rem 1.5rem;
border-inline-end: 1px solid var(--fmq-rule);
display: flex;
flex-direction: column;
gap: 0.45rem;
min-width: 0;
}
.fmq-paths > div:first-child {
padding-inline-start: 0;
}
.fmq-paths > div:last-child {
border-inline-end: 0;
}
.fmq-paths .fmq-eyebrow {
margin-bottom: 0.35rem;
}
.fmq-paths a {
color: var(--fmq-ink);
text-decoration: none;
font-weight: 500;
font-size: 0.975rem;
}
.fmq-paths a::after {
content: ' →';
color: var(--fmq-ink-3);
}
.fmq-paths a:hover {
color: var(--fmq-link);
}
@media (max-width: 48rem) {
.fmq-paths {
grid-template-columns: minmax(0, 1fr);
}
.fmq-paths > div {
padding-inline: 0;
border-inline-end: 0;
border-bottom: 1px solid var(--fmq-rule);
}
.fmq-paths > div:last-child {
border-bottom: 0;
}
}
</style>

View File

@@ -0,0 +1,61 @@
---
// Page footer: edit link, last change, pagination, and the site line.
import EditLink from '@astrojs/starlight/components/EditLink.astro';
import LastUpdated from '@astrojs/starlight/components/LastUpdated.astro';
import Pagination from '@astrojs/starlight/components/Pagination.astro';
import { build } from 'virtual:fairmq/data';
---
<footer class="fmq-footer">
<Pagination />
<div class="meta">
<EditLink />
<LastUpdated />
<p>
Built from <a href={`${build.repo}/commit/${build.commit}`}>{build.branch} @ {build.commitShort}</a>
</p>
</div>
<div class="site">
<span>FairMQ · LGPL-3.0-only · GSI Helmholtzzentrum für Schwerionenforschung GmbH</span>
<a href={build.repo}>github.com/FairRootGroup/FairMQ</a>
</div>
</footer>
<style>
.fmq-footer {
display: flex;
flex-direction: column;
gap: 1.5rem;
margin-top: 3rem;
}
.meta {
display: flex;
flex-wrap: wrap;
gap: 0.5rem 1.75rem;
align-items: center;
border-top: 1px solid var(--fmq-rule);
padding-top: 0.9rem;
font-size: 0.8125rem;
color: var(--fmq-ink-3);
}
.meta :global(p) {
margin: 0;
}
.meta a,
.site a {
color: var(--fmq-ink-3);
}
.meta a:hover,
.site a:hover {
color: var(--fmq-ink);
}
.site {
display: flex;
flex-wrap: wrap;
gap: 0.5rem 1.5rem;
justify-content: space-between;
font-size: 0.8125rem;
color: var(--fmq-ink-3);
padding-bottom: 1rem;
}
</style>

View File

@@ -0,0 +1,174 @@
---
// Site header: logo and version, search, main sections, GitHub and theme.
import Search from '@astrojs/starlight/components/Search.astro';
import SocialIcons from '@astrojs/starlight/components/SocialIcons.astro';
import ThemeSelect from '@astrojs/starlight/components/ThemeSelect.astro';
import { build } from 'virtual:fairmq/data';
import Glyph from '../Glyph.astro';
import { sections } from '../../lib/nav';
const base = import.meta.env.BASE_URL.replace(/\/$/, '');
const path = Astro.url.pathname;
---
<div class="fmq-header">
<div class="fmq-brand">
<a class="fmq-logo" href={`${base}/`}>
<Glyph />
<span translate="no">FairMQ</span>
</a>
<a
class="fmq-ver"
href={`${base}/project/release-notes/`}
title={build.unreleased ? `Built from ${build.branch} @ ${build.commitShort}` : `Release ${build.release}`}
>
{build.label}
{build.unreleased && <b>dev</b>}
</a>
</div>
<div class="fmq-search print:hidden"><Search /></div>
<nav class="fmq-nav sl-hidden md:sl-flex print:hidden" aria-label="Sections">
{
sections.map((s) => (
<a href={`${base}${s.href}`} aria-current={s.match(path, base) ? 'page' : undefined}>
{s.label}
</a>
))
}
</nav>
<div class="fmq-right sl-hidden md:sl-flex print:hidden">
<div class="sl-flex fmq-social"><SocialIcons /></div>
<ThemeSelect />
</div>
</div>
<style>
.fmq-header {
display: flex;
align-items: center;
gap: 1rem;
height: 100%;
}
.fmq-brand {
display: flex;
align-items: center;
gap: 0.6rem;
min-width: 0;
flex: none;
}
.fmq-logo {
display: flex;
align-items: center;
gap: 0.5rem;
font: 800 1.125rem/1 var(--fmq-font-body);
font-stretch: 114%;
letter-spacing: -0.01em;
color: var(--fmq-ink);
text-decoration: none;
white-space: nowrap;
}
.fmq-ver {
display: none;
align-items: center;
gap: 0.35rem;
font: 500 0.75rem/1 var(--fmq-font-mono);
border: 1px solid var(--fmq-rule-strong);
border-radius: 3px;
padding: 0.3rem 0.45rem;
color: var(--fmq-ink-2);
text-decoration: none;
white-space: nowrap;
}
.fmq-ver b {
font-weight: 500;
color: var(--fmq-accent-ink);
}
.fmq-ver:hover {
border-color: var(--fmq-ink-3);
color: var(--fmq-ink);
}
.fmq-search {
display: flex;
flex: 1 1 auto;
justify-content: flex-end;
min-width: 0;
}
.fmq-nav {
gap: 1.25rem;
align-self: stretch;
align-items: stretch;
font-size: 0.875rem;
font-weight: 500;
}
.fmq-nav a {
display: flex;
align-items: center;
color: var(--fmq-ink-2);
text-decoration: none;
border-bottom: 2px solid transparent;
margin-bottom: calc(-1 * var(--sl-nav-pad-y) - 1px);
margin-top: calc(-1 * var(--sl-nav-pad-y));
white-space: nowrap;
}
.fmq-nav a:hover {
color: var(--fmq-ink);
}
.fmq-nav a[aria-current='page'] {
color: var(--fmq-ink);
border-bottom-color: var(--fmq-saffron);
}
.fmq-right {
gap: 1rem;
align-items: center;
}
.fmq-social {
gap: 1rem;
align-items: center;
}
.fmq-social::after {
content: '';
height: 1.5rem;
border-inline-end: 1px solid var(--fmq-rule);
}
/* The search button: a quiet field on wide screens, an icon on phones. */
.fmq-search :global(button[data-open-modal]) {
border-radius: 4px;
border-color: var(--fmq-rule);
background: var(--fmq-paper-2);
color: var(--fmq-ink-3);
font-size: 0.875rem;
}
.fmq-search :global(button[data-open-modal]:hover) {
border-color: var(--fmq-ink-3);
color: var(--fmq-ink);
}
.fmq-search :global(button[data-open-modal] kbd) {
font-family: var(--fmq-font-mono);
background: var(--fmq-paper);
border-radius: 3px;
}
@media (min-width: 30rem) {
.fmq-ver {
display: inline-flex;
}
}
@media (min-width: 50rem) {
.fmq-header {
gap: 1.5rem;
}
.fmq-search {
justify-content: flex-start;
flex: 0 1 22rem;
margin-inline-start: 0.5rem;
}
.fmq-search :global(site-search),
.fmq-search :global(button[data-open-modal]) {
width: 100%;
}
.fmq-nav {
margin-inline-start: auto;
}
}
</style>

View File

@@ -0,0 +1,121 @@
---
// The hero of the home page: the claim, two actions, the install command and the topology.
import Topology from '../diagrams/Topology.astro';
import CopyButton from '../CopyButton.astro';
const { data } = Astro.locals.starlightRoute.entry;
const { title = data.title, tagline, actions = [] } = data.hero ?? {};
const base = import.meta.env.BASE_URL.replace(/\/$/, '');
const href = (link: string) => (link.startsWith('/') && !link.startsWith(base + '/') ? base + link : link);
const install = 'spack install fairmq';
---
<div class="fmq-hero">
<div class="h-text">
<p class="fmq-eyebrow">C++17 message queuing · LGPL-3.0</p>
<h1 id="_top" data-page-title>{title}</h1>
{tagline && <p class="h-lead" set:html={tagline} />}
<div class="h-cta">
{
actions.map((a) => (
<a class:list={['h-btn', { pri: a.variant === 'primary' }]} href={href(a.link)}>
{a.text}
</a>
))
}
</div>
<div class="h-install">
<span aria-hidden="true">$</span>
<code>{install}</code>
<CopyButton text={install} label="Copy the install command" />
</div>
</div>
<Topology />
</div>
<style>
.fmq-hero {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1.05fr);
gap: 2.25rem;
align-items: center;
padding-block: 1.5rem 2.5rem;
}
@media (max-width: 60rem) {
.fmq-hero {
grid-template-columns: minmax(0, 1fr);
gap: 1.75rem;
padding-block: 0.5rem 1.75rem;
}
}
h1 {
font-size: clamp(2.1rem, 1.4rem + 2.4vw, 3.05rem);
line-height: 1.03;
font-weight: 800;
font-stretch: 118%;
letter-spacing: -0.026em;
margin: 0.6rem 0 1rem;
text-wrap: balance;
color: var(--fmq-ink);
}
.h-lead {
font-size: 1.125rem;
line-height: 1.55;
color: var(--fmq-ink-2);
margin: 0 0 1.5rem;
max-width: 46ch;
}
.h-cta {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
}
.h-btn {
display: inline-flex;
align-items: center;
font: 600 0.9375rem/1 var(--fmq-font-body);
padding: 0.75rem 1.1rem;
border-radius: 4px;
border: 1px solid var(--fmq-rule-strong);
color: var(--fmq-ink);
text-decoration: none;
background: var(--fmq-paper);
}
.h-btn:hover {
border-color: var(--fmq-ink-3);
color: var(--fmq-ink);
}
.h-btn.pri {
background: var(--fmq-ink);
border-color: var(--fmq-ink);
color: var(--fmq-paper);
}
.h-btn.pri:hover {
background: var(--fmq-ink-2);
color: var(--fmq-paper);
}
.h-install {
display: flex;
align-items: center;
gap: 0.6rem;
margin-top: 1.25rem;
border: 1px solid var(--fmq-rule);
background: var(--fmq-paper-2);
border-radius: 4px;
padding: 0.4rem 0.45rem 0.4rem 0.75rem;
max-width: 22rem;
font-size: 0.875rem;
}
.h-install span {
color: var(--fmq-ink-3);
font-family: var(--fmq-font-mono);
}
.h-install code {
font-family: var(--fmq-font-mono);
color: var(--fmq-ink);
flex: 1;
background: none;
border: 0;
padding: 0;
}
</style>

View File

@@ -0,0 +1,44 @@
---
// Footer of the phone menu: the main sections, then GitHub and the theme.
import Default from '@astrojs/starlight/components/MobileMenuFooter.astro';
import { sections } from '../../lib/nav';
const base = import.meta.env.BASE_URL.replace(/\/$/, '');
const path = Astro.url.pathname;
---
<nav class="fmq-mnav" aria-label="Sections">
{
sections.map((s) => (
<a href={`${base}${s.href}`} aria-current={s.match(path, base) ? 'page' : undefined}>
{s.label}
</a>
))
}
</nav>
<Default />
<style>
.fmq-mnav {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 0.5rem;
border-top: 1px solid var(--fmq-rule);
padding-top: 0.75rem;
}
.fmq-mnav a {
text-align: center;
padding: 0.5rem 0.25rem;
border: 1px solid var(--fmq-rule);
border-radius: 4px;
color: var(--fmq-ink-2);
text-decoration: none;
font-size: 0.875rem;
font-weight: 500;
}
.fmq-mnav a[aria-current='page'] {
border-color: var(--fmq-bar);
background: var(--fmq-saffron-tint);
color: var(--fmq-ink);
}
</style>

View File

@@ -0,0 +1,87 @@
---
// Right column: the page contents, then the source files and guides of the page.
import Default from '@astrojs/starlight/components/PageSidebar.astro';
const { entry, toc } = Astro.locals.starlightRoute;
const data = entry.data as typeof entry.data & {
code?: string[];
guides?: { label: string; link: string }[];
};
const base = import.meta.env.BASE_URL.replace(/\/$/, '');
const code = data.code ?? [];
const guides = data.guides ?? [];
const withBase = (link: string) => (link.startsWith('/') && !link.startsWith(base + '/') ? base + link : link);
---
<Default />
{
toc && (code.length > 0 || guides.length > 0) && (
<div class="right-sidebar-panel fmq-extra sl-hidden lg:sl-block">
<div class="sl-container">
{guides.length > 0 && (
<nav aria-labelledby="fmq-guides">
<h2 id="fmq-guides">Guides</h2>
<ul>
{guides.map((g) => (
<li>
<a href={withBase(g.link)}>{g.label}</a>
</li>
))}
</ul>
</nav>
)}
{code.length > 0 && (
<nav aria-labelledby="fmq-code">
<h2 id="fmq-code">Code</h2>
<ul>
{code.map((file) => (
<li>
<a class="file" href={`${base}/source/${file}/`}>
{file}
</a>
</li>
))}
</ul>
</nav>
)}
</div>
</div>
)
}
<style>
.fmq-extra {
padding: 0 var(--sl-sidebar-pad-x) 1rem;
}
.fmq-extra nav {
border-top: 1px solid var(--fmq-rule);
padding-top: 0.9rem;
margin-bottom: 1rem;
}
.fmq-extra h2 {
margin-bottom: 0.5rem;
}
.fmq-extra ul {
list-style: none;
padding: 0;
margin: 0;
}
.fmq-extra li + li {
margin-top: 0.3rem;
}
.fmq-extra a {
display: block;
font-size: var(--sl-text-xs);
text-decoration: none;
color: var(--fmq-ink-2);
overflow-wrap: anywhere;
}
.fmq-extra a:hover {
color: var(--fmq-ink);
}
.fmq-extra a.file {
font-family: var(--fmq-font-mono);
font-size: 0.75rem;
color: var(--fmq-link);
}
</style>

View File

@@ -0,0 +1,54 @@
---
// Page title with the section label above it and an optional "since" badge.
import { sectionLabel } from '../../lib/nav';
const { entry, id } = Astro.locals.starlightRoute;
const data = entry.data as typeof entry.data & {
eyebrow?: string;
titleKind?: string;
since?: string;
searchTitle?: string;
};
const eyebrow = data.eyebrow ?? sectionLabel(id);
---
{eyebrow && <p class="fmq-eyebrow">{eyebrow}</p>}
<h1
id="_top"
class:list={{ code: !!data.titleKind }}
data-pagefind-meta={data.searchTitle ? `title:${data.searchTitle}` : undefined}
>
<span>{data.title}</span>
{data.titleKind && <span class="fmq-badge">{data.titleKind}</span>}
{data.since && <span class="fmq-badge since">since {data.since}</span>}
</h1>
<style>
h1 {
margin-top: 0.9rem;
font-size: var(--sl-text-h1);
line-height: 1.06;
font-weight: 800;
font-stretch: 112%;
letter-spacing: -0.02em;
color: var(--fmq-ink);
text-wrap: balance;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.4rem 0.75rem;
}
h1.code {
font-family: var(--fmq-font-mono);
font-stretch: 100%;
font-weight: 700;
letter-spacing: -0.01em;
font-size: calc(var(--sl-text-h1) * 0.8);
overflow-wrap: anywhere;
}
h1 .fmq-badge {
font-size: 0.75rem;
font-family: var(--fmq-font-body);
letter-spacing: 0.08em;
}
</style>

View File

@@ -0,0 +1,26 @@
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';
export const collections = {
docs: defineCollection({
loader: docsLoader(),
schema: docsSchema({
extend: z.object({
/** Text above the title. The default is the name of the sidebar section. */
eyebrow: z.string().optional(),
/** Kind badge after the title, for API pages. The title is then set in the code font. */
titleKind: z.string().optional(),
/** Title for the search results, if it differs from the page title. */
searchTitle: z.string().optional(),
/** First FairMQ release with the feature that the page describes, e.g. "v1.11". */
since: z.string().optional(),
/** Source files that the page describes, relative to the repository root. */
code: z.array(z.string()).default([]),
/** Links in the right column under "Guides". The API pages use it. */
guides: z.array(z.object({ label: z.string(), link: z.string() })).default([]),
}),
}),
}),
};

View File

@@ -0,0 +1,206 @@
---
title: 'Channels and sockets'
description: 'Channels and sub-channels, socket types and patterns, bind and connect, addresses and endpoints, autobind and the transport of a channel.'
sidebar:
order: 3
code: [fairmq/Channel.h, fairmq/Channel.cxx, fairmq/Device.cxx, fairmq/zeromq/Socket.h, fairmq/shmem/Socket.h]
---
import ChannelAnatomy from '../../../components/diagrams/ChannelAnatomy.astro';
import PatternDiagram from '../../../components/diagrams/PatternDiagram.astro';
import Snippet from '../../../components/Snippet.astro';
A device sends and receives messages through its channels. A channel has a name and one or more sub-channels, and each sub-channel has one socket. The configuration of a sub-channel sets the type of its socket, how the socket finds its peers, and the transport that moves the messages.
<ChannelAnatomy />
## Channels and sub-channels
A device keeps its channels in a map from the channel name to a list of sub-channels: [`GetChannels()`](/api/fair/mq/Device/#GetChannels) returns a [`fair::mq::ChannelMap`](/api/fair/mq/#ChannelMap), which is a `std::unordered_map<std::string, std::vector<Channel>>`. Each sub-channel is a [`fair::mq::Channel`](/api/fair/mq/Channel/) with one socket.
A sub-channel has the name `<channel>[<index>]`, for example `data-out[1]`. The index starts at 0. To select a sub-channel, give the channel name and the index:
- [`GetChannel("data-out", 1)`](/api/fair/mq/Device/#GetChannel) returns the `Channel` object.
- [`Send(msg, "data-out", 1)`](/api/fair/mq/Device/#Send) and [`Receive(msg, "data-in")`](/api/fair/mq/Device/#Receive) send and receive through it. The index is the third argument. Its default is 0.
- [`GetNumSubChannels("data-out")`](/api/fair/mq/Device/#GetNumSubChannels) returns the number of sub-channels.
For a channel or an index that does not exist, `GetChannel()` logs `GetChannel(): 'data-out[2]' does not exist.` and throws `std::out_of_range` ([Device.h](/source/fairmq/Device.h/#L323-L329)).
The sampler of the [copypush example](/examples/copypush/) sends a copy of each message to each sub-channel of its channel `data`:
<Snippet file="examples/copypush/sampler.cxx" start="bool ConditionalRun()" />
Its start script gives `data` two sub-channels, with one `address=` key for each sub-channel:
<Snippet file="examples/copypush/fairmq-start-ex-copypush.sh.in" start="SAMPLER=" end="--channel-config" />
A socket can also have several endpoints (see [Addresses and endpoints](#addresses-and-endpoints)). Then the socket itself distributes the messages to its peers, by the rules of its socket type. Use several sub-channels when your code must select the peer for each message.
## Socket types and patterns
<PatternDiagram />
The `type` of a sub-channel is the type of its socket. FairMQ uses the ZeroMQ socket type of the same name ([zeromq/Common.h](/source/fairmq/zeromq/Common.h/#L91-L123)). The `shmem` transport also uses ZeroMQ sockets of this type, for the metadata of the messages. The column Pattern gives the ZeroMQ behavior of each type. The ZeroMQ documentation of `zmq_socket` describes it in full.
| Type | Peer | Pattern | Example in the repository |
| --- | --- | --- | --- |
| `push` | `pull` | Pipeline. A `push` socket with several peers sends each message to one of them. | [1-n-1](/examples/1-n-1/) |
| `pull` | `push` | Pipeline. A `pull` socket receives from all its peers. | [1-n-1](/examples/1-n-1/) |
| `pub` | `sub` | Publish and subscribe. Each `sub` peer gets a copy. | [multiple-channels](/examples/multiple-channels/) |
| `sub` | `pub` | Publish and subscribe. The `zeromq` transport subscribes each `sub` socket to all messages ([zeromq/Socket.h](/source/fairmq/zeromq/Socket.h/#L70-L74)). | [multiple-channels](/examples/multiple-channels/) |
| `req` | `rep` | Request and reply. | [req-rep](/examples/req-rep/) |
| `rep` | `req` | Request and reply. | [req-rep](/examples/req-rep/) |
| `pair` | `pair` | One peer, both directions. | [readout](/examples/readout/) |
| `dealer`, `router`, `xpub`, `xsub` | | The ZeroMQ types of these names. | None |
[`Channel::Validate()`](/api/fair/mq/Channel/#Validate) accepts these 11 types. For another type, it throws [`ChannelConfigurationError`](/api/fair/mq/Channel/ChannelConfigurationError/) ([Channel.cxx](/source/fairmq/Channel.cxx/#L193-L199)). The tests of the repository cover `push`/`pull`, `pub`/`sub`, `req`/`rep` and `pair`.
:::caution[pub and sub with shared memory]
The `shmem` transport does not support `pub` and `sub`. It throws `SocketError` with `PUB/SUB socket type is not supported for shared memory transport` when the device makes such a socket ([shmem/Socket.h](/source/fairmq/shmem/Socket.h/#L59-L62)).
:::
### Behavior of each socket type
FairMQ calls ZeroMQ in a loop ([zeromq/Socket.h](/source/fairmq/zeromq/Socket.h/#L96-L124)). Each ZeroMQ call waits up to 100 ms. If ZeroMQ cannot take or give a message in this time (`EAGAIN`), the loop checks for an interruption and for the timeout of the call. Then it calls ZeroMQ again. Thus `Send()` returns in one of these ways:
- The number of bytes, when ZeroMQ accepts the message.
- `TransferCode::timeout` (-2), when the timeout of the call is over. With the timeout 0, `Send()` does not wait.
- `TransferCode::interrupted` (-3), when the device gets a transition request.
- `TransferCode::error` (-1), when ZeroMQ reports another error. FairMQ logs `Failed transfer on socket <id>, errno: <n>, reason: <text>`. For `ETERM` (the context terminates), it logs `Terminating socket <id>` with the severity `debug`.
`Receive()` uses the same loop. The `shmem` transport has the same loop for its metadata message ([shmem/Socket.h](/source/fairmq/shmem/Socket.h/#L118-L161)). What ZeroMQ does with a full queue, a missing peer or a wrong sequence of calls depends on the socket type. The column "ZeroMQ behavior" comes from the ZeroMQ documentation of `zmq_socket` and `zmq_setsockopt`, not from FairMQ.
| Type | ZeroMQ behavior | Result in FairMQ |
| --- | --- | --- |
| `push` | Sends each message to one peer, in turn (round robin). When the queues of all peers are full, or when it has no peer, the socket blocks and discards nothing. A connecting socket queues messages for its endpoints also before the peer is there. | `Send()` waits until a queue has space, the timeout is over, or a transition interrupts it. FairMQ does not set `ZMQ_IMMEDIATE`, so messages can wait in the queue of a peer that never comes. |
| `pull` | Receives from all peers in turn (fair queuing). | `Receive()` waits for a message. |
| `pub` | Sends a copy to each connected subscriber. A subscriber that is not connected yet gets nothing. When the queue of a subscriber is full, the socket drops the message for this subscriber and does not block. | `Send()` returns the number of bytes also for a dropped message, and the [counters](#socket-counters) count it as sent. |
| `sub` | Receives only the messages that match its subscriptions. A new subscription reaches the publisher some time after the connect. | The `zeromq` transport subscribes each `sub` socket to all messages ([zeromq/Socket.h](/source/fairmq/zeromq/Socket.h/#L70-L74)). `SetOption()` has no option name for `ZMQ_SUBSCRIBE` (see [Set socket options directly](/reference/channel-properties/#set-socket-options-directly)), so a `sub` socket of FairMQ receives all messages. |
| `req` | Only the sequence send, receive, send, receive… A reply goes to the last request. | A second `Send()` without a `Receive()` returns `TransferCode::error`. After a receive timeout, the socket still waits for the reply, so the next `Send()` also fails. |
| `rep` | Only the sequence receive, send, receive, send… The reply goes to the peer of the last request. | A `Send()` before a `Receive()` returns `TransferCode::error`. |
| `pair` | One peer. When the queue is full, or when no peer is there, the socket blocks. | As for `push`. |
| `dealer` | Sends in turn to its peers and receives from all peers, in any sequence. When the queues of all peers are full, or when it has no peer, the socket blocks. To talk to a `rep` socket, each message must start with an empty part. | As for `push`. Use `fair::mq::Parts` for the empty part. |
| `router` | Adds a part with the identity of the peer before each received message. Uses the first part of each sent message to select the peer. Drops a message for an unknown peer or a full queue, and does not block. | FairMQ sets the identity of each socket to `<device id>.<sub-channel name>.<type>`, for example `sampler1.data[0].dealer` ([zeromq/Socket.h](/source/fairmq/zeromq/Socket.h/#L37-L53)). Receive into `fair::mq::Parts`. Part 0 is the identity. |
| `xpub`, `xsub` | As `pub` and `sub`, but the subscriptions are messages: an `xsub` socket subscribes when it sends a message that starts with the byte 1. | FairMQ sets no subscription for these types. |
The `shmem` transport uses ZeroMQ sockets of the same types for its metadata, so the same rules apply to the types that it supports. It sends and reads one ZeroMQ frame in each call and expects the metadata in it. Thus it cannot handle the extra parts of `dealer` and `router`: the identity part and the empty part. No test of the repository covers `dealer`, `router`, `xpub` and `xsub`.
The client of the [req-rep example](/examples/req-rep/) receives the reply before it sends the next request:
<Snippet file="examples/req-rep/client.cxx" start='if (Send(req, "data") > 0) {' />
A `sub` that connects late misses the messages that the `pub` sent before. The test devices of the repository synchronize through a second channel. Each `sub` waits and sends a ready message. The `pub` publishes only after it receives the ready messages:
<Snippet file="test/helper/devices/TestSub.h" start="auto Run() -> void override" />
## Bind and connect
The `method` of a sub-channel is `bind` or `connect`. A binding socket waits for peers on its endpoints. A connecting socket connects to the endpoints of a peer. The method does not depend on the type: a `push` socket can bind or connect. Usually the device with a fixed place in the topology binds, for example the sampler and the sink in the 1-n-1 example.
The device attaches its sub-channels in two states ([Device.cxx](/source/fairmq/Device.cxx/#L217-L276)):
- In `BINDING`, the device binds all binding sub-channels, with one attempt. If one fails, the device goes to `ERROR` with `1 of the binding channels could not initialize`.
- In `CONNECTING`, the device connects all connecting sub-channels. If the address of a sub-channel is not valid or its host name does not resolve, the device tries again every 50 ms. Before each attempt, it reads the address property again. After the time of `--init-timeout` (default 120 s), it goes to `ERROR` with `could not connect all channels after 120 attempts`. The number in this message is the timeout in seconds.
ZeroMQ connects in the background. Thus a connect to a peer that is not there yet does not fail. You can start the devices of a topology in any sequence. [`GetNumberOfConnectedPeers()`](/api/fair/mq/Device/#GetNumberOfConnectedPeers) returns the number of peers of a sub-channel.
## Addresses and endpoints
The `address` of a sub-channel has one endpoint or several endpoints, separated by `,`. An endpoint has the form `[modifier]protocol://location`:
| Protocol | Example | Use |
| --- | --- | --- |
| `tcp://` | `tcp://*:5555`, `tcp://host1:5555` | Between hosts, or on one host. |
| `ipc://` | `ipc:///tmp/fmq_data` | Between processes on one host, through a Unix domain socket file. |
| `inproc://` | `inproc://data` | Between sub-channels of one device with the same transport. |
`Validate()` checks the protocol, a `:` after `tcp://`, and a location that is not empty after `ipc://` and `inproc://` ([Channel.cxx](/source/fairmq/Channel.cxx/#L201-L270)). It also accepts `verbs://`, a remainder of the removed `ofi` transport. The `zeromq` and `shmem` transports cannot use it.
In a TCP bind, the host is `*` for all interfaces, an IPv4 address or a host name. In a TCP connect, the host is an IPv4 address or a host name. The device replaces each host name with its first IPv4 address before it binds or connects ([Device.cxx](/source/fairmq/Device.cxx/#L321-L333)).
A modifier before an endpoint overrides the `method` for this endpoint ([Device.cxx](/source/fairmq/Device.cxx/#L311-L319)):
- `@` binds the endpoint.
- `+` or `>` connects the endpoint.
With modifiers, one socket can bind some endpoints and connect others. A sub-channel without a `method` needs a modifier on each endpoint. The device then attaches it in `CONNECTING`. In this file of the [multipart example](/examples/multipart/), the socket of `sampler1` connects to two sinks. `sink2` binds with `@`, although its method is `connect`:
<Snippet file="examples/multipart/ex-multipart-multiple-endpoints.json" />
:::caution[Separators]
Separate several endpoints with `,`. `Validate()` splits the address at `;`, but the device splits it at `,` ([Device.cxx](/source/fairmq/Device.cxx/#L302)). An address with `;` passes the check and then fails in the transport. In `--channel-config`, the `,` separates the keys, so give several endpoints in a JSON file or as a property.
:::
After the attach, the device writes the address that it uses back to the property `chans.<name>.<index>.address` ([Device.cxx](/source/fairmq/Device.cxx/#L359-L366)). This value has the resolved IPv4 addresses and the port that autobind selected.
## Automatic ports
When a TCP bind fails and `autoBind` is `true` (the default), the device binds to a random port from `portRangeMin` to `portRangeMax` (22000 to 23000). It tries up to 1000 ports ([Channel.cxx](/source/fairmq/Channel.cxx/#L346-L386)).
FairMQ uses this for binding sub-channels without an address. Such a sub-channel gets the address `tcp://<IP of --network-interface>:1`. Without root rights, the bind to port 1 fails, and autobind selects a port. With `--network-interface default`, the device uses the interface of the default route. Code that knows the topology then reads the address property and gives it to the peers, for example a plugin.
:::caution[Fixed ports]
If the configured port is in use, autobind binds to a random port. The device logs this only with the severity `debug`, and the peers do not find the device. For fixed ports, set `autoBind` to `false`. [Channel properties](/reference/channel-properties/#portrangemin-portrangemax-and-autobind) describes the CMake variable that changes the default.
:::
## The transport of a sub-channel
Each sub-channel has a transport: `zeromq` or `shmem`. The `transport` property of the sub-channel selects it. With the value `default`, the sub-channel uses the default transport of the device, from `--transport` (default `zeromq`). The device makes one transport object for each transport that its sub-channels use, and the sub-channels share it ([Device.cxx](/source/fairmq/Device.cxx/#L586-L605)).
- Give both ends of a connection the same transport, as the examples do.
- With `shmem`, all peers must be on the same host and in the same session. Refer to [Sessions and segments](/shmem/sessions/).
- A poller and the data callbacks of [`OnData()`](/api/fair/mq/Device/#OnData) expect one transport for all sub-channels of a channel.
[Transports](/concepts/transports/) compares the transports. [Use several transports](/guides/several-transports/) shows a device with channels of both transports.
## Queues, timeouts and the rate log
Each sub-channel has more properties. [Channel properties](/reference/channel-properties/) gives all details.
| Properties | Default | Effect |
| --- | --- | --- |
| `sndBufSize`, `rcvBufSize` | 1000 | Maximum number of messages in the send queue and the receive queue. |
| `sndKernelSize`, `rcvKernelSize` | 0 | Kernel buffer sizes in bytes. 0: the system default. |
| `sndTimeoutMs`, `rcvTimeoutMs` | -1 | Timeout of `Send()` and `Receive()` without a timeout argument. -1: no timeout. |
| `linger` | 500 | Time in ms to keep unsent messages after the socket closes. See [Linger](/guides/end-of-run/#linger). |
| `rateLogging` | 1 | Interval of the rate log in seconds. 0: no rate log. |
In `RUNNING`, the device logs the rate of each sub-channel with a `rateLogging` above 0, with the severity `info`:
```txt
data[0]: in: <messages/s> (<MB/s> MB) out: <messages/s> (<MB/s> MB)
```
### Socket counters
Each socket counts its transfers. [`Channel`](/api/fair/mq/Channel/) gives the counters of its socket, and [`Socket`](/api/fair/mq/Socket/) has the same four functions:
| Function | Counts |
| --- | --- |
| [`GetMessagesTx()`](/api/fair/mq/Channel/#GetMessagesTx) | Messages that `Send()` gave to ZeroMQ. |
| [`GetBytesTx()`](/api/fair/mq/Channel/#GetBytesTx) | Bytes of these messages. |
| [`GetMessagesRx()`](/api/fair/mq/Channel/#GetMessagesRx) | Messages that `Receive()` got. |
| [`GetBytesRx()`](/api/fair/mq/Channel/#GetBytesRx) | Bytes of these messages. |
The rules are in the send and receive functions of the transports ([zeromq/Socket.h](/source/fairmq/zeromq/Socket.h/#L96-L255), [shmem/Socket.h](/source/fairmq/shmem/Socket.h/#L118-L315)):
- The counters start at 0 when the transport makes the socket. In a device, this occurs in `BINDING` or `CONNECTING`. After `RESET DEVICE`, the next initialization makes new sockets, which start at 0 again.
- Only a successful transfer counts. A timeout, an interruption or an error does not change the counters.
- A multipart message counts as one message. Its bytes are the sum of the sizes of its parts.
- The bytes are the sizes of the messages. The `shmem` transport does not count its metadata message.
- A `pub` socket counts a message also when ZeroMQ drops it for a subscriber. See [Behavior of each socket type](#behavior-of-each-socket-type).
The counters are `unsigned long` values that only increase. Another thread can read them during the transfers. To log other values, read the counters in your own code, for example `GetChannel("data", 0).GetMessagesTx()`.
The rate log reads the counters in its own thread. The thread wakes up every second. At each interval, it reads the four counters of each sub-channel and divides the differences by the time since its last wake-up ([Device.cxx](/source/fairmq/Device.cxx/#L613-L705)). Thus with a `rateLogging` above 1, the logged rates are too high by the factor `rateLogging` (a defect of the code).
[Set socket options directly](/reference/channel-properties/#set-socket-options-directly) tells how to set ZeroMQ options of a socket with [`SetOption()`](/api/fair/mq/Socket/#SetOption).
## Related pages
- [Design a topology](/guides/design-topology/): select the patterns, the binding devices and the addresses.
- [Configure channels](/guides/configure-channels/): give the channels with `--channel-config`, a JSON file or code.
- [Channel properties](/reference/channel-properties/): all properties, with their defaults and allowed values.
- [Device states](/concepts/states/): the states `BINDING` and `CONNECTING`.
- [Messages and multipart](/concepts/messages/): what goes through a channel.
- [Poll several channels](/guides/poll-channels/): receive from several sub-channels in one loop.

View File

@@ -0,0 +1,140 @@
---
title: 'Configuration and properties'
description: 'How a device gets its configuration: options, --channel-config, JSON files and plugins all give properties in one store.'
sidebar:
order: 6
code: [fairmq/ProgOptions.h, fairmq/ProgOptions.cxx, fairmq/Properties.h, fairmq/plugins/config/Config.cxx, fairmq/DeviceRunner.cxx]
---
import Snippet from '../../../components/Snippet.astro';
A device keeps its complete configuration as properties: values with a name, in one store of the type [`fair::mq::ProgOptions`](/api/fair/mq/ProgOptions/). The command-line options, the channel configuration and the values from plugins all go into this store. The device, its plugins and your code read the configuration from there, also while the device runs.
## The property store
A property has a key of the type `std::string` and a value of any C++ type. The value is a [`fair::mq::Property`](/api/fair/mq/#Property), which is a `boost::any`. [`fair::mq::Properties`](/api/fair/mq/#Properties) is a `std::map<std::string, Property>` for several properties. The store protects its data with a mutex, so all threads can use it.
A device has a pointer to its store: [`fConfig`](/api/fair/mq/Device/#fConfig), also from [`GetConfig()`](/api/fair/mq/Device/#GetConfig). A device that you make with the constructor `Device()` has its own internal store. [`SetConfig()`](/api/fair/mq/Device/#SetConfig) replaces it with another store and discards the internal store ([Device.cxx](/source/fairmq/Device.cxx/#L607-L611)). With `runDevice.h`, the [device runner](/api/fair/mq/DeviceRunner/) makes the store and gives it to the device with `SetConfig()`.
:::caution[Properties from the device constructor]
With `runDevice.h`, the device runner calls `SetConfig()` after it makes the device ([DeviceRunner.cxx](/source/fairmq/DeviceRunner.cxx/#L172-L173)). A device that uses the constructor `Device()` loses all properties and channels that its constructor sets. Set them in [`Init()`](/api/fair/mq/Device/#Init), or give the store to the constructor `Device(ProgOptions&)`.
:::
The old name `FairMQProgOptions` is a deprecated alias of `fair::mq::ProgOptions`. Refer to [Move from the FairMQ* names](/guides/migrate-names/).
## Where the properties come from
A device made with `runDevice.h` gets its properties in this sequence ([DeviceRunner.cxx](/source/fairmq/DeviceRunner.cxx/#L108-L194)):
1. The device runner loads the config plugin and the control plugin, and collects the options of all plugins and your `addCustomOptions()`.
2. It parses the command line. Each option becomes a property with the name of the option, for example `id` or `severity`. An option that you do not give gets its default, if it has one.
3. It makes the device with your `getDevice()`, gives it the store, and makes the plugins.
4. It logs all properties with the severity `debug`, and starts the state machine.
5. When the device goes into the state `INITIALIZING DEVICE`, the [config plugin](#the-config-plugin) reads `--mq-config` or `--channel-config`. It stores each channel property as `chans.<name>.<index>.<property>`.
6. When the controller requests the transition `COMPLETE INIT`, the device reads its properties and makes its sub-channels.
Without `DeviceRunner`, your program parses the command line itself. See [Parse options without DeviceRunner](/guides/control-from-code/#parse-options-without-devicerunner).
Plugins and your code can set properties at all times with [`SetProperty()`](/api/fair/mq/ProgOptions/#SetProperty). The device also writes a property: after it binds or connects a sub-channel, it writes the address that it uses to `chans.<name>.<index>.address` ([Device.cxx](/source/fairmq/Device.cxx/#L359-L366)).
## When the device reads a property
The device reads most properties once, at the request of the transition `COMPLETE INIT` ([Device.cxx](/source/fairmq/Device.cxx/#L146-L215)). A later change has an effect only when the device goes through `INITIALIZING DEVICE` again, for example after the transition `RESET DEVICE`.
| Properties | The device reads them | A later change |
| --- | --- | --- |
| `id`, `rate`, `init-timeout`, `transport`, `network-interface` | At the request of `COMPLETE INIT` | No effect |
| `chans.<name>.<index>.<property>` | At the request of `COMPLETE INIT` | No effect, except for the address of a connecting sub-channel that the device could not connect yet |
| `io-threads`, `session`, `shmid`, the `shm-*` and `bad-alloc-*` options | When the device makes the transport, at the request of `COMPLETE INIT` | No effect |
| `control`, `catch-signals` | When the device runner makes the control plugin | No effect |
| `severity`, `file-severity`, `verbosity`, `color`, `log-to-file` | After the parse of the command line | The device runner applies the new value at once ([DeviceRunner.cxx](/source/fairmq/DeviceRunner.cxx/#L82-L101)) |
| Your custom options | When your code reads them | Your code decides |
## Read and change properties
The device and the plugins use the same functions. A device calls them on `fConfig`. A plugin calls them on itself, for example [`Plugin::GetProperty()`](/api/fair/mq/Plugin/#GetProperty). In a plugin, `Count()` has the name [`PropertyExists()`](/api/fair/mq/Plugin/#PropertyExists).
| Function | Effect | If the key does not exist |
| --- | --- | --- |
| [`GetProperty<T>(key)`](/api/fair/mq/ProgOptions/#GetProperty) | Returns the value. | Throws [`PropertyNotFoundError`](/api/fair/mq/PropertyNotFoundError/). |
| [`GetProperty<T>(key, ifNotFound)`](/api/fair/mq/ProgOptions/#GetProperty-2) | Returns the value. | Returns `ifNotFound`. |
| [`GetPropertyAsString(key)`](/api/fair/mq/ProgOptions/#GetPropertyAsString) | Returns the value as text. | Throws `PropertyNotFoundError`. |
| [`GetPropertyAsString(key, ifNotFound)`](/api/fair/mq/ProgOptions/#GetPropertyAsString-2) | Returns the value as text. | Returns `ifNotFound`. |
| [`GetProperties(regex)`](/api/fair/mq/ProgOptions/#GetProperties) | Returns the properties whose full key matches the regular expression. | Returns an empty map and logs a warning. |
| [`GetPropertiesStartingWith(prefix)`](/api/fair/mq/ProgOptions/#GetPropertiesStartingWith) | Returns the properties whose key starts with `prefix`. | Returns an empty map. |
| [`GetPropertiesAsString(regex)`](/api/fair/mq/ProgOptions/#GetPropertiesAsString) | The same as `GetProperties()`, with the values as text. | Returns an empty map and logs a warning. |
| [`GetPropertiesAsStringStartingWith(prefix)`](/api/fair/mq/ProgOptions/#GetPropertiesAsStringStartingWith) | The same as `GetPropertiesStartingWith()`, with the values as text. | Returns an empty map. |
| [`GetPropertyKeys()`](/api/fair/mq/ProgOptions/#GetPropertyKeys) | Returns all keys. | |
| [`Count(key)`](/api/fair/mq/ProgOptions/#Count) | Returns 1 if the property exists, otherwise 0. | |
| [`SetProperty<T>(key, value)`](/api/fair/mq/ProgOptions/#SetProperty) | Sets the value. | Makes the property. |
| [`UpdateProperty<T>(key, value)`](/api/fair/mq/ProgOptions/#UpdateProperty) | Sets the value and returns `true`. | Returns `false`. |
| [`SetProperties(properties)`](/api/fair/mq/ProgOptions/#SetProperties) | Sets several values. | Makes the properties. |
| [`UpdateProperties(properties)`](/api/fair/mq/ProgOptions/#UpdateProperties) | Sets several values and returns `true`. | Returns `false` and changes nothing. |
| [`DeleteProperty(key)`](/api/fair/mq/ProgOptions/#DeleteProperty) | Removes the property. | Does nothing. |
The type `T` must be the exact type of the stored value. For another type, the read throws `boost::bad_any_cast`. The type of an option is the type in its declaration, for example `uint64_t` for `--max-iterations` of the 1-1 sampler. [Command-line options](/reference/options/) shows the type of each option.
:::caution[String literals]
`SetProperty("key", "text")` stores a `const char*`, not a `std::string`. A later `GetProperty<std::string>("key")` then throws. Write `SetProperty<std::string>("key", "text")`.
:::
## Subscribe to changes
[`Subscribe<T>()`](/api/fair/mq/ProgOptions/#Subscribe) registers a callback for the changes of all properties of the type `T`. [`SubscribeAsString()`](/api/fair/mq/ProgOptions/#SubscribeAsString) registers a callback that gets each change of each type, with the value as text. `SetProperty()`, `UpdateProperty()`, `SetProperties()` and `UpdateProperties()` call the callbacks ([ProgOptions.h](/source/fairmq/ProgOptions.h/#L268-L279)).
- The callback gets the key and the new value. It runs in the thread that changes the property, before the change function returns.
- Each subscription has the name of a subscriber. A second subscription with the same name and the same type replaces the first ([EventManager.h](/source/fairmq/EventManager.h/#L124-L144)).
- [`Unsubscribe<T>()`](/api/fair/mq/ProgOptions/#Unsubscribe) and [`UnsubscribeAsString()`](/api/fair/mq/ProgOptions/#UnsubscribeAsString) remove a subscription. For a name without a subscription, they throw `std::out_of_range`.
- A plugin uses [`SubscribeToPropertyChange<T>()`](/api/fair/mq/Plugin/#SubscribeToPropertyChange). The name of the plugin is the name of the subscriber.
This test of the plugin services shows the callbacks for three types, and the effect of an unsubscribe:
<Snippet file="test/plugin_services/_config.cxx" start="TEST_F(PluginServices, ConfigCallbacks)" end="^}" />
### Your own types
A property can hold a value of your own type. To convert it to text, register the type with [`PropertyHelper::AddType<T>()`](/api/fair/mq/PropertyHelper/#AddType). The type must have an `operator<<` for `std::ostream`. Without the registration, `GetPropertyAsString()` returns `[unidentified_type]`. `SetProperties()`, `UpdateProperties()`, `GetPropertiesAsString()` and `GetPropertiesAsStringStartingWith()` throw `std::out_of_range` for such a value ([Properties.h](/source/fairmq/Properties.h/#L33-L70)).
## Channel properties
The configuration of a sub-channel is a group of properties with the keys `chans.<name>.<index>.<property>`, for example `chans.data.0.address`. [Channel properties](/reference/channel-properties/) lists all of them. The parsers of `--channel-config` and JSON files make all 15 properties of each sub-channel.
- [`GetChannelInfo()`](/api/fair/mq/ProgOptions/#GetChannelInfo) counts the sub-channels of each channel by their `type` properties ([ProgOptions.cxx](/source/fairmq/ProgOptions.cxx/#L163-L183)). A sub-channel without a `type` property does not exist for the device.
- The device makes the sub-channels with the indexes 0 to N-1, where N is the count. Thus use the indexes 0, 1, 2 and so on, without gaps.
- The device reads the channel properties at the request of `COMPLETE INIT`. Set them before this request, for example in a plugin in the state `INITIALIZING DEVICE`, or in the hook `Init()` of the device.
[Configure channels](/guides/configure-channels/) shows the three ways to give the channel properties.
## The config plugin
The config plugin is a part of each device made with `runDevice.h`. It declares the options of the groups Device and Shared memory in the [table of options](/reference/options/), and reads the channel configuration ([Config.cxx](/source/fairmq/plugins/config/Config.cxx/#L25-L53)).
When the device goes into the state `INITIALIZING DEVICE`, the config plugin:
1. Takes the value of `--config-key`, or the value of `--id` if `--config-key` is not there.
2. Reads the JSON file of `--mq-config` for this value. If there is no `--mq-config`, it reads `--channel-config`.
3. Stores the channel properties with `SetProperties()`.
If the parser throws an exception, the plugin logs the message with the severity `error`, and the device continues without these channels. If `--id` and `--config-key` are empty, the plugin logs a warning and reads nothing. [JSON configuration](/reference/json/#errors) lists the errors.
The device runner makes the plugins of `-P` before the config plugin. In `INITIALIZING DEVICE`, their callbacks thus run first. The config plugin then replaces the values of all channel properties that the configuration also gives.
## Custom options
Your own options become properties as well. With `runDevice.h`, declare them in `addCustomOptions()`, and read them with `GetProperty<T>()`, usually in [`InitTask()`](/api/fair/mq/Device/#InitTask). [Command-line options](/reference/options/#custom-options) shows the code of the 1-1 example.
## Look at the configuration
- `--print-options` prints all options and their values, and stops. It does not show the channel properties, because the config plugin reads them later.
- At the start, the device logs all properties with the severity `debug`, after the line `Configuration:`.
- With `--severity trace`, the parsers log each property of each sub-channel.
- With `--severity debug`, the device logs `Attached channel <name> to <endpoint> (bind|connect) (<type>)` for each endpoint.
- In your code, [`GetPropertiesAsStringStartingWith("chans.")`](/api/fair/mq/ProgOptions/#GetPropertiesAsStringStartingWith) returns all channel properties as text.
## Related pages
- [Command-line options](/reference/options/): all options, with their types and defaults.
- [Channel properties](/reference/channel-properties/): the keys of the channel properties.
- [Configure channels](/guides/configure-channels/): `--channel-config`, JSON files and properties from code.
- [Plugins and control](/concepts/plugins/): the plugins that read and set properties.
- [Device states](/concepts/states/): the states `INITIALIZING DEVICE`, `BINDING` and `CONNECTING`.

View File

@@ -0,0 +1,240 @@
---
title: 'Devices'
description: 'A device is a class derived from fair::mq::Device. It has channels, a configuration, transports, a state machine and hooks for your code.'
sidebar:
order: 1
code: [fairmq/Device.h, fairmq/Device.cxx, fairmq/DeviceRunner.h, fairmq/DeviceRunner.cxx, fairmq/runDevice.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
A device is the part of a FairMQ topology that does the work. You write a class derived from
[`fair::mq::Device`](/api/fair/mq/Device/) and override its hooks. The state machine of the device
calls the hooks, and the channels of the device connect it to other devices.
## What a device has
Each device has these parts:
| Part | Access | Description |
| --- | --- | --- |
| Channels | [`GetChannels()`](/api/fair/mq/Device/#GetChannels), [`GetChannel()`](/api/fair/mq/Device/#GetChannel) | A map from the channel name to a `std::vector<Channel>` with the sub-channels. The device makes the channels from its properties in `INITIALIZING DEVICE`. |
| Configuration | [`fConfig`](/api/fair/mq/Device/#fConfig), [`GetConfig()`](/api/fair/mq/Device/#GetConfig) | A pointer to a [`ProgOptions`](/api/fair/mq/ProgOptions/) object. It holds all properties of the device, also the channel properties. |
| Transports | [`Transport()`](/api/fair/mq/Device/#Transport), [`AddTransport()`](/api/fair/mq/Device/#AddTransport) | One transport factory for each transport that the device uses. `Transport()` returns the default transport. |
| State machine | [`ChangeState()`](/api/fair/mq/Device/#ChangeState), [`GetCurrentState()`](/api/fair/mq/Device/#GetCurrentState) | A private member. It calls the hooks. See [Device states](/concepts/states/). |
| Id | [`GetId()`](/api/fair/mq/Device/#GetId) | The value of the property `id`. The device reads it in `INITIALIZING DEVICE`. |
| Version | [`GetVersion()`](/api/fair/mq/Device/#GetVersion) | The [`tools::Version`](/reference/tools/#versionh) that you give to the constructor. The default is `{0, 0, 0}`. |
The public member [`fChannels`](/api/fair/mq/Device/#fChannels) is deprecated. Use `GetChannels()`.
A device has four constructors. Copy and move are deleted.
<Snippet file="fairmq/Device.h" start=" Device();" end="Device(ProgOptions& config, tools::Version version);" />
If you do not give a `ProgOptions` object, the device makes its own (`fInternalConfig`).
[`SetConfig()`](/api/fair/mq/Device/#SetConfig) replaces it with your object. `DeviceRunner` calls
`SetConfig()` with its own `ProgOptions` before the device starts.
### The transports
In `INITIALIZING DEVICE`, the device reads the property `transport` (default `zeromq`). It makes the
default transport from this value. Then it makes one more transport for each other transport that a
channel uses. All channels with the same transport share one transport factory. See
[Transports](/concepts/transports/) and [Use several transports](/guides/several-transports/).
## The hooks
The hooks are protected virtual functions. Their default implementations do nothing, and
`ConditionalRun()` returns `false`. Override only the hooks that your device needs.
| Hook | State | When the device calls it |
| --- | --- | --- |
| [`Init()`](/api/fair/mq/Device/#Init) | `INITIALIZING DEVICE` | After the controller requests `CompleteInit`, before the device makes the channels. The header recommends `InitTask()` instead. |
| [`Bind()`](/api/fair/mq/Device/#Bind) | `BINDING` | After the device binds all channels with the method `bind`. |
| [`Connect()`](/api/fair/mq/Device/#Connect) | `CONNECTING` | After the device connects all channels with the method `connect`. |
| [`InitTask()`](/api/fair/mq/Device/#InitTask) | `INITIALIZING TASK` | Once. Read your options and allocate your resources here. |
| [`PreRun()`](/api/fair/mq/Device/#PreRun) | `RUNNING` | Once, at the start of `RUNNING`. |
| [`ConditionalRun()`](/api/fair/mq/Device/#ConditionalRun) | `RUNNING` | Again and again, while it returns `true` and no transition is pending. |
| [`Run()`](/api/fair/mq/Device/#Run) | `RUNNING` | Once, after the `ConditionalRun()` loop. |
| [`PostRun()`](/api/fair/mq/Device/#PostRun) | `RUNNING` | Once, at the end of `RUNNING`. A transition is pending at this time. |
| [`ResetTask()`](/api/fair/mq/Device/#ResetTask) | `RESETTING TASK` | Once. Undo the work of `InitTask()` here. |
| [`Reset()`](/api/fair/mq/Device/#Reset) | `RESETTING DEVICE` | After the device resets its transports, before it removes all channels. |
The device does not call `ConditionalRun()` and `Run()` when it has data callbacks (see below). The
state machine calls the hooks through a handler in the constructor of the device:
<Snippet file="fairmq/Device.cxx" start="fStateMachine.HandleStates([&](State state) {" />
Each wrapper function calls one or more hooks. For example, `InitTaskWrapper()` calls `InitTask()`
and then requests the transition `Auto`, if no other transition is pending. An exception in a hook moves the device to the state
`ERROR`. See [Handle errors and timeouts](/guides/errors-timeouts/).
Two more virtual functions are public:
- [`RegisterChannelEndpoints()`](/api/fair/mq/Device/#RegisterChannelEndpoints): `DeviceRunner`
calls it before the device starts. In it, call
[`RegisterChannelEndpoint()`](/api/fair/mq/Device/#RegisterChannelEndpoint) for each channel that
your device expects, with the minimum and maximum number of sub-channels (default 1 and 1).
- [`LogSocketRates()`](/api/fair/mq/Device/#LogSocketRates): in `RUNNING`, a separate thread runs it
when a channel has the property `rateLogging` larger than 0 (default 1). It logs the message rate
and the data rate of these channels every `rateLogging` seconds.
### A small example
This sampler of the example [1-1](/examples/1-1/) reads two options in `InitTask()` and sends one
message in each call of `ConditionalRun()`:
<Snippet file="examples/1-1/sampler.cxx" start="struct Sampler : fair::mq::Device" />
## Data callbacks
A device can register data callbacks with [`OnData()`](/api/fair/mq/Device/#OnData). The device
then calls the callback for each message that arrives on the channel. A callback receives a message
(`MessagePtr&`) or a multipart message (`Parts&`), and the index of the sub-channel. It returns
`true` to continue, or `false` to end `RUNNING`.
<Snippet file="examples/1-1/sink.cxx" start=" Sink()" />
Register the callbacks before the device enters `RUNNING`, for example in the constructor. See
[Receive data with callbacks or loops](/guides/receive-data/) for all forms of `OnData()`. For the
thread that calls the callbacks, see [Which thread runs your code](/concepts/threads/#which-thread-runs-your-code).
## Helper functions
The device has helper functions for the work in the hooks:
| Function | Description |
| --- | --- |
| [`Send(msg, channel, index = 0)`](/api/fair/mq/Device/#Send), [`Receive(msg, channel, index = 0)`](/api/fair/mq/Device/#Receive) | Send or receive a `MessagePtr`, a `Parts` or a `std::vector<MessagePtr>` on the sub-channel `index` of the channel. Overloads with a fourth argument set a timeout in ms ([`Send-2`](/api/fair/mq/Device/#Send-2), [`Receive-2`](/api/fair/mq/Device/#Receive-2)). They return the number of bytes or a negative [transfer code](/reference/transfer-codes/). |
| [`NewMessage(args...)`](/api/fair/mq/Device/#NewMessage) | Makes a message with the default transport. The arguments go to `TransportFactory::CreateMessage()`. |
| [`NewMessageFor(channel, index, args...)`](/api/fair/mq/Device/#NewMessageFor) | Makes a message with the transport of the sub-channel. |
| [`NewSimpleMessage(data)`](/api/fair/mq/Device/#NewSimpleMessage), [`NewSimpleMessageFor(channel, index, data)`](/api/fair/mq/Device/#NewSimpleMessageFor) | Makes a message with a copy of `data`. |
| [`NewStaticMessage(data)`](/api/fair/mq/Device/#NewStaticMessage), [`NewStaticMessageFor(channel, index, data)`](/api/fair/mq/Device/#NewStaticMessageFor) | Makes a message that does not free `data` after the transfer. The `zeromq` transport uses `data` without a copy. The `shmem` transport copies it. |
| [`NewUnmanagedRegion(args...)`](/api/fair/mq/Device/#NewUnmanagedRegion), [`NewUnmanagedRegionFor(channel, index, args...)`](/api/fair/mq/Device/#NewUnmanagedRegionFor) | Makes an unmanaged region. See [Unmanaged regions](/shmem/regions/). |
| [`NewPoller("a", "b")`](/api/fair/mq/Device/#NewPoller), [`NewPoller(channels)`](/api/fair/mq/Device/#NewPoller-2) | Makes a poller for channel names or for a `std::vector<Channel*>`. All channels must use the same transport. Otherwise the function throws `std::runtime_error`. See [Poll several channels](/guides/poll-channels/). |
| [`GetChannel(name, index = 0)`](/api/fair/mq/Device/#GetChannel) | Returns the sub-channel. Throws `std::out_of_range` if it does not exist. |
| [`GetNumSubChannels(name)`](/api/fair/mq/Device/#GetNumSubChannels) | Returns the number of sub-channels of a channel. |
| [`GetNumberOfConnectedPeers(name, index = 0)`](/api/fair/mq/Device/#GetNumberOfConnectedPeers) | Returns the number of peers that are connected to the sub-channel. |
| [`AddChannel(name, channel)`](/api/fair/mq/Device/#AddChannel) | Adds the properties of a `Channel` object to the configuration, except `sndTimeoutMs` and `rcvTimeoutMs`. The device makes the channel in `INITIALIZING DEVICE`. |
| [`GetConfig()`](/api/fair/mq/Device/#GetConfig) | Returns the `ProgOptions` object. Use `GetConfig()->GetProperty<T>(key)` to read an option. |
| [`GetId()`](/api/fair/mq/Device/#GetId) | Returns the id of the device. |
| [`NewStatePending()`](/api/fair/mq/Device/#NewStatePending) | Returns `true` when a transition is requested and the next state has not started yet. |
| [`WaitFor(duration)`](/api/fair/mq/Device/#WaitFor) | Waits for the duration. Returns `false` if a transition is requested before the end of the duration. |
| [`ChangeState(transition)`](/api/fair/mq/Device/#ChangeState), [`ChangeStateOrThrow(transition)`](/api/fair/mq/Device/#ChangeStateOrThrow) | Request a transition. See [States and transitions](/reference/states/). |
| [`GetCurrentState()`](/api/fair/mq/Device/#GetCurrentState), [`GetCurrentStateName()`](/api/fair/mq/Device/#GetCurrentStateName) | Return the current state. |
| [`WaitForState(state)`](/api/fair/mq/Device/#WaitForState), [`WaitForNextState()`](/api/fair/mq/Device/#WaitForNextState) | Wait in another thread for a state of the device. |
| [`SubscribeToStateChange(key, callback)`](/api/fair/mq/Device/#SubscribeToStateChange) | Calls `callback` at the start of each new state, in the thread of the state machine. |
| [`RunStateMachine()`](/api/fair/mq/Device/#RunStateMachine) | Runs the state machine in the calling thread, until the state `EXITING` or `ERROR`. |
Some setters change a property in the configuration, for example
[`SetTransport()`](/api/fair/mq/Device/#SetTransport) (`transport`) and
[`SetNumIoThreads()`](/api/fair/mq/Device/#SetNumIoThreads) (`io-threads`). The device reads most of
these properties in `INITIALIZING DEVICE`. For all properties, see
[Configuration and properties](/concepts/configuration/).
## How a device starts
Most devices use the header `fairmq/runDevice.h`. It defines a `main()` function that runs one
device with the class [`DeviceRunner`](/api/fair/mq/DeviceRunner/).
### Use runDevice.h
<Steps>
1. Include `<fairmq/runDevice.h>` in one source file of your executable.
2. Write the function `addCustomOptions()`. Add your options to the `options_description`. If you
have no options, leave the body empty.
<Snippet file="examples/1-1/sampler.cxx" start="void addCustomOptions" />
3. Write the function `getDevice()`. Return a new object of your device class.
<Snippet file="examples/1-1/sampler.cxx" start="std::unique_ptr<fair::mq::Device> getDevice" />
</Steps>
The `main()` function of `runDevice.h` adds these two functions as hooks of `DeviceRunner`:
<Snippet file="fairmq/runDevice.h" start="int main(int argc, char* argv[])" />
An exception that reaches `main()` gives the log line `Uncaught exception reached the top of main:`
and the exit code 1.
:::note[Old header]
`fairmq/runFairMQDevice.h` is the old form of this header. There, `getDevice()` takes a
`const fair::mq::ProgOptions&` and returns a raw pointer. Use `fairmq/runDevice.h` for new code.
:::
### What DeviceRunner does
[`DeviceRunner::Run()`](/api/fair/mq/DeviceRunner/#Run) starts the device in this sequence. The
constructor of `DeviceRunner` already loads the plugins of the option `-P`.
<Steps>
1. Load the built-in plugin `config`.
2. Call the hook `LoadPlugins`.
3. Load the built-in plugin `control`.
4. Call the hook `SetCustomCmdLineOptions`.
5. Add the options of all plugins and of the plugin manager.
6. Call the hook `ModifyRawCmdLineArgs`.
7. Parse the command line. For `--help` or `--print-options`, print the output and return 0.
8. Set up the logger from the logging options.
9. Call the hook `InstantiateDevice`. If the hook does not set `fDevice`, log an error and return 1.
10. Call `RegisterChannelEndpoints()` of the device. For `--print-channels` or `--version`, return 0.
11. Give the configuration to the device (`SetConfig()`), and instantiate the plugins.
12. Log the configuration, and call `RunStateMachine()` of the device.
13. When the state machine stops, wait until all plugins release the device control. Return 0.
</Steps>
You add a hook with [`AddHook<H>()`](/api/fair/mq/DeviceRunner/#AddHook). A hook is a function
`void(DeviceRunner&)`. It can use all members of the runner: `fRawCmdLineArgs`, `fConfig`,
`fDevice` and `fPluginManager`.
| Hook (`fair::mq::hooks::`) | Typical use |
| --- | --- |
| `LoadPlugins` | Load more plugins with `r.fPluginManager.LoadPlugin()`. |
| `SetCustomCmdLineOptions` | Add options with `r.fConfig.AddToCmdLineOptions()`. |
| `ModifyRawCmdLineArgs` | Change the arguments in `r.fRawCmdLineArgs` before the parser reads them. |
| `InstantiateDevice` | Make the device and put it into `r.fDevice`. |
You can write your own `main()` with `DeviceRunner`. The example
[custom-controller](/examples/custom-controller/) loads its own control plugin in the hook
`LoadPlugins`:
<Snippet file="examples/custom-controller/main.cxx" start="int main(int argc, char* argv[])" />
[`RunWithExceptionHandlers()`](/api/fair/mq/DeviceRunner/#RunWithExceptionHandlers) calls `Run()`
and catches all exceptions. It logs `Uncaught exception reached the top of DeviceRunner:` and
returns 1.
:::caution[Known defect]
For `--print-channels` and `--version`, `DeviceRunner` sets the console severity to `nolog` and then
prints with `LOG`. Thus both options print nothing in this version. The device does not start.
:::
A process can also run more than one device without `DeviceRunner`. Then your code must call
`RunStateMachine()` and request the transitions. See
[Control a device from code](/guides/control-from-code/).
## The life of a device
A device starts in the state `IDLE`. A controller, usually the control plugin, requests the
transitions. The device initializes in steps, for example `BINDING` and `CONNECTING`, until it is
`READY`. In `RUNNING`, the device processes data. When the work ends, the device goes back to
`READY`. Then it resets in two steps back to `IDLE`, and ends in `EXITING`.
For the states, the transitions and the hooks in each state, see [Device states](/concepts/states/).
## Related pages
- [Device states](/concepts/states/): the state machine and the hooks in each state.
- [Receive data with callbacks or loops](/guides/receive-data/): `OnData()`, `ConditionalRun()` and
`Run()`.
- [Channels and sockets](/concepts/channels/): the channels of a device.
- [Configuration and properties](/concepts/configuration/): the properties that a device reads.
- [Plugins and control](/concepts/plugins/): the plugins that control the device.
- [Threads in a device](/concepts/threads/): the thread that runs each hook and callback.

View File

@@ -0,0 +1,246 @@
---
title: 'Messages and multipart'
description: 'How to make a message, who owns its buffer before and after Send(), and how to send several parts in one transfer with fair::mq::Parts.'
sidebar:
order: 4
code: [fairmq/Message.h, fairmq/Parts.h, fairmq/TransportFactory.h, fairmq/Channel.h]
---
import Snippet from '../../../components/Snippet.astro';
A message is the unit of data that a channel sends and receives. The transport allocates the buffer
of the message, and the owner of the buffer changes when you send it. A multipart message sends
several messages in one transfer.
## The message object
[`fair::mq::Message`](/api/fair/mq/Message/) is an interface. Each transport has its own
implementation: the zeromq message holds a `zmq_msg_t`, the shmem message holds a handle to a buffer
in shared memory. You use a message through [`fair::mq::MessagePtr`](/api/fair/mq/#MessagePtr),
which is a `std::unique_ptr<Message>`. You cannot copy or move a `Message` object, but you can move
the `MessagePtr`.
| Function | What it does |
| --- | --- |
| [`GetData()`](/api/fair/mq/Message/#GetData) | Returns a pointer to the buffer, or `nullptr` if the message has no buffer. |
| [`GetSize()`](/api/fair/mq/Message/#GetSize) | Returns the size of the buffer in bytes. |
| [`SetUsedSize(size, alignment)`](/api/fair/mq/Message/#SetUsedSize) | Makes the buffer smaller. See [Change the size](#change-the-size). |
| [`Rebuild(…)`](/api/fair/mq/Message/#Rebuild) | Releases the buffer and initializes the message again. |
| [`Copy(other)`](/api/fair/mq/Message/#Copy) | Makes the message use the buffer of `other`. |
| [`GetType()`](/api/fair/mq/Message/#GetType) | Returns the transport type, [`Transport::ZMQ`](/api/fair/mq/Transport/#ZMQ) or [`Transport::SHM`](/api/fair/mq/Transport/#SHM). |
| [`GetTransport()`](/api/fair/mq/Message/#GetTransport) | Returns a pointer to the [`TransportFactory`](/api/fair/mq/TransportFactory/) that made the message. |
## Make a message
A device makes messages with [`NewMessage(args…)`](/api/fair/mq/Device/#NewMessage). It forwards
the arguments to [`CreateMessage()`](/api/fair/mq/TransportFactory/#CreateMessage) of the default
transport of the device. [`NewMessageFor(channel, index, args…)`](/api/fair/mq/Device/#NewMessageFor)
uses the transport of the sub-channel `index` of `channel`. A
[`Channel`](/api/fair/mq/Channel/#NewMessage) has a `NewMessage(args…)` function too.
| Arguments | Result |
| --- | --- |
| none | An empty message without a buffer. Use it to receive. |
| `Alignment{64}` | An empty message to receive into. The zeromq transport aligns the received buffer to 64 bytes. |
| `size` | A message with a buffer of `size` bytes from the transport. |
| `size, Alignment{64}` | A buffer of `size` bytes, aligned to 64 bytes. |
| `data, size, ffn, hint` | A message for your buffer. See [Your own buffer](#your-own-buffer). |
| `region, data, size, hint` | A message for a block of an unmanaged region. See [Unmanaged regions](/shmem/regions/). |
A `std::pmr` container can also become a message without a copy:
[`fair::mq::getMessage()`](/api/fair/mq/#getMessage) makes the message from a container that
allocates from the memory resource of the transport. See
[Use std::pmr memory resources](/guides/pmr/).
[`fair::mq::Alignment`](/api/fair/mq/Alignment/) is a struct with one `size_t` member. The value 0
means "no alignment", which is the default. The shmem transport aligns each buffer to at least
`alignof(std::max_align_t)`. It ignores the alignment of an empty message, because the receiver gets
the buffer that the sender allocated.
:::caution[Use messages only while the transports exist]
The device makes its transports in the state `INITIALIZING DEVICE`, after it calls `Init()`. Do not
call `NewMessage()` in the constructor or in `Init()`. Call it in `InitTask()`, `Run()`,
`ConditionalRun()` or in a data callback. The device destroys its transports in the state
`RESETTING DEVICE`. Destroy the messages that your device class keeps in `ResetTask()`. In a build
with the CMake option `FAIRMQ_DEBUG_MODE`, the shmem transport checks this before the device calls
`Reset()`. It throws `MessageError` if messages still exist.
:::
### Your own buffer
`NewMessage(data, size, ffn, hint)` makes a message for a buffer that you allocated. `ffn` is a
deleter of the type [`fair::mq::FreeFn`](/api/fair/mq/#FreeFn), `void(void* data, void* hint)`. The
transport calls `ffn(data, hint)` when it does not need the buffer any more. The
[1-1 example](/examples/1-1/) sends a string this way:
<Snippet file="examples/1-1/sampler.cxx" start="std::string* text = new std::string(fText);" end="text));" />
The two transports use the buffer differently:
- The zeromq transport does not copy the buffer. ZeroMQ calls `ffn` after the transfer. ZeroMQ can
make this call from one of its own threads, so `ffn` must be thread-safe. See
[Threads in a device](/concepts/threads/).
- The shmem transport copies the buffer into the shared memory segment when it makes the message.
Then it calls `ffn` immediately. If `ffn` is `nullptr`, it calls `free(data)`
([shmem/Message.h](/source/fairmq/shmem/Message.h/#L64-L78)). For a size of 0, it does not call
`ffn` and does not free the buffer.
Always give a deleter. For a buffer that you release yourself, give
[`TransportFactory::NoCleanup`](/api/fair/mq/TransportFactory/#NoCleanup).
### Small values and strings
[`NewSimpleMessage(value)`](/api/fair/mq/Device/#NewSimpleMessage) copies `value` into a new
message, and the message owns the copy. For a type `T`, the message has `sizeof(T)` bytes. `T` must
be trivially copyable, because the receiver gets the bytes only. For a string literal and a
`std::string`, the message holds the characters without the terminating zero.
[Limits of NewSimpleMessage()](/guides/send-data-types/#limits-of-newsimplemessage) lists the types
that do not work.
[`NewStaticMessage(str)`](/api/fair/mq/Device/#NewStaticMessage) makes a message for the buffer of
the `std::string` `str`, with the deleter `NoCleanup`. The zeromq transport does not copy the buffer
and does not tell you when the transfer ends. Use it only for a string that does not change and that
lives longer than the transport. The transports of a device live until `RESETTING DEVICE`, so a
member of the device is enough. The shmem transport copies the string when it makes the message.
The test of the transport factory shows both functions:
<Snippet file="test/transport/_factory.cxx" start="// NewSimpleMessage() copies the data" end="^}" />
:::caution
Use `NewStaticMessage()` with a `std::string` only. The template overload
`NewStaticMessage(const T& data)` gives `data` itself as the buffer pointer and `sizeof(T)` as the
size ([TransportFactory.h](/source/fairmq/TransportFactory.h/#L225-L229)).
:::
The functions `NewSimpleMessageFor()` and `NewStaticMessageFor()` take a channel name and a
sub-channel index first, like `NewMessageFor()`.
## Change the size
[`SetUsedSize(size)`](/api/fair/mq/Message/#SetUsedSize) makes the buffer smaller. Use it when you
allocate the maximum size first and know the real size later. It returns `true` if the size is
equal to or smaller than the current size, and `false` if the size is larger. The message test shows
the rules:
<Snippet file="test/message/_message.cxx" start="auto outMsg(push.NewMessage(size));" end="ASSERT_EQ(outMsg->GetSize(), 5);" />
The zeromq transport keeps the full buffer until it releases the message. The shmem transport
shrinks the buffer in the segment where possible, and `SetUsedSize(0)` releases the buffer.
## Rebuild and copy a message
[`Rebuild()`](/api/fair/mq/Message/#Rebuild) releases the buffer of the message and initializes the
message again. It has five overloads with the same arguments as `NewMessage()`, but without the
region overload. Use `Rebuild()` to use one message object for many transfers.
[`Copy(other)`](/api/fair/mq/Message/#Copy) makes the message use the buffer of `other`. The
current transports share the buffer and do not copy the data, but the interface does not guarantee
it. The shmem transport increments a reference count in shared memory, also for messages of other
processes. The zeromq transport calls `zmq_msg_copy()`. Do not change the buffer after `Copy()`.
Both messages must use the same transport. The [copypush example](/examples/copypush/)
sends one buffer on several sub-channels:
<Snippet file="examples/copypush/sampler.cxx" start="fair::mq::MessagePtr msg(NewSimpleMessage(fCounter++));" end='Send(msg, "data", fNumDataChannels - 1);' />
## Send and receive a message
[`Send(msg, channel, index)`](/api/fair/mq/Device/#Send) takes a reference to the `MessagePtr`. It
returns the number of bytes, or a negative
[transfer code](/reference/transfer-codes/) for a timeout, an interruption or an error.
After a successful `Send()`, the transport owns the buffer. The `MessagePtr` still holds a message
object, but you must not read or write its data:
- The zeromq transport gives the message to `zmq_msg_send()`. On success, ZeroMQ empties the
message, and `GetSize()` returns 0.
- The shmem transport keeps the old size and pointer in the message. The buffer belongs to the
receiver now.
To send the same data on two channels, make a second message with `Copy()` before the first
`Send()`. To use the message object again, call `Rebuild()`. If `Send()` returns a negative value,
the message keeps its buffer, and you can send it again.
[`Receive(msg, channel, index)`](/api/fair/mq/Device/#Receive) puts the received buffer into `msg`.
Receive into an empty message: make a new one with `NewMessage()`, or call `Rebuild()` on a used
one. The shmem transport does not release a buffer that the message already holds. The received
message owns its buffer. When you destroy the message, the transport releases the buffer.
### A message of another transport
[`Channel::Send()`](/api/fair/mq/Channel/#Send) compares the transport of each message with the
transport of the channel ([Channel.h](/source/fairmq/Channel.h/#L421-L480)). If they are different,
the channel makes a new message of its own transport, and your `MessagePtr` points to the new
message after the call:
- If the channel uses zeromq, the new message points to the buffer of your message. FairMQ does not
copy the data. It destroys your message when zeromq releases the buffer.
- If the channel uses shmem, the new message has a copy of the data in shared memory. FairMQ
destroys your message immediately.
- An empty message becomes an empty message of the channel transport.
[`Channel::Receive()`](/api/fair/mq/Channel/#Receive) replaces a message of another transport with
an empty message of the channel transport. To prevent the conversion, make the message with
`NewMessageFor()`. See [Use several transports](/guides/several-transports/).
## Multipart messages
[`fair::mq::Parts`](/api/fair/mq/Parts/) holds a `std::vector<MessagePtr>`. Each message in it is a
part. You can move a `Parts` object, but you cannot copy it.
| Function | What it does |
| --- | --- |
| [`Parts(part1, part2, …)`](/api/fair/mq/Parts/#Parts-4) | Makes a `Parts` object from `MessagePtr` values. |
| [`AddPart(part)`](/api/fair/mq/Parts/#AddPart-2) | Adds a `MessagePtr` at the end. |
| [`AddPart(part1, part2, …)`](/api/fair/mq/Parts/#AddPart-3) | Adds several parts at the end. |
| [`AddPart(otherParts)`](/api/fair/mq/Parts/#AddPart-4) | Moves all parts of another `Parts` object to the end. |
| [`operator[](i)`](/api/fair/mq/Parts/#operator-index) | Returns the part `i` as `Message&`. It does not check the index. |
| [`At(i)`](/api/fair/mq/Parts/#At) | Returns the `MessagePtr&` of the part `i`, and throws `std::out_of_range` for a bad index. You can replace the part through it. |
| [`Size()`](/api/fair/mq/Parts/#Size), [`Empty()`](/api/fair/mq/Parts/#Empty), [`Clear()`](/api/fair/mq/Parts/#Clear) | Return the number of parts, check for zero parts, remove all parts. |
| [`begin()`](/api/fair/mq/Parts/#begin), [`end()`](/api/fair/mq/Parts/#end), `cbegin()`, `cend()` | Iterate over the `MessagePtr` elements, for example in a range-based `for` loop. |
`AddPart(Message*)` and `AtRef(i)` are deprecated. The old name `FairMQParts` is an alias of
`fair::mq::Parts` (see [Move from the FairMQ* names](/guides/migrate-names/)).
The sampler of the [multipart example](/examples/multipart/) makes seven parts. It moves three of
them from a second `Parts` object with `AddPart()`, and one part is empty:
<Snippet file="examples/multipart/sampler.cxx" start="fair::mq::Parts parts;" end='Send(parts, "data");' />
The sink receives all parts in one data callback:
<Snippet file="examples/multipart/sink.cxx" start="bool HandleData(fair::mq::Parts& parts, int)" end="header.stopFlag = (static_cast" />
### How a multipart message travels
`Send(parts, …)` sends all parts in one transfer. The receiver gets all parts, in the same order, in
one `Receive(parts, …)` call. `Send()` returns the sum of the sizes of the parts. The channel
counts the transfer as one message in its statistics.
- The zeromq transport sends one zeromq multipart message, with one frame for each part.
- The shmem transport sends one metadata message with the number of parts and the metadata of each
part. The data of the parts stays in shared memory.
`Send()` and `Receive()` also accept a `std::vector<MessagePtr>`. The rules for single messages
apply to each part. This test sends three parts, one of them empty, and receives them:
<Snippet file="test/parts/_access.cxx" start="Parts out(" end="EXPECT_EQ(AsString(in[2])" />
:::caution[Rules for multipart messages]
- Do not send an empty `Parts` object. The zeromq transport returns `TransferCode::error`, but the
shmem transport sends a message with zero parts.
- Receive with the same form that the sender uses: `Parts` for `Parts`, `MessagePtr` for
`MessagePtr`. The shmem transport cannot read a single message into a `Parts` object.
- `Receive()` adds the received parts at the end of the `Parts` object. Give it an empty one.
- A receiver with [`OnData()`](/api/fair/mq/Device/#OnData-3) must register a callback that takes
`fair::mq::Parts&`.
:::
## Related pages
- [Channels and sockets](/concepts/channels/): the channels that send and receive the messages.
- [Transports](/concepts/transports/): how zeromq and shmem move the data.
- [Use several transports](/guides/several-transports/): make messages for the right transport.
- [Unmanaged regions](/shmem/regions/): messages for blocks of your own shared memory.
- [Transfer codes and errors](/reference/transfer-codes/): the return values of `Send()` and `Receive()`.
- [Send your own data types](/guides/send-data-types/): structs, arrays and serialized objects in messages.
- [Use std::pmr memory resources](/guides/pmr/): send a `std::pmr` container without a copy.

View File

@@ -0,0 +1,264 @@
---
title: 'Plugins and control'
description: 'How plugins extend a device, how the plugin manager loads them, what they can do, and how the built-in control plugin drives the state machine.'
sidebar:
order: 7
code: [fairmq/Plugin.h, fairmq/PluginManager.cxx, fairmq/PluginServices.h, fairmq/plugins/control/Control.cxx, fairmq/DeviceRunner.cxx]
---
import OptionsTable from '../../../components/OptionsTable.astro';
import Snippet from '../../../components/Snippet.astro';
A plugin is a class that runs in the process of a device. It can read and set properties, follow the state of the
device and drive the state machine. Each device that starts with `runDevice.h` has two built-in plugins: `config`
reads the channel configuration, and `control` moves the device through its states.
## Parts of the plugin system
| Class | Task |
| --- | --- |
| [`fair::mq::Plugin`](/api/fair/mq/Plugin/) | The base class of all plugins. It holds the name, the version, the maintainer and the homepage of the plugin, and it gives the plugin API. |
| [`fair::mq::PluginManager`](/api/fair/mq/PluginManager/) | Finds, loads, creates and owns the plugins. |
| [`fair::mq::PluginServices`](/api/fair/mq/PluginServices/) | Connects the plugins to the device and to its properties. All plugins of a device use the same object. |
| [`fair::mq::DeviceRunner`](/api/fair/mq/DeviceRunner/) | Starts the device with its properties and its plugins. `runDevice.h` uses it. |
A plugin does not use the device directly. Each call goes through `PluginServices`:
```txt
plugin ──► PluginServices ──► Device (state, transitions)
└─► ProgOptions (properties)
```
## How a device starts
[`DeviceRunner::Run()`](/api/fair/mq/DeviceRunner/#Run) loads and creates the plugins in this sequence
([DeviceRunner.cxx](/source/fairmq/DeviceRunner.cxx/#L108-L194)):
1. The constructor of `DeviceRunner` makes the plugin manager. The plugin manager reads `-S` and `-P` and loads the
plugins of `-P`, in their sequence.
2. `Run()` loads the built-in plugin `config`.
3. The runner hook `hooks::LoadPlugins` runs. Your code can load more plugins here.
4. `Run()` loads the built-in plugin `control`.
5. The runner hook `hooks::SetCustomCmdLineOptions` runs. `runDevice.h` adds the options of `addCustomOptions()`
here.
6. The runner adds the options of all plugins to the command-line options. The runner hook
`hooks::ModifyRawCmdLineArgs` runs. Then the runner parses the command line. With `--help` or `--print-options`,
`Run()` prints the options and returns 0.
7. The runner hook `hooks::InstantiateDevice` makes the device.
8. The plugin manager makes the `PluginServices` object. Then it creates the plugins, in the load sequence.
9. The device runs its state machine until the state `EXITING`.
10. The runner waits until no plugin has the controller role. Then `Run()` returns 0.
The constructor of a plugin runs after the parsing of the command line, so a plugin can read its options there. The
control plugin comes last. A plugin that takes the controller role in its constructor gets it before the control
plugin.
To load plugins without `DeviceRunner`, see
[Load plugins without DeviceRunner](/guides/control-from-code/#load-plugins-without-devicerunner).
## Load a plugin
Give the name of a plugin to `-P` (`--plugin`), or to
[`PluginManager::LoadPlugin()`](/api/fair/mq/PluginManager/#LoadPlugin) in a runner hook. A prefix selects the
mechanism ([PluginManager.cxx](/source/fairmq/PluginManager.cxx/#L135-L150)):
| Name | Mechanism | Where the plugin manager looks |
| --- | --- | --- |
| `name` or `d:name` | Dynamic | In a shared library file. See [Plugin files and search paths](#plugin-files-and-search-paths). |
| `p:name` | Prelinked | In the program. The executable links the library of the plugin at build time. |
| `s:name` | Static | In the program: the built-in plugins `config` and `control`, or a plugin that the executable contains. |
Give `-P` once for each plugin, for example `-P first -P second`. The plugin manager does not split a name at commas.
It loads a dynamic or a prelinked plugin only once, also when you give its name twice.
### Plugin files and search paths
For the dynamic plugin `name`, the plugin manager looks for two file names:
`libfairmq-plugin-name.so` and then `libFairMQPlugin_name.so` (the suffix is the one of the platform, `.so` on Linux).
It looks in these places, in this sequence:
1. Each directory of `-S` (`--plugin-search-path`).
2. The system lookup of the dynamic linker: the system library directories, `RUNPATH` and `LD_LIBRARY_PATH`.
`-S` takes one or more directories. The paths without a prefix make the list. Then the plugin manager puts each path
with the prefix `<` at the start of the list. It puts each path with the prefix `>` at the end. Without `-S`, the list
is empty. The test `PluginManager.Factory` gives this example:
```sh
-S '>/lib' '</home/user/lib' /usr/local/lib /usr/lib
```
The search paths are then `/home/user/lib`, `/usr/local/lib`, `/usr/lib` and `/lib`. Put quotes around paths with
`<` or `>`, because the shell uses these characters for redirection. The plugin manager ignores a directory that does
not exist. A path to a file, or an empty path, gives the error `PluginManager::BadSearchPath`.
When no file loads, the plugin manager throws `PluginManager::PluginLoadError`:
```txt
Could not load dynamic plugin name from configured search paths (-S) nor with system lookup (system libdirs, RUNPATH, $LD_LIBRARY_PATH).
```
The `main()` function of `runDevice.h` catches the exception, logs it and returns 1. A file that exists but does not
load, for example because of a missing symbol, gives the same error.
## What a plugin can do
The functions of `fair::mq::Plugin` call `PluginServices`. They give the name of the plugin as the ID of the
subscriber and of the controller.
| Area | Functions |
| --- | --- |
| State | [`GetCurrentDeviceState()`](/api/fair/mq/Plugin/#GetCurrentDeviceState), [`SubscribeToDeviceStateChange()`](/api/fair/mq/Plugin/#SubscribeToDeviceStateChange), [`UnsubscribeFromDeviceStateChange()`](/api/fair/mq/Plugin/#UnsubscribeFromDeviceStateChange), [`ToDeviceState()`](/api/fair/mq/Plugin/#ToDeviceState), [`ToDeviceStateTransition()`](/api/fair/mq/Plugin/#ToDeviceStateTransition), [`ToStr()`](/api/fair/mq/Plugin/#ToStr) |
| Control | [`TakeDeviceControl()`](/api/fair/mq/Plugin/#TakeDeviceControl), [`StealDeviceControl()`](/api/fair/mq/Plugin/#StealDeviceControl), [`ReleaseDeviceControl()`](/api/fair/mq/Plugin/#ReleaseDeviceControl), [`ChangeDeviceState()`](/api/fair/mq/Plugin/#ChangeDeviceState) |
| Read properties | [`PropertyExists()`](/api/fair/mq/Plugin/#PropertyExists), [`GetProperty<T>()`](/api/fair/mq/Plugin/#GetProperty), [`GetPropertyAsString()`](/api/fair/mq/Plugin/#GetPropertyAsString), [`GetProperties()`](/api/fair/mq/Plugin/#GetProperties), [`GetPropertiesStartingWith()`](/api/fair/mq/Plugin/#GetPropertiesStartingWith), [`GetPropertiesAsString()`](/api/fair/mq/Plugin/#GetPropertiesAsString), [`GetPropertiesAsStringStartingWith()`](/api/fair/mq/Plugin/#GetPropertiesAsStringStartingWith), [`GetPropertyKeys()`](/api/fair/mq/Plugin/#GetPropertyKeys), [`GetChannelInfo()`](/api/fair/mq/Plugin/#GetChannelInfo) |
| Change properties | [`SetProperty<T>()`](/api/fair/mq/Plugin/#SetProperty), [`SetProperties()`](/api/fair/mq/Plugin/#SetProperties), [`UpdateProperty<T>()`](/api/fair/mq/Plugin/#UpdateProperty), [`UpdateProperties()`](/api/fair/mq/Plugin/#UpdateProperties), [`DeleteProperty()`](/api/fair/mq/Plugin/#DeleteProperty) |
| Property changes | [`SubscribeToPropertyChange<T>()`](/api/fair/mq/Plugin/#SubscribeToPropertyChange), [`UnsubscribeFromPropertyChange<T>()`](/api/fair/mq/Plugin/#UnsubscribeFromPropertyChange), [`SubscribeToPropertyChangeAsString()`](/api/fair/mq/Plugin/#SubscribeToPropertyChangeAsString), [`UnsubscribeFromPropertyChangeAsString()`](/api/fair/mq/Plugin/#UnsubscribeFromPropertyChangeAsString) |
| Logging | [`CycleLogConsoleSeverityUp()`](/api/fair/mq/Plugin/#CycleLogConsoleSeverityUp), [`CycleLogConsoleSeverityDown()`](/api/fair/mq/Plugin/#CycleLogConsoleSeverityDown), [`CycleLogVerbosityUp()`](/api/fair/mq/Plugin/#CycleLogVerbosityUp), [`CycleLogVerbosityDown()`](/api/fair/mq/Plugin/#CycleLogVerbosityDown) |
| Metadata | [`GetName()`](/api/fair/mq/Plugin/#GetName), [`GetVersion()`](/api/fair/mq/Plugin/#GetVersion), [`GetMaintainer()`](/api/fair/mq/Plugin/#GetMaintainer), [`GetHomepage()`](/api/fair/mq/Plugin/#GetHomepage) |
The state machine calls the state callback at the start of each new state, in the thread of the state machine. The
device starts the handler of the state after all callbacks return, so keep the callbacks short. A callback for a
property change runs in the thread that changes the property.
`GetNumberOfConnectedPeers()` exists for tests. The code marks it for removal.
## The controller role
Only one plugin at a time can change the state of the device. This plugin is the controller.
| Function | Effect |
| --- | --- |
| `TakeDeviceControl()` | The plugin becomes the controller, if no plugin has the role. If the plugin has the role, nothing changes. If another plugin has the role, the function throws `PluginServices::DeviceControlError`. |
| `ChangeDeviceState(transition)` | Requests a transition. If no plugin has the role, the plugin takes it first. If another plugin has the role, the function throws `DeviceControlError`. It returns `false` when the device cannot do the transition now. |
| `StealDeviceControl()` | The plugin becomes the controller, also when another plugin has the role. The control plugin uses it after a signal. |
| `ReleaseDeviceControl()` | The plugin gives the role back, if it has the role. |
`DeviceRunner` waits after the end of the state machine until no plugin has the role. Thus a controller must release
the role, normally in the state `EXITING`.
The device changes the state when the handler of the current state returns. A requested transition interrupts
blocking transfers, and [`NewStatePending()`](/api/fair/mq/Device/#NewStatePending) then returns `true`, so that the
handler can return. See [Device states](/concepts/states/).
## The config plugin
The built-in plugin `config` adds the device options, for example `--id`, `--transport`, `--session`, `--rate`,
`--mq-config`, `--channel-config` and the options of the `shmem` transport. At the start of the state
`INITIALIZING DEVICE`, it reads the channel configuration and sets the channel properties:
<Snippet file="fairmq/plugins/config/Config.cxx" start="SubscribeToDeviceStateChange" />
The key of the device in the configuration is `--config-key`, or `--id` if `--config-key` is not set. `--mq-config`
has priority over `--channel-config`. When the parser fails, the plugin logs the error and the device continues. See
[Configuration and properties](/concepts/configuration/).
## The control plugin
The built-in plugin `control` has two options: `--control` (default `dynamic`) and `--catch-signals` (default `1`).
Its constructor takes the controller role, unless `--control` is `none`. If another plugin has the role already, the
control plugin logs the reason at the severity `debug` and starts no controller. Its signal handling does not depend
on the controller role.
### Control modes
| `--control` | What the control plugin does |
| --- | --- |
| `dynamic` (default), `interactive`, `external` | It runs the startup sequence. Then it reads keys from the terminal until you press `q`, and runs the shutdown sequence. |
| `static` | It runs the startup sequence. When the device goes back to `READY`, for example because `ConditionalRun()` returns `false`, it runs the shutdown sequence. |
| `gui` | It runs the startup sequence. Then it waits for a signal or for the state `ERROR`. |
| `none` | It does not take the controller role. Another plugin or your code must change the states. |
| Another value | It logs `Unrecognized control mode` at the severity `error` and uses `static`. |
Use `--control static` in scripts. This mode needs no terminal, and it ends the device when the work in `RUNNING` is
done. The test scripts of the examples use it.
For the effect of each mode on the end of a run, see
[What the controllers do](/guides/end-of-run/#what-the-controllers-do).
The startup sequence requests the transitions `INIT DEVICE`, `COMPLETE INIT`, `BIND`, `CONNECT`, `INIT TASK` and
`RUN`. Before each request, the plugin waits for the state that the previous transition gives. At the end, the device
is in `RUNNING`.
The shutdown sequence starts from the current state and repeats until `EXITING`. Then the plugin releases the
controller role.
| Current state | Transition |
| --- | --- |
| `RUNNING` | `STOP` |
| `READY` | `RESET TASK` |
| `DEVICE READY`, `BOUND`, `INITIALIZED` | `RESET DEVICE` |
| `INITIALIZING DEVICE` | `COMPLETE INIT` |
| `IDLE` | `END` |
### Keys of the interactive mode
In the modes `dynamic`, `interactive` and `external`, a key works without Enter, and the terminal does not show it.
| Key | Action |
| --- | --- |
| `h` | Print the help and the state machine with the keys. |
| `c` | Log the current state, at the severity `state`. |
| `p` | Log the number of connected peers of each sub-channel. |
| `i` | Request `INIT DEVICE`, wait for `INITIALIZING DEVICE`, then request `COMPLETE INIT`. |
| `b` | Request `BIND`. |
| `x` | Request `CONNECT`. |
| `j` | Request `INIT TASK`. |
| `r` | Request `RUN`. |
| `s` | Request `STOP`. |
| `t` | Request `RESET TASK`. |
| `d` | Request `RESET DEVICE`. |
| `k`, `l` | Move the console severity one step up (fewer lines) or down (more lines). |
| `n`, `m` | Move the log verbosity one step up or down. |
| `q` | Stop reading keys and run the shutdown sequence. |
| Another key | Print `Invalid input: […].` and the help. |
A key that the current state does not accept changes nothing. The state machine logs
`No transition from state … on transition …` at the severity `state`.
:::caution[One key at a time]
The plugin reads one key each time new input arrives. When several keys arrive together, for example `cq` from a pipe,
the plugin handles only the first one. It reads the next key only after more input arrives. See the disabled test
`ControlPlugin.DISABLED_SeveralKeysInOneInput` in `test/device/_runner.cxx`.
:::
### Signals
With `--catch-signals` greater than 0, the control plugin handles `SIGINT` and `SIGTERM`
([Control.cxx](/source/fairmq/plugins/control/Control.cxx/#L439-L469)):
1. The first signal starts a graceful shutdown. The plugin logs `Received device shutdown request (signal …)` and
`Waiting for graceful device shutdown. Hit Ctrl-C again to abort immediately.`
2. The plugin stops its controller.
3. If its shutdown sequence has not run yet, the plugin takes the controller role with `StealDeviceControl()`, also
from another plugin. Then it runs the shutdown sequence.
4. A `SIGINT` after an earlier signal ends the process at once with `std::abort()`. A second `SIGTERM` has no effect.
With `--catch-signals 0`, the plugin logs the warning `Signal handling (e.g. Ctrl-C) has been deactivated.` A signal
then has its default effect, and the device does not run the shutdown sequence.
### When the device goes to ERROR
An exception in a hook, or the transition `ERROR FOUND`, moves the device to `ERROR`. No transition leaves this state.
1. The state machine stops, and [`RunStateMachine()`](/api/fair/mq/Device/#RunStateMachine) throws: the exception
of the hook, or [`StateMachine::ErrorStateException`](/api/fair/mq/StateMachine/ErrorStateException/).
2. The control plugin stops its controller. It does not run the shutdown sequence.
3. The `main()` function of `runDevice.h` catches the exception, logs
`Uncaught exception reached the top of main: …` and returns 1.
[`DeviceRunner::RunWithExceptionHandlers()`](/api/fair/mq/DeviceRunner/#RunWithExceptionHandlers) also returns 1. It
logs `Uncaught exception reached the top of DeviceRunner: …`. The tests in `test/device/_exceptions.cxx` check the exit
code 1 for the modes `static` and `interactive`.
## Options
<OptionsTable groups={['Control', 'Plugins']} id="plugin" />
## Related pages
- [Write a plugin](/guides/write-plugin/): make your own plugin and load it with `-P`.
- [Control a device from code](/guides/control-from-code/): a controller plugin, runner hooks, or a device in a thread.
- [Device states](/concepts/states/): the states and transitions that a controller requests.
- [custom-controller](/examples/custom-controller/): an example of a controller plugin.
- [dds](/examples/dds/): a topology that needs a DDS plugin to give the addresses to the connecting channels.
- [Command-line options](/reference/options/): all options of a device.

View File

@@ -0,0 +1,272 @@
---
title: 'Device states'
description: 'The state machine of a device: idling and working states, the transitions, the hooks in each state, RUNNING, ERROR and the log lines.'
sidebar:
order: 2
code: [fairmq/States.h, fairmq/StateMachine.cxx, fairmq/Device.cxx, fairmq/plugins/control/Control.cxx]
---
import StateMachine from '../../../components/diagrams/StateMachine.astro';
import Snippet from '../../../components/Snippet.astro';
Each device has a state machine. A controller requests transitions, and the state machine calls the
hooks of your device at fixed points. The state tells you what the device does now and which
transitions it accepts.
<StateMachine />
## Idling states and working states
The state machine has two kinds of states:
- In an **idling state**, the device does no work. It waits until a controller requests the next
transition. The idling states are `IDLE`, `INITIALIZED`, `BOUND`, `DEVICE READY` and `READY`.
- In a **working state**, the device does its work and calls your hooks. At the end, the device
itself requests the next transition. The working states are `INITIALIZING DEVICE`, `BINDING`,
`CONNECTING`, `INITIALIZING TASK`, `RUNNING`, `RESETTING TASK` and `RESETTING DEVICE`.
Two working states are different. In `INITIALIZING DEVICE`, the device waits for the transition
`CompleteInit` from the controller. `RUNNING` ends with the transition `Stop`, from the controller
or from the device.
`EXITING` is the final state. The state machine stops there, and the process of the device can end.
`ERROR` is the state after an error, see [The ERROR state](#the-error-state). The enum
[`fair::mq::State`](/api/fair/mq/State/) also has the values `Undefined` and `Ok`. A device does not
enter them.
## Transitions
A controller requests a transition with [`ChangeState()`](/api/fair/mq/Device/#ChangeState). The
state machine accepts only these transitions:
| Transition | From | To | Requested by |
| --- | --- | --- | --- |
| `InitDevice` | `IDLE` | `INITIALIZING DEVICE` | Controller |
| `CompleteInit` | `INITIALIZING DEVICE` | `INITIALIZED` | Controller |
| `Bind` | `INITIALIZED` | `BINDING` | Controller |
| `Connect` | `BOUND` | `CONNECTING` | Controller |
| `InitTask` | `DEVICE READY` | `INITIALIZING TASK` | Controller |
| `Run` | `READY` | `RUNNING` | Controller |
| `Stop` | `RUNNING` | `READY` | Controller, or the device when its work ends |
| `ResetTask` | `READY` | `RESETTING TASK` | Controller |
| `ResetDevice` | `INITIALIZED`, `BOUND`, `DEVICE READY` | `RESETTING DEVICE` | Controller |
| `End` | `IDLE` | `EXITING` | Controller |
| `Auto` | `BINDING`, `CONNECTING`, `INITIALIZING TASK`, `RESETTING TASK`, `RESETTING DEVICE` | `BOUND`, `DEVICE READY`, `READY`, `DEVICE READY`, `IDLE` (in this order) | The device, at the end of the working state |
| `ErrorFound` | All states | `ERROR` | The device after an exception in a hook, or your code |
These rules apply to all transitions:
- The state machine accepts one transition at a time. While a transition is pending, `ChangeState()`
refuses all other transitions except `ErrorFound`.
- `ChangeState()` returns `false` for a transition that the current state does not accept. The state
does not change.
- The state machine is cooperative. The next state starts only after the hook of the current state
returns.
- A new transition interrupts the transports of the device. A `Send()` or `Receive()` that waits
then returns `TransferCode::interrupted`. The transports resume when the next state starts.
For the complete tables, see [States and transitions](/reference/states/).
## The hooks in each state
The idling states have no hooks. The working states call these hooks:
| State | Hooks | What the device does |
| --- | --- | --- |
| `INITIALIZING DEVICE` | [`Init()`](/api/fair/mq/Device/#Init) | It waits for `CompleteInit`. Then it reads the property `id` and calls `Init()`. Then it reads `rate`, `init-timeout` and `transport`, and makes the transports and the channels. |
| `BINDING` | [`Bind()`](/api/fair/mq/Device/#Bind) | It binds all channels with the method `bind`, and calls `Bind()`. If a channel cannot bind, the device throws an exception. |
| `CONNECTING` | [`Connect()`](/api/fair/mq/Device/#Connect) | It connects all channels with the method `connect`, and calls `Connect()`. See [Connect with a delay](#connect-with-a-delay). |
| `INITIALIZING TASK` | [`InitTask()`](/api/fair/mq/Device/#InitTask) | It calls `InitTask()`. |
| `RUNNING` | [`PreRun()`](/api/fair/mq/Device/#PreRun), data callbacks or [`ConditionalRun()`](/api/fair/mq/Device/#ConditionalRun) and [`Run()`](/api/fair/mq/Device/#Run), [`PostRun()`](/api/fair/mq/Device/#PostRun) | See [The RUNNING state](#the-running-state). |
| `RESETTING TASK` | [`ResetTask()`](/api/fair/mq/Device/#ResetTask) | It calls `ResetTask()`. |
| `RESETTING DEVICE` | [`Reset()`](/api/fair/mq/Device/#Reset) | It resets and removes its transports, calls `Reset()`, and removes all channels. |
After the hooks of a working state, the device requests `Auto`. It does not request `Auto` when
another transition is already pending. `INITIALIZING DEVICE` and `RUNNING` do not end with `Auto`.
### Connect with a delay
In `CONNECTING`, the device tries to connect each channel. If a channel cannot connect, the device
waits 50 ms. Then it reads the address of the channel from the properties again and tries again. A
controller can thus give the address of a peer later. After `init-timeout` seconds (default 120),
the device throws an exception and goes to `ERROR`.
## The RUNNING state
`RUNNING` is the state in which the device processes data. This function of the device runs in
`RUNNING`:
<Snippet file="fairmq/Device.cxx" start="void Device::RunWrapper()" />
The device does these steps:
1. It logs `fair::mq::Device running...`. If a channel has the property `rateLogging` larger than 0
(default 1), the device starts a thread that logs the transfer rates.
2. It calls `PreRun()`.
3. With data callbacks ([`OnData()`](/api/fair/mq/Device/#OnData)), it receives the messages and
calls the callbacks. Without data callbacks, it calls `ConditionalRun()` in a loop, and then
calls `Run()` once.
4. If no transition is pending, the device requests `Stop`.
5. It calls `PostRun()`. Then the next state starts, usually `READY`.
### ConditionalRun(), Run() or data callbacks
You choose one of three ways to do the work in `RUNNING`:
- [`ConditionalRun()`](/api/fair/mq/Device/#ConditionalRun): the device calls it again and again.
Return `true` to get the next call. The option `--rate` (default 0) limits the number of calls per
second. A value of 0 means no limit.
- [`Run()`](/api/fair/mq/Device/#Run): the device calls it once. For continuous work, write a loop
that ends when [`NewStatePending()`](/api/fair/mq/Device/#NewStatePending) returns `true`.
- Data callbacks: the device calls your callback for each message on a channel. The device does not
call `ConditionalRun()` and `Run()` then.
[Receive data with callbacks or loops](/guides/receive-data/) compares the three ways.
### What ends RUNNING
`RUNNING` ends in one of these cases:
- A controller requests `Stop`. For example, the key `s` of the interactive controller, or a
`SIGINT` (Ctrl-C) that starts the shutdown sequence. The device does not call `ConditionalRun()`
and the data callbacks again. Your `Run()` loop must check `NewStatePending()`.
- The work ends. A data callback returns `false`, `ConditionalRun()` returns `false`, or `Run()`
returns. Then the device requests `Stop` itself.
- A `Receive()` for a data callback fails, for example after a receive timeout of the channel. Then
the device also requests `Stop`.
- A hook throws an exception. The device goes to `ERROR`.
To stop a topology without losing messages, see
[Stop a topology without losing messages](/guides/end-of-run/).
:::caution
The state machine does not stop a hook. If your `Run()` does not return, the device cannot leave
`RUNNING`.
:::
In `PostRun()`, the transition is already pending. Thus `NewStatePending()` returns `true`,
`WaitFor()` returns at once, and a `Send()` or `Receive()` that waits returns
`TransferCode::interrupted`. Use `PostRun()` to stop the work that you started in `PreRun()`. The
sampler of the example [multiple-transports](/examples/multiple-transports/) starts a thread in
`PreRun()` and joins it in `PostRun()`:
<Snippet file="examples/multiple-transports/sampler1.cxx" start="void PreRun() override" />
<Snippet file="examples/multiple-transports/sampler1.cxx" start="void PostRun() override" />
To add your own thread without a data race, see [Threads in a device](/concepts/threads/#safe-patterns).
## The ERROR state
A device goes to `ERROR` in two cases:
- A hook throws an exception, in any state.
- Your code requests the transition `ErrorFound`, for example with
`ChangeStateOrThrow(fair::mq::Transition::ErrorFound)`. The state machine accepts `ErrorFound` in
all states, also when another transition is pending.
No transition leaves `ERROR`. The state machine stops, and
[`RunStateMachine()`](/api/fair/mq/Device/#RunStateMachine) throws. It throws the exception of the
hook, or [`StateMachine::ErrorStateException`](/api/fair/mq/StateMachine/ErrorStateException/) with
the text `Device transitioned to error state`. With `fairmq/runDevice.h`, the process then logs
`Uncaught exception reached the top of main:` and ends with the exit code 1. The tests
`Exceptions.Throw` and `ErrorState.ChangeState` in `test/device/` check the exit code 1 for each
hook.
In `ERROR`, the controller of the control plugin stops. It requests no more transitions and no
shutdown sequence. Thus the device does not call `ResetTask()` and `Reset()` after an error.
:::caution[Known defect]
In `ERROR`, `ChangeState()` can return `true`, but the state does not change. See the disabled test
`StateMachine.RefusesTransitionsInError` in `test/state_machine/`.
:::
For the handling of errors, see [Handle errors and timeouts](/guides/errors-timeouts/).
## Wait for a transition in your code
Two functions tell a hook that a transition is pending:
- [`NewStatePending()`](/api/fair/mq/Device/#NewStatePending) returns `true` when a transition is
requested and the next state has not started yet.
- [`WaitFor(duration)`](/api/fair/mq/Device/#WaitFor) waits for the duration, or until a transition
is requested. It returns `true` after the full duration, and `false` when a transition ended the
wait.
A `Run()` loop with a pause of 1 s between two steps can look like this:
```cpp
void Run() override
{
while (!NewStatePending()) {
// One step of the work.
if (!WaitFor(std::chrono::seconds(1))) {
break; // A transition is pending.
}
}
}
```
In the test `WaitFor.Interrupt`, a device calls `WaitFor()` with 60 s in `PreRun()` or `Run()`. A
`SIGINT` makes the control plugin request `Stop`, and the wait ends. In `PostRun()`, the wait ends
at once, because `Stop` is already pending:
<Snippet file="test/helper/devices/TestStateAction.h" start="bool const done = WaitFor" end="Sleeping Done" />
## Log lines
The state machine logs each state change with the severity `state`. A device under the control
`static` that ends its work by itself logs these lines. The lines show only the message text,
without the prefix of the logger. Other log lines between them are left out.
```txt
Starting FairMQ state machine --> IDLE
IDLE ---> INITIALIZING DEVICE
INITIALIZING DEVICE ---> INITIALIZED
INITIALIZED ---> BINDING
BINDING ---> BOUND
BOUND ---> CONNECTING
CONNECTING ---> DEVICE READY
DEVICE READY ---> INITIALIZING TASK
INITIALIZING TASK ---> READY
READY ---> RUNNING
fair::mq::Device running...
RUNNING ---> READY
READY ---> RESETTING TASK
RESETTING TASK ---> DEVICE READY
DEVICE READY ---> RESETTING DEVICE
RESETTING DEVICE ---> IDLE
IDLE ---> EXITING
```
When the device object is destroyed, the state machine logs `Exiting FairMQ state machine`. Two more
lines tell you that the state machine refused a transition:
| Log line | Cause |
| --- | --- |
| `No transition from state DEVICE_READY on transition RUN` | The current state does not accept the transition. This line uses the internal names with an underscore. |
| `Transition RUN incoming, but another state transition is already ongoing.` | Another transition is pending. |
## Control modes in short
The built-in control plugin requests the transitions. The option `--control` selects its mode:
| `--control` | What the controller does |
| --- | --- |
| `dynamic` (default), `interactive`, `external` | It requests all transitions up to `RUNNING`. Then it reads keys from the terminal, for example `s` for `Stop`. The key `q` starts the shutdown sequence. |
| `static` | It requests all transitions up to `RUNNING`. When the device leaves `RUNNING`, it requests the transitions down to `EXITING`. |
| `gui` | It requests all transitions up to `RUNNING`. Then it waits for a signal. |
| `none` | The control plugin does not control the device. Another plugin or your code must request the transitions. |
An unknown value logs an error, and the plugin uses `static`. With `--catch-signals 1` (default),
the first `SIGINT` or `SIGTERM` starts the shutdown sequence. A second `SIGINT` aborts the process.
For the details, see [Plugins and control](/concepts/plugins/).
## Related pages
- [States and transitions](/reference/states/): all states, transitions and keys as tables.
- [Devices](/concepts/devices/): the class `fair::mq::Device` and its hooks.
- [Receive data with callbacks or loops](/guides/receive-data/): the three ways to work in `RUNNING`.
- [Handle errors and timeouts](/guides/errors-timeouts/): exceptions, `ERROR` and interrupted
transfers.
- [Control a device from code](/guides/control-from-code/): request transitions from your program.

View File

@@ -0,0 +1,250 @@
---
title: Threads in a device
description: The threads of a device process, the thread that runs each hook and callback, and the objects that your own threads can share.
sidebar:
order: 7.5
code: [fairmq/Device.cxx, fairmq/StateMachine.cxx, fairmq/plugins/control/Control.cxx, fairmq/Channel.h, fairmq/ProgOptions.h]
---
import Snippet from '../../../components/Snippet.astro';
A device process has more than one thread. FairMQ, its plugins and ZeroMQ start threads, and your
code can add more, for example in `PreRun()`. This page tells you which thread runs each hook and
callback, which objects are thread-safe, and how to add a thread without a data race.
## The threads of a device process
A device that starts with `fairmq/runDevice.h` can have these threads:
| Thread | Started by | When it runs | What it does |
| --- | --- | --- | --- |
| Main thread | The process | Always | Runs `main()` and [`DeviceRunner::Run()`](/api/fair/mq/DeviceRunner/#Run). It creates the plugins and then calls [`RunStateMachine()`](/api/fair/mq/Device/#RunStateMachine). This thread is the thread of the state machine. |
| Controller thread | The control plugin | With each value of `--control` except `none` | Requests the transitions. In the mode `dynamic` (default), it also reads the keys of the terminal ([Control.cxx](/source/fairmq/plugins/control/Control.cxx/#L67-L92)). |
| Signal handler thread | The control plugin | With `--catch-signals 1` (default) | Checks every 100 ms for `SIGINT` or `SIGTERM`. After the first signal, it stops the controller thread and requests the transitions of the shutdown sequence ([Control.cxx](/source/fairmq/plugins/control/Control.cxx/#L439-L469)). |
| Rate logger thread | The device | In `RUNNING`, if a sub-channel has `rateLogging` above 0 (default 1) | Runs [`LogSocketRates()`](/api/fair/mq/Device/#LogSocketRates). It ends when a transition is pending. The device joins it after `PostRun()` ([Device.cxx](/source/fairmq/Device.cxx/#L384-L395)). |
| Poll threads | The device | In `RUNNING`, with data callbacks on input channels of more than one transport | One thread for each transport. Each thread polls its channels and calls their data callbacks ([Device.cxx](/source/fairmq/Device.cxx/#L509-L523)). |
| ZeroMQ I/O threads | ZeroMQ | While the transport exists | Each transport, also `shmem`, has one ZeroMQ context with [`--io-threads`](/reference/options/#opt-io-threads) I/O threads (default 1) ([zeromq/TransportFactory.h](/source/fairmq/zeromq/TransportFactory.h/#L39), [shmem/TransportFactory.h](/source/fairmq/shmem/TransportFactory.h/#L72-L74)). ZeroMQ moves the data of the sockets in these threads (ZeroMQ behavior). |
| Heartbeat thread | The shmem transport | While the transport exists | Writes the heartbeat for [`fairmq-shmmonitor`](/shmem/monitor/#what-the-daemon-does) every 100 ms ([shmem/Manager.h](/source/fairmq/shmem/Manager.h/#L637-L647)). |
| Ack threads of a region | The shmem transport | While the region exists | The ack sender sends the released blocks to the creator of the region. The ack receiver of the creator calls the region callback. See [Acknowledgements](/shmem/regions/#acknowledgements). |
| Region event thread | The transport | After [`SubscribeToRegionEvents()`](/api/fair/mq/TransportFactory/#SubscribeToRegionEvents) | Calls the region event callback. See [Region events](/shmem/regions/#region-events). |
The control plugin does not start a controller thread with `--control none`, or when another plugin
has the controller role. The signal handler thread still runs. The C signal handler itself only counts
the signals and stores the last one. A `SIGINT` after a first signal calls `std::abort()` there. See [Signals](/concepts/plugins/#signals).
Without `DeviceRunner`, the device has no plugins. Then the thread of the state machine is the thread
that calls `RunStateMachine()`, and your code requests the transitions from another thread. See
[Run the device in a thread](/guides/control-from-code/#run-the-device-in-a-thread). One process can
run several devices in this way. In the test `MultipleDevices.TwoInSameProcess`, two devices run in one
process, each with its own thread for `RunStateMachine()` and its own thread for the transitions.
For the limits, see [Several devices in one process](/guides/control-from-code/#several-devices-in-one-process).
## Which thread runs your code
| Your code | Thread | Notes |
| --- | --- | --- |
| The hooks `Init()`, `Bind()`, `Connect()`, `InitTask()`, `PreRun()`, `ConditionalRun()`, `Run()`, `PostRun()`, `ResetTask()`, `Reset()` | The thread of the state machine | One hook at a time. The next state starts only after the hook returns. See [The hooks](/concepts/devices/#the-hooks). |
| Data callbacks of [`OnData()`](/api/fair/mq/Device/#OnData) | The thread of the state machine. With input channels of more than one transport: the poll thread of the transport. | In the poll threads, a mutex lets one callback run at a time ([Device.cxx](/source/fairmq/Device.cxx/#L525-L562)). See [Several input channels](/guides/receive-data/#several-input-channels). |
| State change callbacks: [`SubscribeToStateChange()`](/api/fair/mq/Device/#SubscribeToStateChange), [`SubscribeToDeviceStateChange()`](/api/fair/mq/Plugin/#SubscribeToDeviceStateChange) of a plugin | The thread of the state machine | At the start of each state, before the hooks of the state ([StateMachine.cxx](/source/fairmq/StateMachine.cxx/#L191-L219)). |
| New transition callbacks: [`SubscribeToNewTransition()`](/api/fair/mq/Device/#SubscribeToNewTransition) | The thread that calls `ChangeState()` | The state machine holds its lock while it calls the callback ([StateMachine.cxx](/source/fairmq/StateMachine.cxx/#L257-L260)). |
| Property callbacks: [`Subscribe<T>()`](/api/fair/mq/ProgOptions/#Subscribe), [`SubscribeAsString()`](/api/fair/mq/ProgOptions/#SubscribeAsString), [`SubscribeToPropertyChange<T>()`](/api/fair/mq/Plugin/#SubscribeToPropertyChange) | The thread that changes the property, for example with `SetProperty()` | Before the call returns, after the property store releases its lock ([ProgOptions.h](/source/fairmq/ProgOptions.h/#L268-L279)). |
| Region callbacks: [`RegionCallback`](/api/fair/mq/#RegionCallback), [`RegionBulkCallback`](/api/fair/mq/#RegionBulkCallback) | shmem: the ack receiver thread of the region. zeromq: the thread that makes the region message. | The zeromq transport copies the data and calls the callback at once, in `NewMessage()` ([zeromq/Message.h](/source/fairmq/zeromq/Message.h/#L131-L137)). |
| Region event callbacks | The region event thread of the transport | The shmem transport checks for events every 50 ms. |
| Message free functions ([`FreeFn`](/api/fair/mq/#FreeFn)) | shmem: the thread that makes the message. zeromq: a thread that ZeroMQ selects. | The shmem transport copies the buffer and calls the function at once. ZeroMQ calls it when it releases the buffer, also from its own threads (ZeroMQ behavior). See [Your own buffer](/concepts/messages/#your-own-buffer). |
| Your override of `LogSocketRates()` | The rate logger thread | Only in `RUNNING`. |
| Constructors of plugins, hooks of `DeviceRunner` | The main thread | Before the state machine starts. |
Some rules follow from this table:
- A state change callback blocks the device. The device calls the hooks of the state only after all
state callbacks return. For long work, start a thread. See
[A controller with its own thread](/guides/control-from-code/#a-controller-with-its-own-thread).
- Do not call `ChangeState()`, `ChangeStateOrThrow()` or `WaitFor()` in a new transition callback.
These functions lock the mutex that the state machine holds during the callback.
- The device itself subscribes to new transitions. Its callback interrupts the transports, in the
thread that requests the transition. The next state resumes the transports in the thread of the
state machine ([Device.cxx](/source/fairmq/Device.cxx/#L96-L104)).
- A zeromq channel that sends a shmem message wraps the message. The free function of the wrapper
destroys the shmem message ([Channel.h](/source/fairmq/Channel.h/#L421-L438)). Thus the shmem
message can be destroyed in a thread of ZeroMQ.
- Both transports call the region event callback while they hold the lock of the subscription
([shmem/Manager.h](/source/fairmq/shmem/Manager.h/#L582-L616),
[zeromq/Context.h](/source/fairmq/zeromq/Context.h/#L95-L106)). Do not call
`SubscribeToRegionEvents()` or `UnsubscribeFromRegionEvents()` in the callback. With zeromq, also do
not create or destroy a region and do not call `GetRegionInfo()` there. These functions lock the
same mutex.
## What is thread-safe
| Object or function | From several threads at the same time | Source |
| --- | --- | --- |
| [`Channel`](/api/fair/mq/Channel/) and its socket | No. The header says: "The class is not thread-safe." Use each channel from one thread at a time. | [Channel.h](/source/fairmq/Channel.h/#L30-L35) |
| Different channels, also of one transport | Yes. Each thread uses its own channels. | Test `PushPullMultipart.MultiThreaded_ipc` |
| [`GetNumberOfConnectedPeers()`](/api/fair/mq/Channel/#GetNumberOfConnectedPeers) of a channel | Safe for distinct channels, not safe for one shared channel. | [Channel.h](/source/fairmq/Channel.h/#L198-L204) |
| [`Message`](/api/fair/mq/Message/), [`Parts`](/api/fair/mq/Parts/), a [`Poller`](/api/fair/mq/Poller/) | No. These classes have no lock. Give each object to one thread at a time. | [Message.h](/source/fairmq/Message.h/), [Parts.h](/source/fairmq/Parts.h/), [Poller.h](/source/fairmq/Poller.h/) |
| [`ChannelResource`](/api/fair/mq/ChannelResource/) | No. Its map of the allocated messages has no lock. See [Use std::pmr memory resources](/guides/pmr/). | [MemoryResources.h](/source/fairmq/MemoryResources.h/#L54-L98) |
| The property functions of [`ProgOptions`](/api/fair/mq/ProgOptions/), for example `GetProperty<T>()` and `SetProperty<T>()` | Yes. Each function locks a mutex. [`GetVarMap()`](/api/fair/mq/ProgOptions/#GetVarMap) returns a reference, and the lock does not protect it. | [ProgOptions.h](/source/fairmq/ProgOptions.h/#L61-L87) |
| [`ChangeState()`](/api/fair/mq/Device/#ChangeState), [`NewStatePending()`](/api/fair/mq/Device/#NewStatePending), [`WaitFor()`](/api/fair/mq/Device/#WaitFor), [`GetCurrentState()`](/api/fair/mq/Device/#GetCurrentState) | Yes. The state machine uses a mutex and atomic values. | [StateMachine.cxx](/source/fairmq/StateMachine.cxx/#L175-L182), [StateMachine.cxx](/source/fairmq/StateMachine.cxx/#L257-L260) |
| Subscribe and unsubscribe for state changes | Yes. A mutex protects the subscriptions. | [StateMachine.cxx](/source/fairmq/StateMachine.cxx/#L312-L329), test `PluginServices.SubscriptionThreadSafety` |
| [`WaitForState()`](/api/fair/mq/Device/#WaitForState), [`WaitForNextState()`](/api/fair/mq/Device/#WaitForNextState) | Call them from one thread only. The queue of states gives each state to one caller. | [StateQueue.h](/source/fairmq/StateQueue.h/#L31-L35) |
| [`Interrupt()`](/api/fair/mq/TransportFactory/#Interrupt), [`Resume()`](/api/fair/mq/TransportFactory/#Resume) of a transport | Yes. They set an atomic flag. | [zeromq/Context.h](/source/fairmq/zeromq/Context.h/#L149-L150), [shmem/Manager.h](/source/fairmq/shmem/Manager.h/#L283-L284), test `InterruptTransfer.Receive` |
| The byte and message counters of a channel, for example [`GetBytesTx()`](/api/fair/mq/Channel/#GetBytesTx) | Yes. The sockets keep them in atomic values. The rate logger thread reads them. | [zeromq/Socket.h](/source/fairmq/zeromq/Socket.h/#L399-L402), [shmem/Socket.h](/source/fairmq/shmem/Socket.h/#L459-L462) |
The device makes its channels in `INITIALIZING DEVICE`, after `Init()`
([Device.cxx](/source/fairmq/Device.cxx/#L153-L171)). It removes them in `RESETTING DEVICE`
([Device.cxx](/source/fairmq/Device.cxx/#L744)). Between these states, the map of the channels does
not change. Thus several threads can call [`GetChannel()`](/api/fair/mq/Device/#GetChannel),
[`Send()`](/api/fair/mq/Device/#Send) and [`Receive()`](/api/fair/mq/Device/#Receive) of the device,
each for its own channels. Register the data callbacks before `RUNNING`, and add the channels in
`Init()` at the latest. Do both in one thread.
The test `PushPullMultipart.MultiThreaded_ipc` binds and connects two channels of one transport in
the main thread. Then it sends on one channel and receives on the other, each in its own thread:
<Snippet file="test/protocols/_push_pull_multipart.cxx" start="auto RunMultiThreadedMultipart(" />
:::tip
To find data races, build FairMQ with the CMake option `ENABLE_SANITIZER_THREAD`. The option applies to
FairMQ, its tests and its examples, in the build types `Debug` and `RelWithDebInfo` (default). See
[CMake options and variables](/reference/cmake/).
:::
## Safe patterns
### One thread for each channel
Start your thread in `PreRun()`, and join it in `PostRun()`. Give the thread its own channels, and do
not use these channels in the other threads. The sampler of the example
[multiple-transports](/examples/multiple-transports/) sends on `data1` in `ConditionalRun()`. A second
thread receives the acknowledgements on `ack`:
<Snippet file="examples/multiple-transports/sampler1.cxx" start="void PreRun() override" />
<Snippet file="examples/multiple-transports/sampler1.cxx" start="void PostRun() override" />
<Snippet file="examples/multiple-transports/sampler1.cxx" start="void ListenForAcks()" />
This pattern works for these reasons:
- `PostRun()` runs while the transition is pending. The device interrupted the transports, so the
waiting `Receive()` returns `TransferCode::interrupted`, and the loop ends.
- The next state resumes the transports only after `PostRun()` returns. Thus the thread cannot wait
again before the join.
- The channels exist until `RESETTING DEVICE`. The thread ends before this state.
### Stop your thread with the state machine
- Check [`NewStatePending()`](/api/fair/mq/Device/#NewStatePending) in the loop of your thread.
- For a pause, call [`WaitFor()`](/api/fair/mq/Device/#WaitFor) and not `std::this_thread::sleep_for()`.
`WaitFor()` returns `false` at once when a transition is requested. See
[Wait for a transition in your code](/concepts/states/#wait-for-a-transition-in-your-code).
- Check the return value of each `Send()` and `Receive()`. A negative value ends the loop.
- Catch the exceptions in the function of your thread. An exception that leaves the function of a
`std::thread` calls `std::terminate()`, and the device does not go to `ERROR`. To report the error,
request the transition `ErrorFound`, for example with
[`ChangeStateOrThrow()`](/api/fair/mq/Device/#ChangeStateOrThrow). The state machine accepts it in
all states.
### Hand messages over by move
A [`MessagePtr`](/api/fair/mq/#MessagePtr) is a `std::unique_ptr<Message>`. To give a message to
another thread, move it into a queue that a mutex protects. Then only one thread owns the message at a
time. In this device, the data callback puts each message into a queue. A second thread takes the
messages out and sends them on its own channel `out`:
```cpp
#include <fairmq/Device.h>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <mutex>
#include <thread>
struct Forwarder : fair::mq::Device
{
Forwarder() { OnData("in", &Forwarder::HandleData); }
bool HandleData(fair::mq::MessagePtr& msg, int /*index*/)
{
{
std::lock_guard<std::mutex> lock(fMtx);
fQueue.push_back(std::move(msg));
}
fCV.notify_one();
return true;
}
void PreRun() override { fSender = std::thread(&Forwarder::SendLoop, this); }
void PostRun() override
{
fSender.join();
fQueue.clear(); // destroy the messages that were not sent
}
void SendLoop()
{
while (!NewStatePending()) {
fair::mq::MessagePtr msg;
{
std::unique_lock<std::mutex> lock(fMtx);
if (!fCV.wait_for(lock, std::chrono::milliseconds(100), [this] { return !fQueue.empty(); })) {
continue;
}
msg = std::move(fQueue.front());
fQueue.pop_front();
}
if (Send(msg, "out") < 0) {
break;
}
}
}
std::mutex fMtx;
std::condition_variable fCV;
std::deque<fair::mq::MessagePtr> fQueue;
std::thread fSender;
};
```
- The callback uses the channel `in`, in the thread of the state machine. The second thread uses the
channel `out`. No channel is in two threads.
- After the move, the callback does not use `msg` again.
- `PostRun()` destroys the messages that remain in the queue. Destroy all messages before
`RESETTING DEVICE`, because the device then destroys its transports.
### Protect the data of callbacks
A region callback, a property callback and the data callbacks of several transports can run in other
threads than your hooks. Protect the data that they share with a mutex or a `std::atomic`. The readout
device of the example [readout](/examples/readout/) counts the acknowledgements in a
`std::atomic<uint64_t>`:
<Snippet file="examples/readout/readout.cxx" start="void InitTask() override" />
The member is `std::atomic<uint64_t> fNumUnackedMsgs`. `ConditionalRun()` increments it after each
successful `Send()`, and the callback decrements it in the ack receiver thread.
The dispatcher of the example [qc](/examples/qc/) uses a `std::atomic<bool>` for a flag that a
property callback sets. See [Follow the changes](/guides/control-from-code/#follow-the-changes).
## Problems that can occur
- **The device does not leave `RUNNING`:** your thread waits and `PostRun()` waits in `join()`. Make
the thread check `NewStatePending()`, and use `WaitFor()` for pauses.
- **The process ends with `std::terminate()`:** an exception left the function of a thread, or a data
callback threw in a poll thread. Catch the exceptions in the thread. See
[Receive from channels of different transports](/guides/several-transports/#receive-from-channels-of-different-transports).
- **A crash or wrong data in a transfer:** two threads use one channel. Give each channel to one
thread.
- **`WaitForState()` does not return:** another thread took the state from the queue with
`WaitForState()` or `WaitForNextState()`. Wait for the states in one thread only.
## Related pages
- [Device states](/concepts/states/): the state machine and the hooks in each state.
- [Receive data with callbacks or loops](/guides/receive-data/): data callbacks and the poll threads.
- [Use several transports](/guides/several-transports/): channels of two transports in one device.
- [Control a device from code](/guides/control-from-code/): controller threads and callbacks.
- [Unmanaged regions](/shmem/regions/): the ack threads and the region callbacks.

View File

@@ -0,0 +1,238 @@
---
title: 'Transports'
description: 'The zeromq and shmem transports, how a device selects the transport of each channel, and how the two transports differ.'
sidebar:
order: 5
code: [fairmq/TransportFactory.h, fairmq/TransportFactory.cxx, fairmq/Transports.h, fairmq/Device.cxx, fairmq/zeromq/TransportFactory.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
A transport moves the messages of a channel and allocates their buffers. FairMQ has two transports:
`zeromq` sends the data through sockets, and `shmem` keeps the data in shared memory and sends only
metadata. You select the transport for each channel in the configuration, so the code of your device
does not change.
## The transports and their names
Each transport is a subclass of [`fair::mq::TransportFactory`](/api/fair/mq/TransportFactory/). A
transport factory makes the messages, the sockets of the channels, the pollers and the unmanaged
regions of one transport. [`Transports.h`](/source/fairmq/Transports.h/) maps the names to the values
of the enum [`fair::mq::Transport`](/api/fair/mq/Transport/):
| Name | Enum value | Implementation | Use |
| --- | --- | --- | --- |
| `zeromq` | [`Transport::ZMQ`](/api/fair/mq/Transport/#ZMQ) | `fair::mq::zmq::TransportFactory` in `fairmq/zeromq/` | Data through zeromq sockets, in one process, on one host, or between hosts. |
| `shmem` | [`Transport::SHM`](/api/fair/mq/Transport/#SHM) | [`fair::mq::shmem::TransportFactory`](/api/fair/mq/shmem/TransportFactory/) in `fairmq/shmem/` | Data in shared memory, between processes on one host. |
| `default` | [`Transport::DEFAULT`](/api/fair/mq/Transport/#DEFAULT) | none | Channel property only: the channel uses the default transport of the device. |
[`TransportName()`](/api/fair/mq/#TransportName) converts an enum value to its name.
[`TransportType()`](/api/fair/mq/#TransportType) converts a name to the enum value and throws
`fair::mq::TransportError` for an unknown name.
[`GetEnabledTransports()`](/api/fair/mq/#GetEnabledTransports) returns `Transport::ZMQ` and
`Transport::SHM`.
### Make a transport factory
[`TransportFactory::CreateTransportFactory(type, id, config)`](/api/fair/mq/TransportFactory/#CreateTransportFactory)
returns a `std::shared_ptr<TransportFactory>`. It accepts the names `zeromq` and `shmem`
([TransportFactory.cxx](/source/fairmq/TransportFactory.cxx/#L34-L47)). For all other names, it
logs an error and throws `fair::mq::TransportFactoryError`.
- `id` is the id of the factory in the topology. A device gives its device id. If `id` is empty, the
function makes a UUID.
- `config` is a [`fair::mq::ProgOptions`](/api/fair/mq/ProgOptions/) pointer. The factory reads its
properties from it, for example `io-threads`. Without `config`, the factory uses the defaults.
A device makes its factories itself. You call `CreateTransportFactory()` yourself when you
[use channels without a device](/guides/channels-without-device/).
## How a device selects the transport
The device selects the transports in the state `INITIALIZING DEVICE`
([Device.cxx](/source/fairmq/Device.cxx/#L158-L183)):
<Steps>
1. The device reads the property `transport`, which is the option `--transport`. The default is
`zeromq`. This is the default transport of the device.
2. The device makes the factory of the default transport.
[`Transport()`](/api/fair/mq/Device/#Transport) returns it, and `NewMessage()` uses it.
3. For each sub-channel, the device reads the channel property `transport`. The default is
`default`, which selects the default transport of the device.
4. The device gets the factory for the transport of the sub-channel with
[`AddTransport()`](/api/fair/mq/Device/#AddTransport). This function makes a factory only if the
device has no factory of this transport yet.
</Steps>
The result: a device has one factory for each transport that it uses. All channels with the same
transport share this factory, and with it one zeromq context or one shared memory session. Each
factory gets the device id and the configuration of the device.
An unknown name in `--transport` or in a channel property stops the initialization, and the device
goes to the state `ERROR`.
The sink of the [multiple-transports example](/examples/multiple-transports/) uses `shmem` as the
default transport and `zeromq` for the channel `ack`:
<Snippet file="examples/multiple-transports/fairmq-start-ex-multiple-transports.sh.in" start='SINK="fairmq' end="name=ack,type=pub" />
With `--severity debug`, the sink logs its choices between other debug lines. The block shows these
lines without the prefix of time and severity. The order of the channels can change:
```txt
Setting 'shmem' as default transport for the device
Adding 'shmem' transport
Initializing transport for channel ack[0]: zeromq
Adding 'zeromq' transport
Initializing transport for channel data1[0]: default
Reusing existing 'shmem' transport
Initializing transport for channel data2[0]: shmem
Reusing existing 'shmem' transport
```
### The transports during the life of a device
On each new transition request, the device calls `Interrupt()` on all its factories. A blocking
`Send()` or `Receive()` then returns `TransferCode::interrupted` within about 100 ms. When the next
state starts, the device calls `Resume()`. In the state `RESETTING DEVICE`, the device calls
`Reset()` on all factories and destroys them with the channels.
## Compare the transports
| | `zeromq` | `shmem` |
| --- | --- | --- |
| Data path | The data goes through the zeromq socket. | The data stays in a shared memory segment. A small metadata message goes through a zeromq socket. |
| Copies of the data | For `ipc://` and `tcp://`, the receiver gets its own copy. | None. The receiver reads the buffer that the sender allocated. |
| Peers | One process (`inproc://`), one host (`ipc://`, `tcp://`), or other hosts (`tcp://`). | Processes on one host with the same session. |
| Socket types | `push`, `pull`, `pub`, `sub`, `xpub`, `xsub`, `req`, `rep`, `dealer`, `router`, `pair` | The same, without `pub` and `sub`. |
| Required configuration | None. | The same `--session` on all peers, and a segment that is large enough (`--shm-segment-size`, default 2 GiB). |
| Message from your buffer | No copy. The transport calls your deleter after the transfer. | The transport copies the buffer into the segment and calls your deleter at once. |
| Message from an unmanaged region | The transport copies the block and calls the region callback at once. | No copy. The callback runs when the receiver releases the block. |
| [`Copy()`](/api/fair/mq/Message/#Copy) of a message | The messages share the buffer in one process. | The messages share the buffer through a reference count, also between processes. |
| Clean-up | Nothing to clean up. | The last shmem factory of the session removes the shared memory, unless `--shm-no-cleanup` is `true`. After a crash, use the monitor. |
| Tools | none | [`fairmq-shmmonitor`](/tools/shmmonitor/) |
An `inproc://` address connects only the channels of one factory: each factory has its own zeromq
context, and ZeroMQ connects `inproc://` endpoints only inside one context. Thus both channels must
be in the same process and use the same factory.
## The zeromq transport
The zeromq transport ([`fairmq/zeromq/`](/source/fairmq/zeromq/TransportFactory.h/)) uses the
libzmq library:
- Each factory has one zeromq context with `--io-threads` I/O threads (default 1). The context
accepts up to 10000 sockets ([zeromq/Context.h](/source/fairmq/zeromq/Context.h/#L37-L56)).
- Each sub-channel has one zeromq socket of its type. The socket identity is
`<factory id>.<channel name>.<type>`.
- A `sub` socket subscribes to all messages.
- A socket waits for 100 ms at most in each call to libzmq. Between the calls, it checks for an
interruption and for the timeout of the transfer.
## The shmem transport
The shmem transport ([`fairmq/shmem/`](/source/fairmq/shmem/TransportFactory.h/)) puts the data of
each message into a managed segment of the session. The segment has a default size of 2 GiB. A send
transfers only the metadata of the message through a zeromq socket: 40 bytes for a single message on
a 64-bit platform, or the value of `--shm-metadata-msg-size` if it is larger. The receiver finds the
same buffer in the segment. The factory has its own zeromq context with `--io-threads` I/O threads.
The devices that exchange shmem messages must run on one host and use the same `--session` (default
`default`). A `pub` or `sub` socket throws `fair::mq::SocketError`. For the details, see
[How shared memory works](/shmem/how-it-works/) and [Sessions and segments](/shmem/sessions/). All devices of a
session must use compatible FairMQ versions: see [Mixed versions](/project/release-notes/#mixed-versions).
## Tune the zeromq transport
The zeromq transport has few settings of its own. Most of the tuning is in the channel properties
and in the selection of the transport. Measure each change with
[Run a benchmark](/guides/benchmark/): give the same options to `fairmq-bsampler` and `fairmq-sink`,
and compare the [rate lines](/guides/benchmark/#read-the-rate-lines).
### I/O threads
`--io-threads` sets the number of I/O threads of the zeromq context (`ZMQ_IO_THREADS`, default 1).
In code, [`SetNumIoThreads()`](/api/fair/mq/Device/#SetNumIoThreads) sets the same property. The
factory reads the value one time, when it makes its context in `INITIALIZING DEVICE`
([zeromq/TransportFactory.h](/source/fairmq/zeromq/TransportFactory.h/#L30-L44)). All sockets of
the factory share these threads.
- ZeroMQ needs at least one I/O thread for `tcp://` and `ipc://`. A program that uses only
`inproc://` can set 0 (ZeroMQ behavior).
- If ZeroMQ refuses the value, the zeromq transport throws `ContextError` with
`failed configuring context, reason: <text>`
([zeromq/Context.h](/source/fairmq/zeromq/Context.h/#L37-L56)). The shmem transport only logs the
error.
- The shmem transport uses `--io-threads` for its own context, which sends the metadata.
If one I/O thread does not move the data of all channels fast enough, try 2 or more threads, and
compare the rates.
### Number of sockets
FairMQ sets `ZMQ_MAX_SOCKETS` of each context to 10000
([zeromq/Context.h](/source/fairmq/zeromq/Context.h/#L45-L48)). The ZeroMQ default is 1023. No
option changes this value. Each FairMQ socket also makes a monitor for
[`GetNumberOfConnectedPeers()`](/api/fair/mq/Device/#GetNumberOfConnectedPeers)
([zeromq/Common.h](/source/fairmq/zeromq/Common.h/#L127-L171)). `zmq_socket_monitor()` makes one
`pair` socket in the context (ZeroMQ behavior), and FairMQ makes a second one that reads the events.
Thus one FairMQ socket uses three ZeroMQ sockets of the context.
### Queues and kernel buffers
The channel properties set the buffers of each socket. See
[Channel properties](/reference/channel-properties/#sndbufsize-and-rcvbufsize).
- `sndBufSize` and `rcvBufSize` (default 1000) limit the number of messages in the queues. ZeroMQ
applies the limit to each peer of the socket (ZeroMQ behavior). With the zeromq transport, a
queue holds the messages with their data: 1000 messages of 1 MB in one queue use 1 GB of memory.
Smaller values limit this memory. A `push` socket then waits earlier for a slow receiver. See
[Behavior of each socket type](/concepts/channels/#behavior-of-each-socket-type).
- `sndKernelSize` and `rcvKernelSize` (default 0, the system default) set the kernel buffers of
the `tcp://` connections in bytes. ZeroMQ does not apply them to `ipc://` connections (ZeroMQ
behavior). See
[`sndKernelSize` and `rcvKernelSize`](/reference/channel-properties/#sndkernelsize-and-rcvkernelsize).
Linux limits the values to `net.core.wmem_max` and `net.core.rmem_max` (Linux behavior).
To send a large buffer without a copy into the message, make the message from your buffer with a
deleter. See [Your own buffer](/concepts/messages/#your-own-buffer).
### When to use shmem
Use the shmem transport for large messages between processes on one host. With `ipc://` or
`tcp://`, the zeromq transport moves each byte through the kernel, and the receiver gets its own
copy. The shmem transport sends only the metadata, and the receiver reads the buffer of the sender.
- The saved copy grows with the size of the message. The cost of each transfer stays: the shmem
transport also sends one ZeroMQ message for each transfer, and it allocates the buffer in the
segment. Measure both transports with the message sizes of your application.
- The shmem transport needs the same session on all peers and a segment that holds all messages
in flight. See [Tune and debug](/shmem/tuning/).
- Between hosts, and for `pub` and `sub`, use the zeromq transport.
A device can use both transports: shmem for the channels on the host, zeromq for the others. See
[Use several transports](/guides/several-transports/).
## The removed ofi transport
FairMQ v1.5.0 removed the experimental `ofi` transport. No transport replaces it. The name `ofi` is
an unknown transport now: `CreateTransportFactory("ofi")` throws `TransportFactoryError`, and a
device with `--transport ofi` goes to the state `ERROR`. `Channel::Validate()` still accepts the
`verbs://` addresses of the `ofi` transport, but the zeromq and shmem transports cannot bind or
connect to them. Use `zeromq` with `tcp://` for transfers between hosts.
## Related pages
- [Messages and multipart](/concepts/messages/): what a transport does with your buffers.
- [Use several transports](/guides/several-transports/): one device with zeromq and shmem channels.
- [How shared memory works](/shmem/how-it-works/): the shmem transport in detail.
- [Use channels without a device](/guides/channels-without-device/): make a transport factory in your own program.
- [Command-line options](/reference/options/): `--transport`, `--io-threads` and the `--shm-*` options.
- [Run a benchmark](/guides/benchmark/): measure the two transports and the effect of the settings.
- [Use std::pmr memory resources](/guides/pmr/): fill a container in the message memory of a transport.

View File

@@ -0,0 +1,240 @@
---
title: '1-1: sampler and sink'
description: 'Two devices: a sampler sends a text message on a push channel, and a sink receives it on a pull channel.'
sidebar:
order: 1
code: [fairmq/Device.h, fairmq/runDevice.h, fairmq/Message.h, fairmq/ProgOptions.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps, FileTree } from '@astrojs/starlight/components';
The 1-1 example has two [devices](/concepts/devices/): a sampler that sends a text message and a sink that
receives it. It shows the minimum code of a device: a class that derives from
[`fair::mq::Device`](/api/fair/mq/Device/), its hooks, one [channel](/concepts/channels/), and the
`main()` function of `fairmq/runDevice.h`.
The files of the example are in
[`examples/1-1`](https://github.com/FairRootGroup/FairMQ/tree/dev/examples/1-1) on GitHub.
## Topology
The devices connect through one channel with the name `data`. The sampler binds a `push` socket, and the
sink connects a `pull` socket to it.
| Device | Channel | Type | Method | Address |
| --- | --- | --- | --- | --- |
| `sampler1` | `data` | `push` | `bind` | `tcp://*:5555` |
| `sink1` | `data` | `pull` | `connect` | `tcp://localhost:5555` |
The start script sets `rateLogging=0` on both channels, so the devices do not log the transfer rates. It
also starts the sampler with `--rate 1`, so the sampler sends one message per second.
## Build the example
The examples build together with FairMQ when the CMake option `BUILD_EXAMPLES` is `ON`. `ON` is the
default (see [Install](/start/install/)). The build puts these files into the build directory of the
example:
<FileTree>
- build/examples/1-1/
- fairmq-ex-1-1-sampler the sampler, from sampler.cxx
- fairmq-ex-1-1-sink the sink, from sink.cxx
- fairmq-start-ex-1-1.sh the start script
- test-ex-1-1.sh the test script
</FileTree>
The install step copies the two executables and the start script to `<prefix>/bin/`. The installed start
script calls the installed executables.
## Run the example
<Steps>
1. Go to the directory of the example in the build tree:
```sh
cd build/examples/1-1
```
2. Run the start script:
```sh
./fairmq-start-ex-1-1.sh
```
</Steps>
The script opens one `xterm` window for each device. The windows stay open after a device stops
(`xterm -hold`). The script also sets the environment variable `FAIRMQ_PATH` to `<build>/fairmq`. A device
with `--transport shmem` and `--shm-monitor true` uses this path to find `fairmq-shmmonitor`.
If you do not use `xterm`, open two terminals in `build/examples/1-1`. Run one command of the script in
each terminal:
```sh
./fairmq-ex-1-1-sampler --id sampler1 --rate 1 \
--channel-config "name=data,type=push,method=bind,address=tcp://*:5555,rateLogging=0"
```
```sh
./fairmq-ex-1-1-sink --id sink1 \
--channel-config "name=data,type=pull,method=connect,address=tcp://localhost:5555,rateLogging=0"
```
- `--id` sets the ID of the device.
- `--channel-config` configures one channel with a list of `key=value` pairs. The
[channel properties](/reference/channel-properties/) page lists all keys.
- `--rate` sets the maximum number of `ConditionalRun()` calls per second. The default `0` sets no limit.
You can start the two devices in any order. Each device goes through its [states](/concepts/states/) to
`RUNNING` without input. Then the default controller (`--control dynamic`) reads keys in the terminal.
Push `q` to stop the device and end the process. Push `h` to see all keys. Ctrl-C also stops the device.
## The sampler
The sampler is a `struct` that derives from `fair::mq::Device`. It overrides two hooks and has three
members: `fText`, `fMaxIterations` and `fNumIterations`
([sampler.cxx](https://github.com/FairRootGroup/FairMQ/blob/dev/examples/1-1/sampler.cxx#L16-L57)).
<Snippet file="examples/1-1/sampler.cxx" start="void InitTask()" />
The device calls [`InitTask()`](/api/fair/mq/Device/#InitTask) in the state `INITIALIZING TASK`. The
sampler reads its two custom options there. [`fConfig`](/api/fair/mq/Device/#fConfig) points to the
configuration of the device. [`GetProperty<T>()`](/api/fair/mq/ProgOptions/#GetProperty) returns the value
of an option as the type `T`.
<Snippet file="examples/1-1/sampler.cxx" start="bool ConditionalRun()" />
In the state `RUNNING`, the device calls [`ConditionalRun()`](/api/fair/mq/Device/#ConditionalRun) again
while the function returns `true` ([Device.cxx](/source/fairmq/Device.cxx/#L412-L427)):
- [`NewMessage()`](/api/fair/mq/Device/#NewMessage) with a buffer, a size, a free function and a hint
creates a message for an existing buffer. Here the buffer is a new `std::string`, and the free function
deletes it.
- The `zeromq` transport sends the buffer without a copy and calls the free function after the transfer.
The `shmem` transport copies the buffer into shared memory and calls the free function at once.
- [`Send()`](/api/fair/mq/Device/#Send) sends the message on the sub-channel 0 of the channel `data`. It
returns the number of bytes, or a negative [transfer code](/reference/transfer-codes/).
- `LOG(info)` writes a log line with the severity `info` (see [Logging](/tools/logging/)).
- The return value `false` ends the state `RUNNING`, and the device goes to `READY`. The sampler returns
`false` if `Send()` fails or if it reaches `--max-iterations`.
<Snippet file="examples/1-1/sampler.cxx" start="void addCustomOptions" />
<Snippet file="examples/1-1/sampler.cxx" start="getDevice(" />
The header `fairmq/runDevice.h` contains the `main()` function of the executable. `main()` calls two
functions that your source file must define ([runDevice.h](/source/fairmq/runDevice.h/#L13-L17)):
- `addCustomOptions()` adds the options of the device to the command line. The sampler adds `--text`
(default `Hello`) and `--max-iterations` (default `0`, no limit). `bpo` is an alias of the namespace
`boost::program_options`.
- `getDevice()` creates the device.
## The sink
<Snippet file="examples/1-1/sink.cxx" start="Sink()" />
The sink has no `ConditionalRun()`. Its constructor registers the member function `HandleData()` for the
channel `data` with [`OnData()`](/api/fair/mq/Device/#OnData). In the state `RUNNING`, the device receives
the messages of the channel and calls the handler for each message. A device with data handlers does not
call `ConditionalRun()` or `Run()`, and `--rate` has no effect on it
([Device.cxx](/source/fairmq/Device.cxx/#L404-L411)).
<Snippet file="examples/1-1/sink.cxx" start="bool HandleData" />
The handler gets the message and the index of the sub-channel.
[`GetData()`](/api/fair/mq/Message/#GetData) returns a pointer to the data, and
[`GetSize()`](/api/fair/mq/Message/#GetSize) returns the size in bytes. The handler returns `true` to get
the next message, or `false` to end the state `RUNNING`. The sink also has the option `--max-iterations`.
## Output
The listings show the severity and the message of each line. The real lines also have a time at the
start; the option `--verbosity` sets this prefix. Before these lines, each device logs the FairMQ logo and
its states from `IDLE` to `READY`. The interactive controller also prints its list of keys.
The sampler sends one message per second:
```txt
[STATE] READY ---> RUNNING
[INFO] fair::mq::Device running...
[INFO] Sending "Hello"
[INFO] Sending "Hello"
[INFO] Sending "Hello"
```
The sink logs each message that it receives:
```txt
[STATE] READY ---> RUNNING
[INFO] fair::mq::Device running...
[INFO] Received: "Hello"
[INFO] Received: "Hello"
[INFO] Received: "Hello"
```
With `--max-iterations 3`, each device logs these lines after the third message:
```txt
[INFO] Configured maximum number of iterations reached. Leaving RUNNING state.
[STATE] RUNNING ---> READY
```
## Test the example
The test script `test-ex-1-1.sh` starts the two devices in the background, in one terminal. Among others,
it adds these options to the commands of the start script:
| Option | Value in the test | Effect |
| --- | --- | --- |
| `--transport` | the first argument of the script, default `zeromq` | The transport of the devices. |
| `--session` | the output of [`fairmq-uuid-gen -h`](/reference/tools/#fairmq-uuid-gen) | A new session for each run. |
| `--control` | `static` | The process ends when the device leaves `RUNNING`. |
| `--max-iterations` | `1` | Each device stops after one message. |
| `--shm-segment-size` | `100000000` | A 100 MB shared memory segment. |
| `--shm-monitor` | `true` | With `shmem`, starts [`fairmq-shmmonitor`](/tools/shmmonitor/) as a daemon. |
The test uses an `ipc://` address instead of TCP: `ipc:///tmp/fmq_<session>_data_<transport>`. At the end,
the script deletes this file.
CTest runs the script once for each transport. The tests are `Example.1-1.zeromq` and `Example.1-1.shmem`,
each with a timeout of 30 s. CTest has these tests only if you configure with `-DBUILD_TESTING=ON`. The
default is `OFF`.
```sh
cmake -S FairMQ -B build -DBUILD_TESTING=ON
cmake --build build
cd build
ctest -R '^Example\.1-1\.' --output-on-failure
```
You can also run the script directly, for example `./test-ex-1-1.sh shmem` in `build/examples/1-1`.
To write a test of this type for your own devices, see [Test your devices](/guides/test-devices/). To add
an example with its test to FairMQ, see [Add an example](/project/contributing/#add-an-example).
## Things to try
- Use shared memory: add `--transport shmem` to both commands. Both devices must use the same session. If
you do not set `--session`, both use the session `default`.
- Change the rate: start the sampler with `--rate 10`. Without `--rate`, the sampler sends as fast as it
can.
- Send another text: start the sampler with `--text "Hello FairMQ"`.
- Stop after five messages: add `--max-iterations 5` to both commands. Also add `--control static` to end
the processes when the devices leave `RUNNING`. To check that no message is lost, see
[Check that no message is lost](/guides/end-of-run/#check-that-no-message-is-lost).
- Show the transfer rates: set `rateLogging=1` in both channel configurations. Each second, the device
logs the messages per second and the MB per second of the channel.
- Swap bind and connect: the sink binds `tcp://*:5555`, and the sampler connects to `tcp://localhost:5555`.
- Show all options of a device, with the custom options: run it with `--help`.
## Related pages
- [Your first device](/start/first-device/): write and build a device like this one.
- [Device states](/concepts/states/): the states that the devices go through.
- [Channels and sockets](/concepts/channels/): socket types and methods.
- [Receive data with callbacks or loops](/guides/receive-data/): `OnData()` compared to `ConditionalRun()`.
- [1-n-1: sampler, processors and sink](/examples/1-n-1/): the next example.

View File

@@ -0,0 +1,181 @@
---
title: '1-n-1: sampler, processors and sink'
description: 'A sampler sends messages to several processors, and the processors send the results to one sink. A JSON file configures the channels.'
sidebar:
order: 2
code: [fairmq/Device.h, fairmq/JSONParser.cxx, fairmq/plugins/config/Config.cxx]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps, FileTree } from '@astrojs/starlight/components';
The 1-n-1 example puts processors between a sampler and a sink. The sampler distributes its messages over
the processors, each processor changes the text, and the sink collects the results. A JSON file configures
the channels of all devices, and the two processors share one entry of this file.
The files of the example are in
[`examples/1-n-1`](https://github.com/FairRootGroup/FairMQ/tree/dev/examples/1-n-1) on GitHub.
## Topology
The topology comes from the file `ex-1-n-1.json`:
| Device | Channel | Type | Method | Address |
| --- | --- | --- | --- | --- |
| `sampler1` | `data1` | `push` | `bind` | `tcp://*:5555` |
| `processor1`, `processor2` | `data1` | `pull` | `connect` | `tcp://localhost:5555` |
| `processor1`, `processor2` | `data2` | `push` | `connect` | `tcp://localhost:5556` |
| `sink1` | `data2` | `pull` | `bind` | `tcp://*:5556` |
All sockets have `sndBufSize` 1000, `rcvBufSize` 1000 and `rateLogging` 0. The sampler and the sink bind,
and the processors connect. Thus all processors have the same configuration, and you can add processors
at any time. The `push` socket of the sampler sends each message to one connected processor, in turn
(round-robin). The `pull` socket of the sink receives from all processors.
## The JSON file
The file has one entry for each device in `fairMQOptions.devices`. This is the entry of the processors:
<Snippet file="examples/1-n-1/ex-1-n-1.json" start='"key": "processor"' end="^ ]$" />
A device uses the entry whose `id` is equal to its `--id`. With `--config-key processor`, the device uses
the entry with `"key": "processor"` instead ([Config.cxx](/source/fairmq/plugins/config/Config.cxx/#L29-L33),
[JSONParser.cxx](/source/fairmq/JSONParser.cxx/#L69)). Thus `processor1` and `processor2` have different
IDs, but the same channels. The [JSON configuration](/reference/json/) page describes the format.
## Build the example
The examples build together with FairMQ when the CMake option `BUILD_EXAMPLES` is `ON` (the default). The
build copies the JSON file to the build directory of the example:
<FileTree>
- build/examples/1-n-1/
- fairmq-ex-1-n-1-sampler
- fairmq-ex-1-n-1-processor
- fairmq-ex-1-n-1-sink
- ex-1-n-1.json
- fairmq-start-ex-1-n-1.sh
- test-ex-1-n-1.sh
</FileTree>
The install step copies the JSON file to `<prefix>/share/fairmq/`. The installed start script uses this
copy.
## Run the example
<Steps>
1. Go to the directory of the example in the build tree:
```sh
cd build/examples/1-n-1
```
2. Run the start script. It opens four `xterm` windows, one for each device:
```sh
./fairmq-start-ex-1-n-1.sh
```
</Steps>
To run the example without `xterm`, run each command in its own terminal in `build/examples/1-n-1`:
```sh
./fairmq-ex-1-n-1-sampler --id sampler1 --mq-config ex-1-n-1.json
./fairmq-ex-1-n-1-processor --id processor1 --mq-config ex-1-n-1.json --config-key processor
./fairmq-ex-1-n-1-processor --id processor2 --mq-config ex-1-n-1.json --config-key processor
./fairmq-ex-1-n-1-sink --id sink1 --mq-config ex-1-n-1.json
```
Push `q` in a terminal to stop the device in it.
## The code
<Snippet file="examples/1-n-1/sampler.cxx" start="bool ConditionalRun()" />
[`NewStaticMessage()`](/api/fair/mq/Device/#NewStaticMessage) creates a message for the data of `fText`
and does not delete the data after the transfer. The `zeromq` transport does not copy the data, so the data
must stay valid until the transfer is complete. `fText` is a member of the device, so it stays valid. The
`shmem` transport copies the data into shared memory when it creates the message
([shmem/Message.h](/source/fairmq/shmem/Message.h/#L64-L78)). After each message, the sampler waits 1 s.
<Snippet file="examples/1-n-1/processor.cxx" start="Processor()" />
<Snippet file="examples/1-n-1/processor.cxx" start="bool HandleData" />
The processor registers `HandleData()` for the channel `data1` with
[`OnData()`](/api/fair/mq/Device/#OnData). For each message, it copies the text into a new string and adds
its device ID [`fId`](/api/fair/mq/Device/#fId). Then it sends the new message on `data2`. The processor has
no custom options, so it runs until you stop it.
The sink is the sink of the [1-1 example](/examples/1-1/#the-sink), with the channel `data2`.
## Output
The listings show the severity and the message of each line, without the time.
The sampler logs `Sending "Hello"` once per second. Each processor logs one line for each message that it
gets:
```txt
[INFO] Received data, processing...
```
The sink gets the messages of both processors:
```txt
[INFO] Received: "Hello (modified by processor1)"
[INFO] Received: "Hello (modified by processor2)"
[INFO] Received: "Hello (modified by processor1)"
```
## Test the example
The test script `test-ex-1-n-1.sh` configures the channels with `--channel-config` instead of the JSON file.
It uses `ipc://` addresses in `/tmp`, a new session, and `--control static`. The sampler and the sink stop
after two messages (`--max-iterations 2`). The processors have no such option, so the script stops them
with `SIGINT` after the sampler and the sink end.
CTest runs the script once for each transport: `Example.1-n-1.zeromq` and `Example.1-n-1.shmem`. The tests
exist if you configure with `-DBUILD_TESTING=ON`.
```sh
cd build
ctest -R '^Example\.1-n-1\.' --output-on-failure
```
## Things to try
- Add a processor while the other devices run. The sampler then distributes the messages over three
processors:
```sh
./fairmq-ex-1-n-1-processor --id processor3 --mq-config ex-1-n-1.json --config-key processor
```
- Configure a processor without the JSON file, as the test script does. One `--channel-config` option takes
one value for each channel:
```sh
./fairmq-ex-1-n-1-processor --id processor3 \
--channel-config "name=data1,type=pull,method=connect,address=tcp://localhost:5555,rateLogging=0" \
"name=data2,type=push,method=connect,address=tcp://localhost:5556,rateLogging=0"
```
If you give `--mq-config` and `--channel-config` together, the device uses only `--mq-config`
([Config.cxx](/source/fairmq/plugins/config/Config.cxx/#L37-L45)).
- Send another text: start the sampler with `--text "Hi"`.
- Use shared memory: add `--transport shmem` to all four commands.
- Stop after four messages: add `--max-iterations 4` to the commands of the sampler and the sink.
## Related pages
- [JSON configuration](/reference/json/): all keys of the JSON file.
- [Configure channels](/guides/configure-channels/): `--channel-config`, `--mq-config` and code.
- [Channels and sockets](/concepts/channels/): how `push` and `pull` distribute messages.
- [1-1: sampler and sink](/examples/1-1/): the code of the sampler and the sink in detail.
- [Design a topology](/guides/design-topology/#fan-out-and-fan-in): fan-out and fan-in with `push` and `pull`.

View File

@@ -0,0 +1,150 @@
---
title: 'builtin-devices: a topology of built-in devices'
description: 'The built-in devices fairmq-bsampler, fairmq-splitter, fairmq-proxy, fairmq-merger, fairmq-multiplier and fairmq-sink in one topology, without own code.'
sidebar:
order: 10
code: [fairmq/devices/BenchmarkSampler.h, fairmq/devices/Splitter.h, fairmq/devices/Merger.h, fairmq/devices/Multiplier.h, fairmq/devices/Sink.h]
---
import Snippet from '../../../components/Snippet.astro';
import { FileTree } from '@astrojs/starlight/components';
This example has no own code. Its start script connects the [built-in devices](/tools/builtin-devices/) of FairMQ into one topology. The messages go from a benchmark sampler through a splitter, two proxies, a merger and a multiplier to a sink.
The code is in [`examples/builtin-devices`](https://github.com/FairRootGroup/FairMQ/tree/dev/examples/builtin-devices). The example shows how to:
- configure the built-in devices with command-line options only,
- distribute messages over the [sub-channels](/concepts/channels/) of a channel (splitter),
- collect messages from all sub-channels of a channel (merger),
- send each message to all sub-channels of a channel (multiplier),
- transfer single messages or [multipart messages](/concepts/messages/) with `--multipart`.
## Topology
All channels have `sndBufSize=50` and `rcvBufSize=50`. A channel with two addresses has two sub-channels.
| Device | Executable | Channel | Type | Method | Address |
| --- | --- | --- | --- | --- | --- |
| `bsampler1` | `fairmq-bsampler` | `data1` | `push` | `bind` | `tcp://localhost:5555` |
| `splitter` | `fairmq-splitter` | `data1` | `pull` | `connect` | `tcp://localhost:5555` |
| | | `data2` | `push` | `bind` | `tcp://localhost:5556`, `tcp://localhost:5557` |
| `proxy1` | `fairmq-proxy` | `data2` | `pull` | `connect` | `tcp://localhost:5556` |
| | | `data3` | `push` | `connect` | `tcp://localhost:5558` |
| `proxy2` | `fairmq-proxy` | `data2` | `pull` | `connect` | `tcp://localhost:5557` |
| | | `data3` | `push` | `connect` | `tcp://localhost:5559` |
| `merger` | `fairmq-merger` | `data3` | `pull` | `bind` | `tcp://localhost:5558`, `tcp://localhost:5559` |
| | | `data4` | `push` | `connect` | `tcp://localhost:5560` |
| `multiplier` | `fairmq-multiplier` | `data4` | `pull` | `bind` | `tcp://localhost:5560` |
| | | `data5` | `push` | `connect` | `tcp://localhost:5561`, `tcp://localhost:5561` |
| `sink1` | `fairmq-sink` | `data5` | `pull` | `bind` | `tcp://localhost:5561` |
Each device gets the names of its channels with `--in-channel` and `--out-channel`. Both sub-channels of `data5` connect to the same sink. Thus the sink receives each message two times.
The sampler sends messages of 100000 bytes, at most 100 messages per second (`--msg-size 100000`, `--msg-rate 100`). The sampler and the sink run without a limit (`--max-iterations 0`).
## Requirements
The start script opens one `xterm` window for each device. `xterm` must be installed.
## Build and run
The built-in devices are part of the FairMQ build. The example adds only the scripts. The start script uses the executables in `build/fairmq`:
<FileTree>
- build/
- fairmq/
- fairmq-bsampler
- fairmq-splitter
- fairmq-proxy
- fairmq-merger
- fairmq-multiplier
- fairmq-sink
- examples/builtin-devices/
- fairmq-start-ex-builtin-devices.sh
- test-ex-builtin-devices.sh
</FileTree>
The start script takes three optional arguments: the transport (default `zeromq`), `true` or `false` for `--multipart` (default `false`), and the number of parts (default `1`).
```sh
cd build/examples/builtin-devices
./fairmq-start-ex-builtin-devices.sh
./fairmq-start-ex-builtin-devices.sh shmem true 4
```
The sampler uses `--control interactive`. The other devices use the default `--control dynamic`, which is the same interactive controller. Type `q` in the window of a device to end it. Type `h` to see all keys.
## The code
The code of the devices is in `fairmq/devices/`. This section shows the parts that move the messages.
### Configure a device
The start script builds the command line of each device. The splitter gets its input and output channels by name. Its output channel has two addresses:
<Snippet file="examples/builtin-devices/fairmq-start-ex-builtin-devices.sh.in" start='SPLITTER="fairmq-splitter"' end="xterm" />
### Splitter: one sub-channel after the other
The splitter ([`Splitter.h`](/source/fairmq/devices/Splitter.h/)) registers `HandleData()` with [`OnData()`](/api/fair/mq/Device/#OnData) for its input channel. Each call sends the payload to the next sub-channel of the output channel:
<Snippet file="fairmq/devices/Splitter.h" start="bool HandleData(T& payload, int)" />
### Merger: poll all sub-channels
The merger makes a poller for all sub-channels of its input channel. In each loop, it waits up to 100 ms for data. Then it forwards the data from each sub-channel that has input. See [`Merger.h`](/source/fairmq/devices/Merger.h/#L44-L101) and [Poll several channels](/guides/poll-channels/).
### Multiplier: copy to all outputs
The multiplier ([`Multiplier.h`](/source/fairmq/devices/Multiplier.h/)) sends a copy to each sub-channel of each output channel. It sends the original message to the last sub-channel of the last output channel:
<Snippet file="fairmq/devices/Multiplier.h" start="bool HandleSingleData" />
[`Copy()`](/api/fair/mq/Message/#Copy) shares the data of the message and does not duplicate it. For multipart messages, `HandleMultipartData()` copies each part in the same way.
## Output
The sampler logs when it starts and when `RUNNING` ends:
```txt
Starting the benchmark with message size of 100000 and 0 iterations.
Done <n> iterations in <t>ms.
```
The sink logs the same two points:
```txt
Starting sink and expecting to receive 0 messages.
Received <n> messages in <t>ms.
Leaving RUNNING state.
```
The proxies and the merger log `Transfer interrupted` on the severity `debug` when a transfer is interrupted, for example at a state change. The start script sets `--severity debug` only for the sampler and the sink.
## Test
`examples/builtin-devices/CMakeLists.txt` adds four tests: `Example.builtin-devices.single_msg.zeromq`, `Example.builtin-devices.multipart.zeromq`, `Example.builtin-devices.single_msg.shmem` and `Example.builtin-devices.multipart.shmem`. Each test runs `test-ex-builtin-devices.sh` with the transport and the variant as arguments. The timeout is 30 s.
The test script uses `ipc://` addresses, `--control static` and `--msg-rate 1`. The variant `multipart` sets `--multipart true` and sends two parts. The sink stops at `--max-iterations 2`. Then the script stops the other devices with `SIGINT`.
Configure with `-DBUILD_TESTING=ON` to register the tests. Then run them in the build directory:
```sh
ctest -R Example.builtin-devices
```
## Things to try
- Write the received data to a file. Add `--out-filename /tmp/sink.bin` to the sink. The sink stops after `--max-file-size` bytes (default 2000000000).
- Remove one of the two addresses of `data5` in the multiplier. Then the sink receives each message once.
- Send more data. Raise `--msg-rate` or set it to `0` (no limit).
- Use the script `startMQBenchmark.sh` in `build/fairmq` for a benchmark with a sampler and a sink. See [Run a benchmark](/guides/benchmark/).
## Related pages
- [Built-in devices](/tools/builtin-devices/): all options of each device.
- [Channels and sockets](/concepts/channels/)
- [Poll several channels](/guides/poll-channels/)
- [Messages and multipart](/concepts/messages/)

View File

@@ -0,0 +1,159 @@
---
title: 'copypush: one message to several receivers'
description: 'A sampler sends the same data to two sinks. It makes a copy of each message for each sub-channel of a push channel.'
sidebar:
order: 5
code: [fairmq/Message.h, fairmq/Device.h, fairmq/SuboptParser.cxx]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps, FileTree } from '@astrojs/starlight/components';
The copypush example sends the same data to several receivers. The sampler has one channel with two
[sub-channels](/concepts/channels/), and it sends one copy of each message on each sub-channel.
[`Copy()`](/api/fair/mq/Message/#Copy) makes the copy without a copy of the data.
The files of the example are in
[`examples/copypush`](https://github.com/FairRootGroup/FairMQ/tree/dev/examples/copypush) on GitHub.
## Topology
| Device | Channel | Type | Method | Address |
| --- | --- | --- | --- | --- |
| `sampler1` | `data[0]` | `push` | `bind` | `tcp://*:5555` |
| `sampler1` | `data[1]` | `push` | `bind` | `tcp://*:5556` |
| `sink1` | `data` | `pull` | `connect` | `tcp://localhost:5555` |
| `sink2` | `data` | `pull` | `connect` | `tcp://localhost:5556` |
The channel configuration of the sampler has two `address` keys. Each `address` key makes one sub-channel,
and the sub-channels share the other keys ([SuboptParser.cxx](/source/fairmq/SuboptParser.cxx/#L105-L108)).
Each sub-channel has its own socket, and one sink connects to it.
## Build the example
The examples build together with FairMQ when the CMake option `BUILD_EXAMPLES` is `ON` (the default):
<FileTree>
- build/examples/copypush/
- fairmq-ex-copypush-sampler
- fairmq-ex-copypush-sink
- fairmq-start-ex-copypush.sh
- test-ex-copypush.sh
</FileTree>
## Run the example
<Steps>
1. Go to the directory of the example in the build tree:
```sh
cd build/examples/copypush
```
2. Run the start script. It opens three `xterm` windows, one for each device:
```sh
./fairmq-start-ex-copypush.sh
```
</Steps>
To run the example without `xterm`, run each command in its own terminal in `build/examples/copypush`:
```sh
./fairmq-ex-copypush-sampler --id sampler1 \
--channel-config "name=data,type=push,method=bind,rateLogging=0,address=tcp://*:5555,address=tcp://*:5556"
```
```sh
./fairmq-ex-copypush-sink --id sink1 \
--channel-config "name=data,type=pull,method=connect,rateLogging=0,address=tcp://localhost:5555"
```
```sh
./fairmq-ex-copypush-sink --id sink2 \
--channel-config "name=data,type=pull,method=connect,rateLogging=0,address=tcp://localhost:5556"
```
## The sampler
<Snippet file="examples/copypush/sampler.cxx" start="void InitTask()" />
[`GetNumSubChannels()`](/api/fair/mq/Device/#GetNumSubChannels) returns the number of sub-channels of a
channel. Here it is 2.
<Snippet file="examples/copypush/sampler.cxx" start="bool ConditionalRun()" />
- [`NewSimpleMessage()`](/api/fair/mq/Device/#NewSimpleMessage) creates a message with a copy of the
counter, a `uint64_t`.
- For each sub-channel except the last, the sampler creates an empty message with
[`NewMessage()`](/api/fair/mq/Device/#NewMessage). [`Copy()`](/api/fair/mq/Message/#Copy) makes it a copy
of `msg`.
- The third argument of [`Send()`](/api/fair/mq/Device/#Send) is the index of the sub-channel. The original
message goes to the last sub-channel.
- After each round, the sampler waits 1 s.
`Copy()` does not copy the data in the sampler. The `zeromq` transport shares the buffer between the two
messages (`zmq_msg_copy()`). The `shmem` transport increments a reference count of the buffer in shared
memory. Do not change the data of a message after a `Copy()`.
## The sink
<Snippet file="examples/copypush/sink.cxx" start="bool HandleData" />
The sink registers `HandleData()` for the channel `data` with [`OnData()`](/api/fair/mq/Device/#OnData).
The handler reads the counter from the data of the message. Both sinks run the same executable with
different IDs and addresses.
## Output
The listings show the severity and the message of each line, without the time. The sampler logs no line
for each message. Each sink logs every counter value, once per second:
```txt
[INFO] Received message: "0"
[INFO] Received message: "1"
[INFO] Received message: "2"
```
`sink1` and `sink2` get the same values.
## Push sub-channels compared to pub and sub
A `pub` socket also sends each message to all receivers. But the `shmem` transport does not support the
socket types `pub` and `sub` ([shmem/Socket.h](/source/fairmq/shmem/Socket.h/#L59-L62)). With one `push`
sub-channel for each sink, the example runs with both transports. You need one sub-channel, thus one
socket and one address, for each receiver.
## Test the example
The test script `test-ex-copypush.sh` starts the sampler and the two sinks with two `ipc://` addresses in
`/tmp`, a new session and `--control static`. All three devices stop after one message
(`--max-iterations 1`).
CTest runs the script once for each transport: `Example.copypush.zeromq` and `Example.copypush.shmem`. The
tests exist if you configure with `-DBUILD_TESTING=ON`.
```sh
cd build
ctest -R '^Example\.copypush\.' --output-on-failure
```
## Things to try
- Add a third sink. Add `address=tcp://*:5557` to the channel configuration of the sampler. Then start a
sink with `--id sink3` and `address=tcp://localhost:5557`. `GetNumSubChannels()` returns 3, and the
sampler sends to all three sinks.
- Use shared memory: add `--transport shmem` to all three commands.
- Stop after three messages: add `--max-iterations 3` to all three commands.
## Related pages
- [Messages and multipart](/concepts/messages/): message ownership and `Copy()`.
- [Channels and sockets](/concepts/channels/): channels, sub-channels and socket types.
- [1-n-1: sampler, processors and sink](/examples/1-n-1/): distribute messages instead of copying them.
- [multiple-channels: data and broadcast](/examples/multiple-channels/): a `pub` and `sub` channel.
- [Design a topology](/guides/design-topology/#fan-out-and-fan-in): distribute or copy messages to several receivers.

View File

@@ -0,0 +1,156 @@
---
title: 'custom-controller: control from code'
description: 'A controller plugin, compiled into the program, moves a device through all states; a state change callback ends the run after 3 s.'
sidebar:
order: 11
code: [fairmq/Plugin.h, fairmq/PluginServices.h, fairmq/DeviceRunner.h, fairmq/PluginManager.cxx]
---
import Snippet from '../../../components/Snippet.astro';
import { FileTree } from '@astrojs/starlight/components';
This example replaces the built-in controller of a device with an own [plugin](/concepts/plugins/). The plugin is compiled into the program. It takes device control and requests each [transition](/concepts/states/) from a state change callback.
The code is in [`examples/custom-controller`](https://github.com/FairRootGroup/FairMQ/tree/dev/examples/custom-controller). The example shows how to:
- write a controller plugin that takes device control,
- compile a plugin into the executable and load it with the prefix `s:`,
- start a device with [`DeviceRunner`](/api/fair/mq/DeviceRunner/) and its hooks, without `runDevice.h`,
- end the run through a property that the controller reads.
For the general procedure, see [Control a device from code](/guides/control-from-code/).
## Topology
The example has no channels. `MyDevice` in `MyDevice.h` is an alias of [`fair::mq::Device`](/api/fair/mq/Device/). The device goes through its states without data.
## Requirements
The example needs only FairMQ. It has no start script and no install rule.
## Build and run
The examples build when the CMake option `BUILD_EXAMPLES` is `ON` (the default). The executable is in the build directory:
<FileTree>
- build/examples/custom-controller/
- fairmq-ex-custom-controller
</FileTree>
```sh
cd build/examples/custom-controller
./fairmq-ex-custom-controller
```
The program stops by itself about 3 s after the device enters `RUNNING`. Its exit code is 0.
`CMakeLists.txt` sets the target property `ENABLE_EXPORTS ON`. The executable then exports its symbols, so the plugin manager can find the plugin factory in the program itself.
## The code
### The program
`main.cxx` creates a `DeviceRunner` and adds two hooks:
<Snippet file="examples/custom-controller/main.cxx" start="DeviceRunner runner(argc, argv);" end="return runner.RunWithExceptionHandlers();" />
- `hooks::LoadPlugins` runs after the runner loads the built-in plugin `config` and before it loads the built-in plugin `control`. The hook loads `s:mycontroller`. The prefix `s:` loads a static plugin, a plugin that is part of the executable. The name is the second argument of `REGISTER_FAIRMQ_PLUGIN`.
- `hooks::InstantiateDevice` sets the property `catch-signals` to 0. Thus the built-in control plugin installs no signal handler. The hook also creates the device and subscribes to its state changes with [`SubscribeToStateChange()`](/api/fair/mq/Device/#SubscribeToStateChange).
- In `RUNNING`, the callback waits 3 s with [`WaitFor()`](/api/fair/mq/Device/#WaitFor). Then it sets the property `please-shut-me-down` to `true`.
- [`RunWithExceptionHandlers()`](/api/fair/mq/DeviceRunner/#RunWithExceptionHandlers) runs the device. It returns 1 if an exception reaches it.
The hooks are declared in [`DeviceRunner.h`](/source/fairmq/DeviceRunner.h/#L84-L89). The order of the steps is in [`DeviceRunner.cxx`](/source/fairmq/DeviceRunner.cxx/#L108-L194).
### The controller plugin
`MyController` is a [`fair::mq::Plugin`](/api/fair/mq/Plugin/). The constructor takes device control and subscribes to the state changes of the device:
<Snippet file="examples/custom-controller/MyController.h" start="struct MyController : fair::mq::Plugin" />
- The plugin manager creates the plugins in their load order: `config`, `mycontroller`, `control`. Thus [`TakeDeviceControl()`](/api/fair/mq/Plugin/#TakeDeviceControl) of `mycontroller` succeeds first. The built-in control plugin cannot take control. It logs the reason on the severity `debug` and starts no controller.
- For each state, the callback requests the next transition with [`ChangeDeviceState()`](/api/fair/mq/Plugin/#ChangeDeviceState). In `BINDING`, `CONNECTING`, `INITIALIZING TASK`, `RESETTING TASK` and `RESETTING DEVICE`, the device changes state by itself, so the callback requests nothing.
- The callback reads `please-shut-me-down` with [`GetProperty()`](/api/fair/mq/Plugin/#GetProperty-2). The default is `false`.
- In `EXITING`, the plugin calls [`ReleaseDeviceControl()`](/api/fair/mq/Plugin/#ReleaseDeviceControl). `DeviceRunner::Run()` waits until all plugins release device control, and then returns.
The plugin requests these transitions:
| State | `please-shut-me-down` is `false` | `please-shut-me-down` is `true` |
| --- | --- | --- |
| `IDLE` | `InitDevice` | `End` |
| `INITIALIZING DEVICE` | `CompleteInit` | `CompleteInit` |
| `INITIALIZED` | `Bind` | `Bind` |
| `BOUND` | `Connect` | `Connect` |
| `DEVICE READY` | `InitTask` | `ResetDevice` |
| `READY` | `Run` | `ResetTask` |
| `RUNNING` | `Stop` | `Stop` |
The macro `REGISTER_FAIRMQ_PLUGIN` registers the class under the name `mycontroller`:
<Snippet file="examples/custom-controller/MyController.h" start="REGISTER_FAIRMQ_PLUGIN(example::MyController" end="fair::mq::Plugin::NoProgramOptions)" />
### The order of the callbacks
`RunStateMachine()` first calls the state change callbacks with `IDLE`, so the plugin requests `InitDevice`. In each later state, the state machine calls the state change callbacks before the state handler of the device. See [`StateMachine::ProcessWork()`](/source/fairmq/StateMachine.cxx/#L396-L414) and the [loop of the state machine](/source/fairmq/StateMachine.cxx/#L191-L219).
The state machine calls the callbacks in the order of the number at the start of their key. A key without a number, for example `example` or `mycontroller`, has the number 0. Callbacks with the same number run in the order of subscription. The hook in `main.cxx` subscribes before the plugin manager creates the plugin. Thus, in `RUNNING`, the callback of `main.cxx` runs first:
1. The callback of `main.cxx` waits 3 s and sets `please-shut-me-down` to `true`.
2. The callback of the plugin requests `Stop`.
3. The state handler of the device logs `fair::mq::Device running...`. The device has no own `Run()` code, and a transition is pending. Thus the device goes to `READY` at once.
4. In `READY`, `DEVICE READY` and `IDLE`, the plugin reads `true`. It requests `ResetTask`, `ResetDevice` and `End`.
## Output
The log shows each state change (here without the prefix of the logger):
```txt
Starting FairMQ state machine --> IDLE
IDLE ---> INITIALIZING DEVICE
INITIALIZING DEVICE ---> INITIALIZED
INITIALIZED ---> BINDING
BINDING ---> BOUND
BOUND ---> CONNECTING
CONNECTING ---> DEVICE READY
DEVICE READY ---> INITIALIZING TASK
INITIALIZING TASK ---> READY
READY ---> RUNNING
fair::mq::Device running...
RUNNING ---> READY
READY ---> RESETTING TASK
RESETTING TASK ---> DEVICE READY
DEVICE READY ---> RESETTING DEVICE
RESETTING DEVICE ---> IDLE
IDLE ---> EXITING
```
The 3 s pause is between `READY ---> RUNNING` and `fair::mq::Device running...`. `main.cxx` sets the console severity to `debug`, so the log also shows debug lines. The log also has these warnings:
- `Signal handling (e.g. Ctrl-C) has been deactivated.`, because `catch-signals` is 0.
- `No device ID or config-key provided for the configuration parser.`, because the program gives no `--id`.
- `No channels created after finishing initialization`, because the device has no channels.
## Test
`examples/custom-controller/CMakeLists.txt` adds the test `Example.custom-controller`. It runs the executable and passes when the exit code is 0. The timeout is 30 s.
Configure with `-DBUILD_TESTING=ON` to register the test. Then run it in the build directory:
```sh
ctest -R Example.custom-controller
```
## Things to try
- Change the time in `WaitFor(3s)`.
- Set `please-shut-me-down` to `true` in the hook `InstantiateDevice`. Then the plugin requests `End` in the first `IDLE`, and the device never runs.
- Give the plugin its own options. Remove the `//` in front of the function `MyControllerProgramOptions()` in `MyController.h`. Then use `example::MyControllerProgramOptions` as the last argument of `REGISTER_FAIRMQ_PLUGIN`, in place of `fair::mq::Plugin::NoProgramOptions`. The options `--custom-dummy-option` and `--custom-dummy-option2` then show in the output of `--help`.
## Related pages
- [Control a device from code](/guides/control-from-code/)
- [Write a plugin](/guides/write-plugin/)
- [Plugins and control](/concepts/plugins/)
- [Device states](/concepts/states/)
- [States and transitions](/reference/states/)

View File

@@ -0,0 +1,198 @@
---
title: 'dds: run with DDS'
description: 'A sampler, ten processors and a sink in a DDS topology without channel addresses; the start script needs DDS and a DDS plugin for FairMQ.'
sidebar:
order: 12
code: [fairmq/Device.h, fairmq/Device.cxx, fairmq/PluginManager.cxx, fairmq/runDevice.h]
---
import Snippet from '../../../components/Snippet.astro';
import { FileTree } from '@astrojs/starlight/components';
This example describes a topology for the deployment system DDS. One sampler sends messages to ten processors, and the processors send them to one sink. The topology file gives the [channels](/concepts/channels/) no addresses. The binding channels get [automatic addresses](/concepts/channels/#automatic-ports). A DDS [plugin](/concepts/plugins/) must give the addresses to the connecting channels at run time.
:::caution
FairMQ alone cannot run this example. The start script needs DDS, a DDS plugin for FairMQ and the tool `fairmq-dds-command-ui`. DDS is not part of FairMQ. FairMQ v1.5.0 and later do not contain the plugin and the tool. See [Requirements](#requirements).
:::
The code is in [`examples/dds`](https://github.com/FairRootGroup/FairMQ/tree/dev/examples/dds). The example shows how to:
- describe the devices, their channels and their number in a DDS topology file,
- configure channels without addresses,
- request the transitions of all devices from a script,
- send a message that uses a buffer of the device and a function that deletes the buffer.
## Topology
The topology file `ex-dds-topology.xml` declares three tasks. Each task starts one device. The group `ProcessorGroup` has `n="10"`, so DDS starts the task `Processor` 10 times.
| Task | Instances | Channel | Type | Method | Address |
| --- | --- | --- | --- | --- | --- |
| `Sampler` | 1 | `data1` | `push` | `bind` | not set |
| `Processor` | 10 | `data1` | `pull` | `connect` | not set |
| | | `data2` | `push` | `connect` | not set |
| `Sink` | 1 | `data2` | `pull` | `bind` | not set |
Each task configures its channels with `--channel-config` and loads the plugin with `-P dds`. No task sets `--id`. The sampler and the sink stop after 10 messages (`--iterations 10`).
<Snippet file="examples/dds/ex-dds-topology.xml" lang="xml" start='<decltask name="Processor">' end="</decltask>" />
The file declares the properties `fmqchan_data1` and `fmqchan_data2`. The task `Sampler` has write access to `fmqchan_data1`, and the task `Sink` has write access to `fmqchan_data2`. The task `Processor` has read access to both. In DDS, the tasks with read access get the values that the tasks with write access set. The DDS plugin of FairMQ v1.4.56 (`fairmq/plugins/DDS/DDS.cxx` at the tag `v1.4.56`) used these properties:
- In `BOUND`, it wrote the bound addresses of each binding channel `<name>` to the property `fmqchan_<name>`.
- When it had a value of `fmqchan_<name>` for each sub-channel of a connecting channel `<name>`, it set the properties `chans.<name>.<index>.address` to these addresses.
A connecting channel waits for its address. In `CONNECTING`, the device reads `chans.<name>.<index>.address` again every 50 ms, until all channels connect or `--init-timeout` ends (default 120 s). See [`Device.cxx`](/source/fairmq/Device.cxx/#L235-L276).
Each task also has a requirement of the type `wnname`, with the value `sampler`, `processor` or `sink`. These values are the first column of `ex-dds-hosts.cfg`.
In `ex-dds-topology-infinite.xml`, the sampler sends without an end, at most 100 messages per second (`--rate 100 --iterations 0`). The sink has no `--iterations` there, so it uses the default 1000. The start script does not use this file.
## Requirements
The three devices build with FairMQ alone. The CMake files of FairMQ do not search for DDS. To run the start script, you need:
- DDS. The start script calls `dds-session`, `dds-submit`, `dds-info`, `dds-topology`, `dds-agent-cmd` and `dds-user-defaults`.
- A DDS plugin for FairMQ: a library with the name `libfairmq-plugin-dds` or `libFairMQPlugin_dds`.
- The tool `fairmq-dds-command-ui`.
FairMQ v1.4.56 is the last release that contains the DDS plugin (`fairmq/plugins/DDS`, library `FairMQPlugin_dds`) and `fairmq-dds-command-ui` (`fairmq/sdk`). FairMQ v1.5.0 and later do not contain them. The commit that removes them says that these components moved to the ODC project. It refers to [discussion #392](https://github.com/FairRootGroup/FairMQ/discussions/392).
The scripts in the build directory add `build/fairmq/sdk` to `PATH`. This is the old directory of `fairmq-dds-command-ui`, and FairMQ does not build it now. Add the directory of your `fairmq-dds-command-ui` to `PATH`.
### Load the plugin
`-P dds` loads the plugin from a shared library. The plugin manager searches the directories of `-S` (`--plugin-search-path`) for `libfairmq-plugin-dds` and `libFairMQPlugin_dds`, with the library suffix of the system. Then it tries the system lookup: the system library directories, `RUNPATH` and `LD_LIBRARY_PATH`. See [`PluginManager.cxx`](/source/fairmq/PluginManager.cxx/#L169-L230).
The plugin manager loads the plugins of `-P` in the constructor of `DeviceRunner`. If it finds no library, the program stops before it creates the device. The exit code is 1, and the log shows:
```txt
Uncaught exception reached the top of main: Could not load dynamic plugin dds from configured search paths (-S) nor with system lookup (system libdirs, RUNPATH, $LD_LIBRARY_PATH).
```
## Build and run
The examples build when the CMake option `BUILD_EXAMPLES` is `ON` (the default). CMake writes these files to the build directory:
<FileTree>
- build/examples/dds/
- fairmq-ex-dds-sampler
- fairmq-ex-dds-processor
- fairmq-ex-dds-sink
- fairmq-start-ex-dds.sh
- fairmq-ex-dds-env.sh
- ex-dds-topology.xml
- ex-dds-topology-infinite.xml
- ex-dds-hosts.cfg
</FileTree>
The install step copies the executables and the two scripts to `bin`, and the topology files and `ex-dds-hosts.cfg` to `share/fairmq` in the install prefix.
The start script takes one optional argument: the plugin that `dds-submit` uses to start the agents, `localhost` (default) or `ssh`. With `ssh`, the script gives `ex-dds-hosts.cfg` to `dds-submit`.
```sh
cd build/examples/dds
./fairmq-start-ex-dds.sh
./fairmq-start-ex-dds.sh ssh
```
The script does these steps. `set -e` stops it at the first command that fails.
1. It starts a DDS session and exports `DDS_SESSION_ID`. When the script exits, a trap stops the session.
2. It submits the agents and waits for 12 idle slots.
3. It exports `FAIRMQ_DDS_TOPO_FILE`, activates `ex-dds-topology.xml` and waits for 12 executing slots.
4. It requests the transitions with `fairmq-dds-command-ui`.
5. It stops the topology, gets the log files of the agents and prints `Example successful`.
Each task has `fairmq-ex-dds-env.sh` as its `env` element. This script adds the directory of the executables to `PATH`.
### Request the transitions
Step 4 of the script requests the transitions of all devices:
<Snippet file="examples/dds/fairmq-start-ex-dds.sh.in" start='fairmq-dds-command-ui -w "IDLE"' end="fairmq-dds-command-ui -c q" />
The script waits until the sampler and the sink go from `RUNNING` to `READY`, after 10 messages. Then it stops all devices. The script uses the options of `fairmq-dds-command-ui` of FairMQ v1.4.56 (`fairmq/sdk/runDDSCommandUI.cxx` at the tag `v1.4.56`). In that version, the tool read the session from `DDS_SESSION_ID` and the topology file from `FAIRMQ_DDS_TOPO_FILE`. Its options had this meaning:
| Option | Meaning in v1.4.56 |
| --- | --- |
| `-c i`, `-c k`, `-c b`, `-c x`, `-c j`, `-c r` | Request `InitDevice`, `CompleteInit`, `Bind`, `Connect`, `InitTask` or `Run`. |
| `-c s`, `-c t`, `-c d`, `-c q` | Request `Stop`, `ResetTask`, `ResetDevice` or `End`. |
| `-c p` | Set the property `--property-key` to the value `--property-value`. |
| `-w <state>` | Wait until the devices are in the state. |
| `-w "<state1>-><state2>"` | Wait until the devices go from `<state1>` to `<state2>`. |
| `-p <path>` | Send the command to, or wait for, only the tasks of this topology path. Without `-p`, the tool uses all tasks. |
For the transitions, see [States and transitions](/reference/states/).
## The code
### Sampler
The sampler sends the string `Data` in each [`ConditionalRun()`](/api/fair/mq/Device/#ConditionalRun) call. [`NewSimpleMessage()`](/api/fair/mq/Device/#NewSimpleMessage) copies the data into a new message.
<Snippet file="examples/dds/sampler.cxx" start="bool ConditionalRun() override" />
After `--iterations` messages (default 1000, `0` for no limit), `ConditionalRun()` returns `false`. Then the device goes to `READY`.
### Processor
The processor registers `HandleData()` for `data1` with [`OnData()`](/api/fair/mq/Device/#OnData). It appends ` (modified by <id>)` to the text, with the device id of the processor.
<Snippet file="examples/dds/processor.cxx" start="bool HandleData" />
The new message gets the buffer of the string and a function that deletes the string. See [`CreateMessage()`](/api/fair/mq/TransportFactory/#CreateMessage-5) and [Messages](/concepts/messages/).
- The zeromq transport, the default, sends the buffer without a copy. It calls the function when it no longer needs the buffer.
- The shmem transport copies the data into the managed segment and calls the function at once.
### Sink
The sink registers its `HandleData()` for `data2` and logs each text. After `--iterations` messages (default 1000, `0` for no limit), it returns `false`, and the device goes to `READY`.
## Output
The sampler logs each message and the end:
```txt
Sending "Data"
Sent 10 messages. Finished.
```
Each processor logs `Received data, processing...` for each message. The sink logs each text and the end:
```txt
Received: "Data (modified by <id>)"
Received 10 messages. Finished.
```
`<id>` is the id of the processor. When `--id` was empty, the DDS plugin of FairMQ v1.4.56 set the id to the path of the DDS task. At the end, the start script calls `dds-agent-cmd getlog -a`. If this command succeeds, the script prints `AGENT LOG FILES IN: <directory>`.
## Test
The example has no test. In `CMakeLists.txt`, the test `Example.DDS.localhost` is a comment. It runs `fairmq-start-ex-dds.sh localhost` with a timeout of 15 s and expects the output `Example successful`.
## Things to try
- Run the devices without DDS. Remove `-P dds` and give each channel an address. Start each device in its own terminal in `build/examples/dds`:
```sh
./fairmq-ex-dds-sampler --id sampler1 --iterations 10 --channel-config name=data1,type=push,method=bind,address=tcp://127.0.0.1:5555
./fairmq-ex-dds-processor --id processor1 --channel-config name=data1,type=pull,method=connect,address=tcp://127.0.0.1:5555 name=data2,type=push,method=connect,address=tcp://127.0.0.1:5556
./fairmq-ex-dds-sink --id sink1 --iterations 10 --channel-config name=data2,type=pull,method=bind,address=tcp://127.0.0.1:5556
```
The devices use the interactive controller. Type `q` in each terminal to end the device.
- Start the processor without the address of `data1`. It waits in `CONNECTING`. After `--init-timeout` (default 120 s), it logs `could not connect all channels after 120 attempts` on the severity `error` and goes to the state `ERROR`.
- For a topology with many senders and receivers, see [n-m: n senders to m receivers](/examples/n-m/).
## Related pages
- [Plugins and control](/concepts/plugins/)
- [Configure channels](/guides/configure-channels/)
- [n-m: n senders to m receivers](/examples/n-m/)
- [qc: quality control on demand](/examples/qc/)
- [Configuration](/concepts/configuration/)

View File

@@ -0,0 +1,200 @@
---
title: 'multipart: several parts in one message'
description: 'A sampler sends a header and six data parts as one multipart message, and a sink receives all parts in one handler call.'
sidebar:
order: 4
code: [fairmq/Parts.h, fairmq/Device.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps, FileTree } from '@astrojs/starlight/components';
The multipart example sends one message that has several parts. The sampler puts a header and six data
parts into a [`fair::mq::Parts`](/api/fair/mq/Parts/) object and sends all parts with one `Send()` call.
The sink gets all seven parts in one call of its data handler. The
[Messages and multipart](/concepts/messages/) page explains the concept.
The files of the example are in
[`examples/multipart`](https://github.com/FairRootGroup/FairMQ/tree/dev/examples/multipart) on GitHub.
## Topology
| Device | Channel | Type | Method | Address |
| --- | --- | --- | --- | --- |
| `sampler1` | `data` | `push` | `connect` | `tcp://127.0.0.1:5555` |
| `sink1` | `data` | `pull` | `bind` | `tcp://127.0.0.1:5555` |
Here the sink binds and the sampler connects. Both devices use `rateLogging=0`.
## Build the example
The examples build together with FairMQ when the CMake option `BUILD_EXAMPLES` is `ON` (the default):
<FileTree>
- build/examples/multipart/
- fairmq-ex-multipart-sampler
- fairmq-ex-multipart-sink
- fairmq-start-ex-multipart.sh
- test-ex-multipart.sh
</FileTree>
## Run the example
<Steps>
1. Go to the directory of the example in the build tree:
```sh
cd build/examples/multipart
```
2. Run the start script. It opens two `xterm` windows, one for each device:
```sh
./fairmq-start-ex-multipart.sh
```
</Steps>
The first argument of the script sets the transport, for example `./fairmq-start-ex-multipart.sh shmem`.
The default is `zeromq`. The script gives both devices the same session name, from `fairmq-uuid-gen -h`.
To run the example without `xterm`, run each command in its own terminal in `build/examples/multipart`.
Any session name works if both devices use the same one:
```sh
./fairmq-ex-multipart-sampler --id sampler1 --transport zeromq --session ex-multipart \
--channel-config "name=data,type=push,method=connect,rateLogging=0,address=tcp://127.0.0.1:5555"
```
```sh
./fairmq-ex-multipart-sink --id sink1 --transport zeromq --session ex-multipart \
--channel-config "name=data,type=pull,method=bind,rateLogging=0,address=tcp://127.0.0.1:5555"
```
## The header
<Snippet file="examples/multipart/Header.h" start="struct Header" />
The sampler and the sink include `Header.h`. The first part of each message is a `Header`. The sink stops
when `stopFlag` is `1`.
## The sampler
<Snippet file="examples/multipart/sampler.cxx" start="bool ConditionalRun()" />
- `fair::mq::Parts parts;` creates an empty multipart message. `Parts` holds a vector of
[`MessagePtr`](/api/fair/mq/#MessagePtr).
- [`NewSimpleMessage()`](/api/fair/mq/Device/#NewSimpleMessage) copies the header into a new message. The
transport deletes this copy when it does not need it any more. Use it for small data only.
- [`AddPart()`](/api/fair/mq/Parts/#AddPart-2) adds one message at the end.
- `NewMessage(1000)` creates a message of 1000 bytes. The example does not write data into it.
`NewMessage()` without arguments creates an empty part of 0 bytes.
- The [constructor](/api/fair/mq/Parts/#Parts-4) of `Parts` takes several messages.
[`AddPart()`](/api/fair/mq/Parts/#AddPart-4) with a `Parts` object moves all its parts to the end.
- [`At()`](/api/fair/mq/Parts/#At) returns the part at an index. [`Size()`](/api/fair/mq/Parts/#Size)
returns the number of parts.
- [`Send()`](/api/fair/mq/Device/#Send) sends all seven parts as one message.
The sampler sets `stopFlag` to `1` in its last message. The option `--max-iterations` of this sampler has
the default `5`, so the sampler stops after five messages. The value `0` sets no limit.
## The sink
<Snippet file="examples/multipart/sink.cxx" start="Sink()" />
<Snippet file="examples/multipart/sink.cxx" start="bool HandleData" />
The handler takes a `fair::mq::Parts&` instead of a message. With this handler type,
[`OnData()`](/api/fair/mq/Device/#OnData-3) receives multipart messages on the channel. The sink checks the
number of parts and reads the header from the data of part 0. To also check the size of each part, see
[Read the data safely](/guides/send-data-types/#read-the-data-safely).
- If the message does not have seven parts, the handler throws an exception. The device then goes to the
state `ERROR`.
- If `stopFlag` is `1`, the handler returns `false`. The log line says `going IDLE`, but the device goes to
the state `READY`.
## Output
The listings show the severity and the message of each line, without the time. The sampler logs two lines
for each message, once per second. The listing shows the first and the last message:
```txt
[INFO] Sending header with stopFlag: 0
[INFO] Sending body of size: 1000
[INFO] Sending header with stopFlag: 1
[INFO] Sending body of size: 1000
[INFO] Configured maximum number of iterations reached. Leaving RUNNING state.
```
The sink logs the parts of each message:
```txt
[INFO] Received message with 7 parts
[INFO] Received part 1 (header) with stopFlag: 0
[INFO] Received part 2 of size: 1000
[INFO] Received part 3 of size: 500
[INFO] Received part 4 of size: 600
[INFO] Received part 5 of size: 700
[INFO] Received part 6 of size: 0
[INFO] Received part 7 of size: 100
```
After the message with `stopFlag` 1, the sink also logs `stopFlag is 1, going IDLE`.
## Test the example
The test script `test-ex-multipart.sh` uses a `pair` channel instead of `push` and `pull`. The sampler
connects with `linger=1000`, and the sink binds. The channel uses an `ipc://` address in `/tmp`, and the
devices use `--control static`. The sampler has `--max-iterations 1`, so its first message has the
`stopFlag` 1. Thus both devices stop after one message.
CTest runs the script once for each transport: `Example.multipart.zeromq` and `Example.multipart.shmem`. The
tests exist if you configure with `-DBUILD_TESTING=ON`.
```sh
cd build
ctest -R '^Example\.multipart\.' --output-on-failure
```
## Things to try
- Use shared memory: run `./fairmq-start-ex-multipart.sh shmem`.
- Send without a limit: start the sampler with `--max-iterations 0`. `stopFlag` then stays `0`, and the sink
does not stop.
- Send to two sinks: use the JSON file of the next section.
### Send to two sinks
The source folder of the example has the file `ex-multipart-multiple-endpoints.json`. The build does not
copy it. In this file, one sampler sends to two sinks.
The `address` of the sampler has two endpoints, `tcp://localhost:5555,tcp://localhost:5556`. The socket of
the sampler connects to both. The entry of `sink2` has the method `connect`, but the address starts with
`@`:
<Snippet file="examples/multipart/ex-multipart-multiple-endpoints.json" start='"id": "sink2"' end="^ ]$" />
`@` in front of an endpoint makes the socket bind there, and `+` or `>` makes it connect
([Device.cxx](/source/fairmq/Device.cxx/#L300-L320)). Run each device in its own terminal, with the path of
the file in your source tree:
```sh
./fairmq-ex-multipart-sink --id sink1 --mq-config /path/to/FairMQ/examples/multipart/ex-multipart-multiple-endpoints.json
./fairmq-ex-multipart-sink --id sink2 --mq-config /path/to/FairMQ/examples/multipart/ex-multipart-multiple-endpoints.json
./fairmq-ex-multipart-sampler --id sampler1 --mq-config /path/to/FairMQ/examples/multipart/ex-multipart-multiple-endpoints.json
```
The `push` socket of the sampler distributes the messages over the two sinks. Only the sink that gets the
message with `stopFlag` 1 leaves `RUNNING`.
## Related pages
- [Messages and multipart](/concepts/messages/): messages, parts and their memory.
- [Receive data with callbacks or loops](/guides/receive-data/): handlers for messages and for parts.
- [Channel properties](/reference/channel-properties/): the `address` with several endpoints.
- [1-1: sampler and sink](/examples/1-1/): a sampler and a sink with single-part messages.
- [Stop a topology without losing messages](/guides/end-of-run/): end messages, linger and the stop order.

View File

@@ -0,0 +1,193 @@
---
title: 'multiple-channels: data and broadcast'
description: 'A sampler and a sink use a data channel and a broadcast channel. The sampler polls both channels, and the sink has one handler for each.'
sidebar:
order: 6
code: [fairmq/Poller.h, fairmq/Device.h, fairmq/Device.cxx]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps, FileTree } from '@astrojs/starlight/components';
The multiple-channels example shows devices with more than one channel. The sampler sends data to the sink
on the channel `data`. Both devices also receive the messages of a broadcaster on the channel `broadcast`.
The sampler checks its two channels with a [poller](/guides/poll-channels/), and the sink registers one data
handler for each channel.
The files of the example are in
[`examples/multiple-channels`](https://github.com/FairRootGroup/FairMQ/tree/dev/examples/multiple-channels)
on GitHub.
## Topology
| Device | Channel | Type | Method | Address |
| --- | --- | --- | --- | --- |
| `sampler1` | `data` | `push` | `bind` | `tcp://*:5555` |
| `sampler1` | `broadcast` | `sub` | `connect` | `tcp://localhost:5005` |
| `sink1` | `data` | `pull` | `connect` | `tcp://localhost:5555` |
| `sink1` | `broadcast` | `sub` | `connect` | `tcp://localhost:5005` |
| `broadcaster1` | `broadcast` | `pub` | `bind` | `tcp://*:5005` |
The `pub` socket of the broadcaster sends each message to all connected `sub` sockets. FairMQ subscribes
each `sub` socket to all messages ([zeromq/Socket.h](/source/fairmq/zeromq/Socket.h/#L70-L74)). All
channels use `rateLogging=0`.
:::caution[zeromq only]
The example needs the `zeromq` transport. The `shmem` transport does not support the socket types `pub` and
`sub`: it throws a `SocketError` when it creates such a socket
([shmem/Socket.h](/source/fairmq/shmem/Socket.h/#L59-L62)). Thus CTest runs this example only with
`zeromq`.
:::
## Build the example
The examples build together with FairMQ when the CMake option `BUILD_EXAMPLES` is `ON` (the default):
<FileTree>
- build/examples/multiple-channels/
- fairmq-ex-multiple-channels-sampler
- fairmq-ex-multiple-channels-sink
- fairmq-ex-multiple-channels-broadcaster
- fairmq-start-ex-multiple-channels.sh
- test-ex-multiple-channels.sh
</FileTree>
## Run the example
<Steps>
1. Go to the directory of the example in the build tree:
```sh
cd build/examples/multiple-channels
```
2. Run the start script. It opens three `xterm` windows, one for each device:
```sh
./fairmq-start-ex-multiple-channels.sh
```
</Steps>
To run the example without `xterm`, run each command in its own terminal in
`build/examples/multiple-channels`. One `--channel-config` option takes one value for each channel:
```sh
./fairmq-ex-multiple-channels-sampler --id sampler1 \
--channel-config "name=data,type=push,method=bind,rateLogging=0,address=tcp://*:5555" \
"name=broadcast,type=sub,method=connect,rateLogging=0,address=tcp://localhost:5005"
```
```sh
./fairmq-ex-multiple-channels-sink --id sink1 \
--channel-config "name=data,type=pull,method=connect,rateLogging=0,address=tcp://localhost:5555" \
"name=broadcast,type=sub,method=connect,rateLogging=0,address=tcp://localhost:5005"
```
```sh
./fairmq-ex-multiple-channels-broadcaster --id broadcaster1 \
--channel-config "name=broadcast,type=pub,method=bind,rateLogging=0,address=tcp://*:5005"
```
## The sampler
<Snippet file="examples/multiple-channels/sampler.cxx" start="void Run()" />
The sampler overrides [`Run()`](/api/fair/mq/Device/#Run) instead of `ConditionalRun()`. The device calls
`Run()` once in the state `RUNNING`. Thus `Run()` has its own loop, and it must return when
[`NewStatePending()`](/api/fair/mq/Device/#NewStatePending) is `true`.
- [`NewPoller()`](/api/fair/mq/Device/#NewPoller) creates a poller for the channels `data` and `broadcast`,
with all their sub-channels.
- [`Poll(100)`](/api/fair/mq/Poller/#Poll) waits for max. 100 ms for an event on one of the channels.
- [`CheckInput("broadcast", 0)`](/api/fair/mq/Poller/#CheckInput-2) is `true` if the sub-channel
`broadcast[0]` has a message to receive.
- [`CheckOutput("data", 0)`](/api/fair/mq/Poller/#CheckOutput-2) is `true` if the sub-channel `data[0]` can
send. The `zeromq` poller checks `push` sockets for output and `sub` sockets for input
([zeromq/Poller.h](/source/fairmq/zeromq/Poller.h/#L111-L123)).
- Before each send, the sampler waits 1 s. [`NewSimpleMessage()`](/api/fair/mq/Device/#NewSimpleMessage)
copies the text into a new message.
- At `--max-iterations`, the loop ends. When `Run()` returns, the device goes to `READY`.
All channels of one poller must use the same transport. Otherwise `NewPoller()` throws an exception
([Device.h](/source/fairmq/Device.h/#L218-L238)).
## The sink
<Snippet file="examples/multiple-channels/sink.cxx" start="Sink()" />
The sink calls [`OnData()`](/api/fair/mq/Device/#OnData) once for each channel. With more than one input
channel, the device polls all input channels and calls the handler of the channel that has a message
([Device.cxx](/source/fairmq/Device.cxx/#L449-L507)).
<Snippet file="examples/multiple-channels/sink.cxx" start="bool CheckIterations()" />
Both handlers return the result of `CheckIterations()`. With `--max-iterations`, the sink leaves `RUNNING`
only after it got messages on both channels.
## The broadcaster
<Snippet file="examples/multiple-channels/broadcaster.cxx" start="bool ConditionalRun()" />
Once per second, the broadcaster sends the text `OK` on its `pub` channel. It has no custom options, so it
runs until you stop it.
## Output
The listings show the severity and the message of each line, without the time. The lines of the two
channels mix, because the messages arrive in any order.
The sampler:
```txt
[INFO] Received broadcast: "OK"
[INFO] Sent "Hello"
```
The sink:
```txt
[INFO] Received broadcast: "OK"
[INFO] Received message: "Hello"
```
The broadcaster:
```txt
[INFO] Sending OK
```
## Test the example
The test script `test-ex-multiple-channels.sh` uses `ipc://` addresses in `/tmp`, a new session and
`--control static`. It starts the sink first, waits 1 s, and then starts the sampler and the broadcaster.
The sampler and the sink stop after one iteration (`--max-iterations 1`). Then the script stops the
broadcaster with `SIGINT`.
The CMake file of the example sets `TRANSPORT zeromq`. Thus CTest has only one test,
`Example.multiple-channels.zeromq`. The test exists if you configure with `-DBUILD_TESTING=ON`.
```sh
cd build
ctest -R '^Example\.multiple-channels\.' --output-on-failure
```
## Things to try
- Start the broadcaster some seconds after the other devices. The sampler and the sink exchange data
before the first broadcast arrives.
- Stop the broadcaster. The data on the channel `data` continues.
- Send another text: start the sampler with `--text "Hi"`.
- Stop after three iterations: add `--max-iterations 3` to the commands of the sampler and the sink.
## Related pages
- [Poll several channels](/guides/poll-channels/): the `Poller` interface in detail.
- [Receive data with callbacks or loops](/guides/receive-data/): `OnData()`, `ConditionalRun()` and `Run()`.
- [Channels and sockets](/concepts/channels/): the socket types `pub` and `sub`.
- [multiple-transports: zeromq and shmem](/examples/multiple-transports/): input channels with two
transports.
- [Design a topology](/guides/design-topology/#broadcast-and-data): a data link and a broadcast link in one topology.

View File

@@ -0,0 +1,186 @@
---
title: 'multiple-transports: zeromq and shmem'
description: 'Two samplers and a sink use the shmem and the zeromq transport at the same time, with a transport for each channel.'
sidebar:
order: 7
code: [fairmq/Device.h, fairmq/Device.cxx, fairmq/Channel.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps, FileTree } from '@astrojs/starlight/components';
The multiple-transports example uses two [transports](/concepts/transports/) at the same time, in one
topology and in one device. The devices use `shmem` as their default transport, and the channel `ack` uses
`zeromq`. The example also shows [`NewMessageFor()`](/api/fair/mq/Device/#NewMessageFor), which creates a
message with the transport of a channel.
The files of the example are in
[`examples/multiple-transports`](https://github.com/FairRootGroup/FairMQ/tree/dev/examples/multiple-transports)
on GitHub.
## Topology
The start script starts all three devices with `--transport shmem`:
| Device | Channel | Type | Method | Address | Transport |
| --- | --- | --- | --- | --- | --- |
| `sampler1` | `data1` | `push` | `bind` | `tcp://127.0.0.1:5555` | `shmem` (default of the device) |
| `sampler1` | `ack` | `sub` | `bind` | `tcp://127.0.0.1:5557` | `zeromq` |
| `sampler2` | `data2` | `push` | `bind` | `tcp://127.0.0.1:5556` | `shmem` (default of the device) |
| `sink1` | `data1` | `pull` | `connect` | `tcp://127.0.0.1:5555` | `shmem` (default of the device) |
| `sink1` | `data2` | `pull` | `connect` | `tcp://127.0.0.1:5556` | `shmem` |
| `sink1` | `ack` | `pub` | `connect` | `tcp://127.0.0.1:5557` | `zeromq` |
- `--transport` sets the default transport of a device. Its default is `zeromq`.
- The channel key `transport` sets the transport of one channel. A channel without this key uses the
default transport of the device.
- The device creates its default transport and each other transport that one of its channels uses
([Device.cxx](/source/fairmq/Device.cxx/#L173-L183)).
The two ends of a channel must use the same transport. The channel `ack` must use `zeromq`, because the
`shmem` transport does not support `pub` and `sub` sockets.
## Build the example
The examples build together with FairMQ when the CMake option `BUILD_EXAMPLES` is `ON` (the default):
<FileTree>
- build/examples/multiple-transports/
- fairmq-ex-multiple-transports-sampler1
- fairmq-ex-multiple-transports-sampler2
- fairmq-ex-multiple-transports-sink
- fairmq-start-ex-multiple-transports.sh
- test-ex-multiple-transports.sh
</FileTree>
## Run the example
<Steps>
1. Go to the directory of the example in the build tree:
```sh
cd build/examples/multiple-transports
```
2. Run the start script. It opens three `xterm` windows, one for each device:
```sh
./fairmq-start-ex-multiple-transports.sh
```
</Steps>
To run the example without `xterm`, run each command in its own terminal in
`build/examples/multiple-transports`:
```sh
./fairmq-ex-multiple-transports-sampler1 --id sampler1 --severity debug --transport shmem \
--channel-config "name=data1,type=push,method=bind,address=tcp://127.0.0.1:5555" \
"name=ack,type=sub,method=bind,address=tcp://127.0.0.1:5557,transport=zeromq"
```
```sh
./fairmq-ex-multiple-transports-sampler2 --id sampler2 --severity debug --transport shmem \
--channel-config "name=data2,type=push,method=bind,address=tcp://127.0.0.1:5556"
```
```sh
./fairmq-ex-multiple-transports-sink --id sink1 --severity debug --transport shmem \
--channel-config "name=data1,type=pull,method=connect,address=tcp://127.0.0.1:5555" \
"name=data2,type=pull,method=connect,address=tcp://127.0.0.1:5556,transport=shmem" \
"name=ack,type=pub,method=connect,address=tcp://127.0.0.1:5557,transport=zeromq"
```
The three devices use the session `default`, because the commands do not set `--session`.
## The samplers
<Snippet file="examples/multiple-transports/sampler1.cxx" start="bool ConditionalRun()" />
`NewMessageFor("data1", 0, 1000000)` creates a message of 1000000 bytes with the transport of the
sub-channel `data1[0]`. Here this is `shmem`. The sampler sends as fast as it can, because it does not wait
and the start script does not set `--rate`.
<Snippet file="examples/multiple-transports/sampler1.cxx" start="void ListenForAcks()" />
[`PreRun()`](/api/fair/mq/Device/#PreRun) starts a thread that runs `ListenForAcks()`, and
[`PostRun()`](/api/fair/mq/Device/#PostRun) waits for the end of this thread. The thread receives the
acknowledgements on the channel `ack`, with empty `zeromq` messages from `NewMessageFor("ack", 0)`. A new
state interrupts `Receive()`, and `Receive()` then returns a negative value. Thus the loop ends when the
device leaves `RUNNING`. For the rules of this pattern, see
[One thread for each channel](/concepts/threads/#one-thread-for-each-channel).
`sampler2` sends messages of 1000 bytes on `data2` with `NewMessage(1000)`. `NewMessage()` uses the default
transport of the device. This is also the transport of `data2`.
## The sink
<Snippet file="examples/multiple-transports/sink.cxx" start="Sink()" />
<Snippet file="examples/multiple-transports/sink.cxx" start="bool HandleData1" />
For each message on `data1`, the sink sends an empty `zeromq` message on `ack`. If `Send()` fails, the
handler throws an exception. With the channels of the start script, the device then goes to the state
`ERROR`. If the input channels use two transports, the handler runs in a separate thread, and the exception
ends the process ([Device.cxx](/source/fairmq/Device.cxx/#L558-L561)). With `--max-iterations`, the sink
leaves `RUNNING` after it got this number of messages on both data channels.
### Messages and channels with different transports
If the transport of a message is not the transport of the channel, `Send()` converts the message. It creates
a new message of the channel transport for the same data
([Channel.h](/source/fairmq/Channel.h/#L421-L438)). If the channel uses `shmem`, this step copies the data
into shared memory. `NewMessageFor()` creates the message with the transport of the channel, so `Send()`
does not convert it.
## Output
The start script does not set `rateLogging`, so each channel uses the default `1`. Each second, each device
logs one line for each sub-channel: the messages per second and the MB per second, in and out. For example,
the sink logs lines of this form, without the time:
```txt
[INFO] data1[0]: in: <messages per second> (<MB per second> MB) out: <messages per second> (<MB per second> MB)
```
With `--severity debug`, the devices also log their transports, for example `Adding 'zeromq' transport`.
When `sampler1` leaves `RUNNING`, it logs the number of acknowledgements: `Acknowledged <n> messages`.
## Test the example
The test script `test-ex-multiple-transports.sh` uses `ipc://` addresses in `/tmp`, a new session and
`--control static`. All devices stop after one message (`--max-iterations 1`). To write a script of this
type for your own devices, see [Write the test script](/guides/test-devices/#write-the-test-script).
The test uses `zeromq` for `data2`: it starts `sampler2` with `--transport zeromq`, and the sink sets
`transport=zeromq` on `data2`. Thus the input channels of the sink use two transports. In this case, the
device polls each transport in its own thread ([Device.cxx](/source/fairmq/Device.cxx/#L509-L523)).
The CMake file of the example sets `NO_TRANSPORT`, so CTest runs the script only once, without a transport
argument. The name of this test is `Example.multiple-transports.`, with a dot at the end, and its timeout is
30 s. The test exists if you configure with `-DBUILD_TESTING=ON`.
```sh
cd build
ctest -R '^Example\.multiple-transports' --output-on-failure
```
## Things to try
- Use `zeromq` for `data2`, as the test does. Start `sampler2` with `--transport zeromq`, and set
`transport=zeromq` on `data2` of the sink.
- Remove `transport=zeromq` from the channel `ack` of the sink. The sink then goes to the state `ERROR`,
because the `shmem` transport cannot create a `pub` socket.
- Hide the rate lines: add `rateLogging=0` to each channel configuration.
- Stop after 1000 messages: add `--max-iterations 1000` to all three commands. The devices then wait in
the state `READY`.
## Related pages
- [Use several transports](/guides/several-transports/): configure the transport of each channel.
- [Transports](/concepts/transports/): `zeromq` and `shmem` compared.
- [How shared memory works](/shmem/how-it-works/): what the `shmem` transport does with a message.
- [multiple-channels: data and broadcast](/examples/multiple-channels/): devices with several channels.

View File

@@ -0,0 +1,186 @@
---
title: 'n-m: n senders to m receivers'
description: 'Three senders send each timeframe to one of four receivers, and the receiver collects the parts of all senders; with push/pull or pair channels.'
sidebar:
order: 13
code: [fairmq/Device.h, fairmq/Parts.h, fairmq/Channel.h, fairmq/Device.cxx]
---
import Snippet from '../../../components/Snippet.astro';
import { FileTree } from '@astrojs/starlight/components';
In this example, three senders and four receivers exchange timeframes. A synchronizer gives each timeframe an id. Each sender sends its part of the timeframe to the receiver that the id selects, and that receiver collects the parts of all senders.
The code is in [`examples/n-m`](https://github.com/FairRootGroup/FairMQ/tree/dev/examples/n-m). The example shows how to:
- send one message to all senders on a `pub`/`sub` [channel](/concepts/channels/),
- select the [sub-channel](/concepts/channels/) for each message with the index argument of `Send()`,
- send without a wait (timeout 0 ms),
- collect the [parts](/concepts/messages/) of one timeframe from several senders,
- connect n senders to m receivers with `push`/`pull` channels or with `pair` channels.
## Topology
### Push and pull
`fairmq-start-ex-n-m.sh` starts one synchronizer, three senders and four receivers:
| Device | Channel | Type | Method | Address |
| --- | --- | --- | --- | --- |
| `Sync` | `sync` | `pub` | `bind` | `tcp://localhost:8010` |
| `Sender1`, `Sender2`, `Sender3` | `sync` | `sub` | `connect` | `tcp://localhost:8010` |
| | `data` | `push` | `connect` | `tcp://localhost:8021`, `tcp://localhost:8022`, `tcp://localhost:8023`, `tcp://localhost:8024` |
| `Receiver1` | `data` | `pull` | `bind` | `tcp://localhost:8021` |
| `Receiver2` | `data` | `pull` | `bind` | `tcp://localhost:8022` |
| `Receiver3` | `data` | `pull` | `bind` | `tcp://localhost:8023` |
| `Receiver4` | `data` | `pull` | `bind` | `tcp://localhost:8024` |
The `data` channel of a sender has four sub-channels. Sub-channel 0 connects to `Receiver1`, sub-channel 3 to `Receiver4`.
The devices get these options:
- `Sync`: `--rate 100`.
- `Sender1`, `Sender2`, `Sender3`: `--sender-index 0`, `1` or `2`, `--subtimeframe-size 1000000` and `--num-receivers 4`.
- The receivers: `--num-senders 3`.
### Pair
`fairmq-start-ex-n-m-pair.sh` starts the same devices with the same options. The `data` channels are `pair` channels, and each sub-channel connects one sender to one receiver:
| Device | Channel | Type | Method | Ports of the sub-channels |
| --- | --- | --- | --- | --- |
| `Sender1` | `data` | `pair` | `connect` | 8021, 8022, 8023, 8024 |
| `Sender2` | `data` | `pair` | `connect` | 8031, 8032, 8033, 8034 |
| `Sender3` | `data` | `pair` | `connect` | 8041, 8042, 8043, 8044 |
| `Receiver1` | `data` | `pair` | `bind` | 8021, 8031, 8041 |
| `Receiver2` | `data` | `pair` | `bind` | 8022, 8032, 8042 |
| `Receiver3` | `data` | `pair` | `bind` | 8023, 8033, 8043 |
| `Receiver4` | `data` | `pair` | `bind` | 8024, 8034, 8044 |
All addresses are `tcp://localhost:<port>`. The `sync` channels are the same as in the push and pull topology.
### DDS
`fairmq-start-ex-n-m-dds.sh` and `fairmq-start-ex-n-m-pair-dds.sh` start the devices with DDS. They use the topology files `ex-n-m-topology.xml` and `ex-n-m-pair-topology.xml`. The channels have no addresses, and each task loads the DDS plugin with `-P dds`. The files set the variables `numSenders` to 3 and `numReceivers` to 4. The table shows these values. DDS starts the task of a group `n` times and replaces `%taskIndex%` with the index of the task.
| Task | Instances | Channel | Type | Method | Options |
| --- | --- | --- | --- | --- | --- |
| `Synchronizer` | 1 | `sync` | `pub` | `bind` | `--id sync`, `--rate 100` |
| `Sender` | 3 (group `Senders`) | `sync` | `sub` | `connect` | `--id sender%taskIndex%`, `--num-receivers 4` |
| | | `data` | `push` or `pair` | `connect` | `numSockets=4` |
| `Receiver` | 4 (group `Receivers`) | `data` | `pull` or `pair` | `bind` | `--id receiver%taskIndex%`, `--num-senders 3`, `--max-timeframes 10` |
In the pair topology, the `data` channel of a receiver has `numSockets=3`. Each sender also gets `--dds-i data:%taskIndex%`. With this option, the DDS plugin of FairMQ v1.4.56 took address number `%taskIndex%` from the addresses that each receiver published for `data`.
The topology files give the senders `--timeframe-size 100000`. The sender has no such option. The device logs it as an unregistered option on the severity `debug` and ignores it. Thus the senders use the default `--subtimeframe-size` of 1000 bytes. The files also give no `--sender-index`, so all senders use the index 0.
## Requirements
- `fairmq-start-ex-n-m.sh` and `fairmq-start-ex-n-m-pair.sh` open one `xterm` window for each device. `xterm` must be installed. These scripts do not need DDS.
- The two DDS scripts need DDS, a DDS plugin for FairMQ and `fairmq-dds-command-ui`. DDS is not part of FairMQ. FairMQ v1.5.0 and later do not contain the plugin and the tool. See [dds: run with DDS](/examples/dds/#requirements).
## Build and run
The examples build when the CMake option `BUILD_EXAMPLES` is `ON` (the default). CMake writes these files to the build directory:
<FileTree>
- build/examples/n-m/
- fairmq-ex-n-m-synchronizer
- fairmq-ex-n-m-sender
- fairmq-ex-n-m-receiver
- fairmq-start-ex-n-m.sh
- fairmq-start-ex-n-m-pair.sh
- fairmq-start-ex-n-m-dds.sh
- fairmq-start-ex-n-m-pair-dds.sh
- fairmq-ex-n-m-env.sh
- ex-n-m-topology.xml
- ex-n-m-pair-topology.xml
</FileTree>
The scripts take no arguments:
```sh
cd build/examples/n-m
./fairmq-start-ex-n-m.sh
./fairmq-start-ex-n-m-pair.sh
```
The devices use the interactive controller. Type `q` in a window to end its device.
The DDS scripts call `dds-submit -r localhost --slots 8`. They request the transitions with `fairmq-dds-command-ui`, in the same sequence as the [dds example](/examples/dds/). They wait until all receivers go from `RUNNING` to `READY`, and then they stop all devices.
The install step copies the executables and the scripts to `bin`, and the topology files to `share/fairmq` in the install prefix.
## The code
### Synchronizer: one id for each timeframe
[`ConditionalRun()`](/api/fair/mq/Device/#ConditionalRun) sends a 2-byte id on the `pub` channel `sync`. All senders receive it. With `--rate 100`, the synchronizer sends at most 100 ids per second.
<Snippet file="examples/n-m/synchronizer.cxx" start="bool ConditionalRun() override" />
After the id 65533, the next id is 0. If a send fails, `ConditionalRun()` returns `false`, and the device goes to `READY`.
### Sender: select the receiver
The parts of a timeframe start with this header:
<Snippet file="examples/n-m/Header.h" start="struct Header" />
The sender has its own `Run()` loop. It receives an id from `sync` with [`Channel::Receive()`](/api/fair/mq/Channel/#Receive). Then it sends a multipart message: the header, and a message of `--subtimeframe-size` bytes (default 1000).
<Snippet file="examples/n-m/sender.cxx" start="void Run() override" />
- The id modulo `--num-receivers` selects the sub-channel of `data`. Thus all senders send the parts of one id to the same receiver.
- The last argument of [`Send()`](/api/fair/mq/Device/#Send-2) is a timeout of 0 ms, so `Send()` does not wait. If the queue of the sub-channel is full, `Send()` returns a negative value. The sender then logs `Failed to queue Subtimeframe #<id> to Receiver[<n>]` on the severity `debug` and drops the parts.
- `--num-receivers` has no default. The device does not start without it.
### Receiver: collect the parts
The receiver registers `HandleData()` for the multipart messages of `data` with [`OnData()`](/api/fair/mq/Device/#OnData-3). It moves part 1 into a buffer for the id of the header. When the buffer has `--num-senders` parts, the timeframe is complete.
<Snippet file="examples/n-m/receiver.cxx" start="bool HandleData(fair::mq::Parts& parts, int /* index */)" />
- With `--max-timeframes` greater than 0, the receiver leaves `RUNNING` after that number of complete timeframes. The default is 0 (no limit).
- `--num-senders` has no default. The device does not start without it.
- In the pair topology, the `data` channel of a receiver has three sub-channels. The device then polls all sub-channels and calls `HandleData()` with the index of the sub-channel. See [Poll several channels](/guides/poll-channels/).
`DiscardIncompleteTimeframes()` removes the timeframes that are older than `--buffer-timeout` (default 1000 ms). The example never calls this function. Thus `--buffer-timeout` has no effect, and an incomplete timeframe stays in the buffer.
## Output
Each receiver logs each complete timeframe:
```txt
Successfully completed timeframe #<id>
```
With `--max-timeframes`, the receiver logs this line when it leaves `RUNNING`:
```txt
Reached configured maximum number of timeframes (10). Exiting RUNNING state.
```
The synchronizer and the senders log no lines of their own on the severity `info`. In `RUNNING`, each device logs the message rate and the data rate of each sub-channel every second, in the form `data[0]: in: <rate> (<rate> MB) out: <rate> (<rate> MB)`. The channel property `rateLogging` sets the interval in seconds (default 1, `0` turns it off).
## Test
The example has no test. In `CMakeLists.txt`, the tests `Example.N-M.localhost` and `Example.N-M-pair.localhost` are comments. They run the two DDS scripts with a timeout of 15 s and expect the output `Example successful`.
## Things to try
- Add `--max-timeframes 10` to the receivers in `fairmq-start-ex-n-m.sh`. Each receiver then goes to `READY` after 10 complete timeframes.
- End one sender with `q`. The receivers then get only two parts for each id, so no timeframe is complete. The buffers of the receivers grow, because the example does not discard incomplete timeframes.
- Add `--severity debug` to the senders and end one receiver with `q`. When the queue of that sub-channel is full, the senders log `Failed to queue Subtimeframe #<id> to Receiver[<n>]`.
- Change `--subtimeframe-size` or the `--rate` of the synchronizer, and look at the rates of the `data` sub-channels.
## Related pages
- [Channels and sockets](/concepts/channels/)
- [Messages and multipart](/concepts/messages/)
- [Poll several channels](/guides/poll-channels/)
- [dds: run with DDS](/examples/dds/)
- [Errors and timeouts](/guides/errors-timeouts/)
- [Design a topology](/guides/design-topology/#n-senders-to-m-receivers)

View File

@@ -0,0 +1,144 @@
---
title: 'qc: quality control on demand'
description: 'A dispatcher forwards data from a sampler to a sink, and also to a QC task when a controller sets the property qc to active; the start script needs DDS.'
sidebar:
order: 14
code: [fairmq/ProgOptions.h, fairmq/Device.h, fairmq/Message.h]
---
import Snippet from '../../../components/Snippet.astro';
import { FileTree } from '@astrojs/starlight/components';
This example sends data from a sampler through a dispatcher to a sink. When a controller sets the [property](/concepts/configuration/) `qc` of the dispatcher to `active`, the dispatcher also sends the data to a QC task. In this example, the QC task only logs that it received data.
:::caution
FairMQ alone cannot run the start script of this example. It needs DDS, a DDS plugin for FairMQ and the tool `fairmq-dds-command-ui`. DDS is not part of FairMQ. FairMQ v1.5.0 and later do not contain the plugin and the tool. See [dds: run with DDS](/examples/dds/#requirements).
:::
The code is in [`examples/qc`](https://github.com/FairRootGroup/FairMQ/tree/dev/examples/qc). The example shows how to:
- subscribe to the changes of a property with `Subscribe()`,
- change the behavior of a running device through a property,
- start the devices of a topology in a specified order.
## Topology
The topology file `ex-qc-topology.xml` lists each task once in `main`, so DDS starts one instance of each task. Each task loads the DDS plugin with `-P dds`. No channel has an address.
| Task | Executable | Channel | Type | Method | Address |
| --- | --- | --- | --- | --- | --- |
| `Sampler` | `fairmq-ex-qc-sampler` | `data1` | `push` | `bind` | not set |
| `QCDispatcher` | `fairmq-ex-qc-dispatcher` | `data1` | `pull` | `connect` | not set |
| | | `data2` | `push` | `connect` | not set |
| | | `qc` | `push` | `connect` | not set |
| `QCTask` | `fairmq-ex-qc-task` | `qc` | `pull` | `bind` | not set |
| `Sink` | `fairmq-ex-qc-sink` | `data2` | `pull` | `bind` | not set |
The tasks with a binding channel have write access to the properties `fmqchan_data1`, `fmqchan_qc` and `fmqchan_data2`. The dispatcher has read access to all three. The [dds example](/examples/dds/) explains how the DDS plugin of FairMQ v1.4.56 used these properties.
The file gives `--max-iterations 1000` to the sampler and the sink. These devices have no such option. They log it as an unregistered option on the severity `debug` and ignore it.
## Requirements
The start script needs DDS, a DDS plugin for FairMQ and `fairmq-dds-command-ui`. The [dds example](/examples/dds/#requirements) describes these requirements and the error when the plugin is missing.
The four devices build with FairMQ alone. Without DDS, you can start them by hand. See [Things to try](#things-to-try).
## Build and run
The examples build when the CMake option `BUILD_EXAMPLES` is `ON` (the default). CMake writes these files to the build directory:
<FileTree>
- build/examples/qc/
- fairmq-ex-qc-sampler
- fairmq-ex-qc-dispatcher
- fairmq-ex-qc-task
- fairmq-ex-qc-sink
- fairmq-start-ex-qc.sh
- fairmq-ex-qc-env.sh
- ex-qc-topology.xml
</FileTree>
`fairmq-ex-qc-dispatcher` comes from `qCDispatcher.cxx`, and `fairmq-ex-qc-task` from `qCTask.cxx`. The install step copies the executables and the scripts to `bin`, and `ex-qc-topology.xml` to `share/fairmq` in the install prefix.
The start script takes no arguments:
```sh
cd build/examples/qc
./fairmq-start-ex-qc.sh
```
The script does the same steps as the start script of the [dds example](/examples/dds/), with `dds-submit -r localhost --slots 4`. It requests the transitions in a specified order:
<Snippet file="examples/qc/fairmq-start-ex-qc.sh.in" start="fairmq-dds-command-ui -c j" end='fairmq-dds-command-ui -w "RUNNING->READY"' />
1. All devices go to `READY`.
2. The sampler, the dispatcher and the sink go to `RUNNING`.
3. The script sets the property `qc` of the dispatcher to `active` (`-c p`).
4. The QC task goes to `RUNNING`.
5. The script waits until the QC task goes from `RUNNING` to `READY`. Then it stops all devices and prints `Example successful :)`.
For the options of `fairmq-dds-command-ui`, see [Request the transitions](/examples/dds/#request-the-transitions).
## The code
### Dispatcher: subscribe to a property
In `InitTask()`, the dispatcher subscribes to the changes of all properties of the type `std::string` with [`Subscribe()`](/api/fair/mq/ProgOptions/#Subscribe). The callback looks only at the key `qc`. The value `active` turns the sends to `qc` on, and `inactive` turns them off.
<Snippet file="examples/qc/qCDispatcher.cxx" start="void InitTask() override" />
The callback runs in the thread that changes the property. Thus `fDoQC` is a `std::atomic<bool>`. [`ResetTask()`](/api/fair/mq/Device/#ResetTask) ends the subscription with [`Unsubscribe()`](/api/fair/mq/ProgOptions/#Unsubscribe).
### Dispatcher: forward the data
The dispatcher registers `HandleData()` for `data1` with [`OnData()`](/api/fair/mq/Device/#OnData):
<Snippet file="examples/qc/qCDispatcher.cxx" start="bool HandleData" />
When `fDoQC` is `true`, the dispatcher makes a copy of the message with [`Copy()`](/api/fair/mq/Message/#Copy). But it sends `msg` to `qc`, and then the same `msg` to `data2`. The code does not use `msgCopy`. On the zeromq transport, the first `Send()` empties `msg`, so the sink gets empty messages while `qc` is `active`.
### Sampler, QC task and sink
- The sampler sends a message of 1000 bytes on `data1` in each `ConditionalRun()` call. Then it waits 10 ms. It has no limit.
- The QC task registers a lambda for `qc` with [`OnData()`](/api/fair/mq/Device/#OnData-2). The lambda logs `received data` and returns `false`. Thus the QC task goes to `READY` after its first message.
- The sink registers `HandleData()` for `data2`. The function does nothing with the messages and returns `true`.
## Output
The QC task logs one line when it gets the first message on `qc`:
```txt
received data
```
The sampler, the dispatcher and the sink log no lines of their own.
## Test
The example has no test. In `CMakeLists.txt`, the test `Example.QC.localhost` is a comment. It runs `fairmq-start-ex-qc.sh localhost` with a timeout of 15 s and expects the output `Example successful`.
## Things to try
- Send `msgCopy` to `qc` in `qCDispatcher.cxx`. Then the QC task and the sink both get the data. The built-in multiplier uses the same method, see [builtin-devices](/examples/builtin-devices/).
- Start the devices without DDS. Remove `-P dds` and give each channel an address. Start each device in its own terminal in `build/examples/qc`:
```sh
./fairmq-ex-qc-sampler --id sampler1 --channel-config name=data1,type=push,method=bind,address=tcp://127.0.0.1:5555
./fairmq-ex-qc-task --id qctask1 --channel-config name=qc,type=pull,method=bind,address=tcp://127.0.0.1:5556
./fairmq-ex-qc-sink --id sink1 --channel-config name=data2,type=pull,method=bind,address=tcp://127.0.0.1:5557
./fairmq-ex-qc-dispatcher --id dispatcher1 --channel-config name=data1,type=pull,method=connect,address=tcp://127.0.0.1:5555 name=data2,type=push,method=connect,address=tcp://127.0.0.1:5557 name=qc,type=push,method=connect,address=tcp://127.0.0.1:5556
```
No controller sets `qc` here, so the dispatcher sends nothing to the QC task.
- Set the property from code. When the dispatcher is in `READY` or `RUNNING`, a plugin can call [`SetProperty()`](/api/fair/mq/Plugin/#SetProperty) as `SetProperty<std::string>("qc", "active")`. The value must be a `std::string`, because the dispatcher subscribes to `std::string` properties. See [Write a plugin](/guides/write-plugin/) and [custom-controller](/examples/custom-controller/).
## Related pages
- [Configuration and properties](/concepts/configuration/)
- [dds: run with DDS](/examples/dds/)
- [Plugins and control](/concepts/plugins/)
- [builtin-devices: a topology of built-in devices](/examples/builtin-devices/)

View File

@@ -0,0 +1,138 @@
---
title: 'readout: a readout chain'
description: 'A readout node passes region messages over shmem channels and sends them to a receiver over zeromq, with or without a processor.'
sidebar:
order: 9
code: [fairmq/UnmanagedRegion.h, fairmq/Device.h, fairmq/Channel.h, fairmq/shmem/Message.h]
---
import Snippet from '../../../components/Snippet.astro';
import { FileTree } from '@astrojs/starlight/components';
This example models a readout node and a processing node. On the readout node, messages from an [unmanaged region](/shmem/regions/) go through several devices on shmem channels without a copy. A sender forwards the data to the processing node on a zeromq channel.
The code is in [`examples/readout`](https://github.com/FairRootGroup/FairMQ/tree/dev/examples/readout). The example shows how to:
- create a region in one device and send messages from it,
- forward region messages through other devices,
- send a shmem message on a zeromq channel ([several transports](/guides/several-transports/) in one device),
- make new data in the managed segment from a region message, and release the region block.
## Topology
The devices do not set `--transport`, so the default transport of each device is `zeromq`. Each channel selects its transport with the [channel property](/reference/channel-properties/) `transport`. All channels are `pair` channels.
`fairmq-start-ex-readout.sh` starts four devices: readout, builder, sender and receiver.
| Device | Channel | Type | Method | Address | Transport |
| --- | --- | --- | --- | --- | --- |
| `readout1` | `rb` | `pair` | `bind` | `tcp://localhost:7777` | `shmem` |
| `builder1` | `rb` | `pair` | `connect` | `tcp://localhost:7777` | `shmem` |
| | `bs` | `pair` | `connect` | `tcp://localhost:7778` | `shmem` |
| `sender1` | `bs` | `pair` | `bind` | `tcp://localhost:7778` | `shmem` |
| | `sr` | `pair` | `connect` | `tcp://localhost:7779` | `zeromq` |
| `receiver1` | `sr` | `pair` | `bind` | `tcp://localhost:7779` | `zeromq` |
`fairmq-start-ex-readout-processing.sh` adds a processor between the builder and the sender. The builder gets `--output-name bp` and the sender gets `--input-name ps`.
| Device | Channel | Type | Method | Address | Transport |
| --- | --- | --- | --- | --- | --- |
| `readout1` | `rb` | `pair` | `bind` | `tcp://localhost:7777` | `shmem` |
| `builder1` | `rb` | `pair` | `connect` | `tcp://localhost:7777` | `shmem` |
| | `bp` | `pair` | `connect` | `tcp://localhost:7778` | `shmem` |
| `processor1` | `bp` | `pair` | `bind` | `tcp://localhost:7778` | `shmem` |
| | `ps` | `pair` | `connect` | `tcp://localhost:7779` | `shmem` |
| `sender1` | `ps` | `pair` | `bind` | `tcp://localhost:7779` | `shmem` |
| | `sr` | `pair` | `connect` | `tcp://localhost:7780` | `zeromq` |
| `receiver1` | `sr` | `pair` | `bind` | `tcp://localhost:7780` | `zeromq` |
## Requirements
The start scripts open one `xterm` window for each device. `xterm` must be installed.
## Build and run
The examples build when the CMake option `BUILD_EXAMPLES` is `ON` (the default). The executables and the start scripts are in the build directory:
<FileTree>
- build/examples/readout/
- fairmq-ex-readout-readout
- fairmq-ex-readout-builder
- fairmq-ex-readout-processor
- fairmq-ex-readout-sender
- fairmq-ex-readout-receiver
- fairmq-start-ex-readout.sh
- fairmq-start-ex-readout-processing.sh
</FileTree>
Both scripts take one optional argument: the message size in bytes (default `1000000`).
```sh
cd build/examples/readout
./fairmq-start-ex-readout.sh
./fairmq-start-ex-readout-processing.sh 4096
```
## The code
### Readout: create the region and send
The readout device creates a region of 10000000 bytes with the transport of the channel `rb`. It gives no [`RegionConfig`](/api/fair/mq/RegionConfig/), so the region uses the defaults. The callback counts the acknowledgements.
<Snippet file="examples/readout/readout.cxx" start="void InitTask() override" />
[`ConditionalRun()`](/api/fair/mq/Device/#ConditionalRun) sends one message for each call. The message points to the start of the region and has the size `--msg-size`.
<Snippet file="examples/readout/readout.cxx" start="bool ConditionalRun() override" />
In `ResetTask()`, the readout device waits 500 ms once if messages are not acknowledged. Then it destroys the region.
### Builder and sender: forward the messages
The builder and the sender register a data callback with [`OnData()`](/api/fair/mq/Device/#OnData) and send each message on. The builder forwards from `rb` to the channel of `--output-name` (default `bs`):
<Snippet file="examples/readout/builder.cxx" start="bool HandleData" />
The sender forwards from the channel of `--input-name` (default `bs`) to `sr`. The message is a shmem message, but `sr` is a zeromq channel. [`Channel::Send()`](/api/fair/mq/Channel/#Send) compares the transports. If they differ, the channel puts the data of the message into a new message of its own transport. It does not copy the data. The new message deletes the original message when the zeromq transport releases the data. See [`Channel.h`](/source/fairmq/Channel.h/#L421-L438).
Thus the readout device gets the acknowledgement for a block after the zeromq transport releases the data.
### Processor: make new data
The processor receives a region message and makes a new message of the same size for the channel `ps`. It does not copy the data. On the shmem transport, this message is in the managed segment, not in the region.
<Snippet file="examples/readout/processor.cxx" start="bool HandleData" />
The device destroys the received message when `HandleData()` returns (see [`Device.cxx`](/source/fairmq/Device.cxx/#L564-L573)). Then the transport releases the region block, and the readout device gets the acknowledgement. The new message is not part of the region.
## Output
The devices log little. With `--max-iterations` greater than 0, the readout device and the receiver leave the state `RUNNING` after that number of messages. The readout device logs:
```txt
Configured maximum number of iterations reached. Leaving RUNNING state.
```
The receiver logs `Configured max number of iterations reached. Leaving RUNNING state.` With `--severity debug` and `--max-iterations`, the readout device also logs each bulk callback as `Received <n> acks`. When messages are not acknowledged in `ResetTask()`, it logs `waiting for all acknowledgements... (<n>)` and `done, still unacked: <n>` on the severity `debug`.
## Test
The example has no test. Its `CMakeLists.txt` uses `NO_TEST`.
## Things to try
- Add `--max-iterations 1000 --severity debug` to the readout device in the start script. The log then shows the acknowledgements.
- Limit the rate of the readout device with `--rate 100` (in Hz). The option controls the `ConditionalRun()` loop.
- Run the receiver on a second computer. Change the address of `sr` in the sender and in the receiver to an address of that computer.
- Look at the segment and the region with [fairmq-shmmonitor](/tools/shmmonitor/) while the devices run.
## Related pages
- [Unmanaged regions](/shmem/regions/)
- [How shared memory works](/shmem/how-it-works/)
- [Use several transports](/guides/several-transports/)
- [region: unmanaged regions](/examples/region/): acknowledgements, region events and shared copies.
- [Transports](/concepts/transports/)
- [Design a topology](/guides/design-topology/#a-readout-chain)

View File

@@ -0,0 +1,207 @@
---
title: 'region: unmanaged regions'
description: 'A sampler sends messages from an unmanaged region and counts the acknowledgements; a larger topology shares the region data with four sinks.'
sidebar:
order: 8
code: [fairmq/UnmanagedRegion.h, fairmq/Device.h, fairmq/TransportFactory.h, fairmq/shmem/UnmanagedRegion.h, fairmq/shmem/Message.h]
---
import Snippet from '../../../components/Snippet.astro';
import { FileTree, Steps } from '@astrojs/starlight/components';
The sampler of this example creates an [unmanaged region](/shmem/regions/) and sends messages that point into it. The transport tells the sampler, through a callback, when the receivers no longer use a message. The sampler counts these acknowledgements.
The code is in [`examples/region`](https://github.com/FairRootGroup/FairMQ/tree/dev/examples/region). The example shows how to:
- create a region with [`NewUnmanagedRegionFor()`](/api/fair/mq/Device/#NewUnmanagedRegionFor) and a [`RegionConfig`](/api/fair/mq/RegionConfig/),
- make messages in the region with [`NewMessageFor()`](/api/fair/mq/Device/#NewMessageFor) and send 64 of them as one multipart message,
- receive the acknowledgements in a bulk callback,
- log region events with [`SubscribeToRegionEvents()`](/api/fair/mq/TransportFactory/#SubscribeToRegionEvents),
- share region messages between two outputs with [`Copy()`](/api/fair/mq/Message/#Copy),
- use a region that another process created.
## Topology
The example has three start scripts. `fairmq-start-ex-region.sh` connects one sampler to one sink:
| Device | Channel | Type | Method | Address |
| --- | --- | --- | --- | --- |
| `sampler1` | `data` | `push` | `bind` | `tcp://127.0.0.1:7777` |
| `sink1` | `data` | `pull` | `connect` | `tcp://127.0.0.1:7777` |
The script also sets `sndKernelSize=212992` on the channel of the sampler and `rcvKernelSize=212992` on the channel of the sink.
`fairmq-start-ex-region-advanced.sh` starts one sampler, two processors and four sinks. The `push` channel of the sampler distributes the messages over the two processors. Each processor sends each part to two sinks. The sampler and the sinks select their channel with `--chan-name`.
| Device | `--shm-segment-id` | Channel | Type | Method | Address |
| --- | --- | --- | --- | --- | --- |
| `sampler1` | `0` (default) | `data1` | `push` | `bind` | `tcp://127.0.0.1:7777` |
| `processor1` | `1` | `data1` | `pull` | `connect` | `tcp://127.0.0.1:7777` |
| | | `data2` | `push` | `bind` | `tcp://127.0.0.1:7778` |
| | | `data3` | `push` | `bind` | `tcp://127.0.0.1:7779` |
| `processor2` | `2` | `data1` | `pull` | `connect` | `tcp://127.0.0.1:7777` |
| | | `data2` | `push` | `bind` | `tcp://127.0.0.1:7788` |
| | | `data3` | `push` | `bind` | `tcp://127.0.0.1:7789` |
| `sink1_1` | `1` | `data2` | `pull` | `connect` | `tcp://127.0.0.1:7778` |
| `sink1_2` | `1` | `data3` | `pull` | `connect` | `tcp://127.0.0.1:7779` |
| `sink2_1` | `2` | `data2` | `pull` | `connect` | `tcp://127.0.0.1:7788` |
| `sink2_2` | `2` | `data3` | `pull` | `connect` | `tcp://127.0.0.1:7789` |
`fairmq-start-ex-region-advanced-external.sh` starts the same topology with these changes:
- All devices use `--shmid 1`, `--shm-no-cleanup true` and `--shm-monitor false`.
- The sampler uses `--external-region true` and `--rc-segment-size 200000000`.
With `--external-region true`, the sampler uses a region that another process created. See [Use a region of another process](#use-a-region-of-another-process).
## Requirements
- The start scripts open one `xterm` window for each device. `xterm` must be installed.
- The advanced scripts use options of the shmem transport (`--shm-segment-id`, `--shmid`). Use them with the shmem transport, the default of the scripts.
- `fairmq-ex-region-keep-alive` uses the shared memory classes of FairMQ directly. It works only with shared memory.
## Build and run
The examples build when the CMake option `BUILD_EXAMPLES` is `ON` (the default). The executables and the start scripts are in the build directory:
<FileTree>
- build/examples/region/
- fairmq-ex-region-sampler
- fairmq-ex-region-processor
- fairmq-ex-region-sink
- fairmq-ex-region-keep-alive
- fairmq-start-ex-region.sh
- fairmq-start-ex-region-advanced.sh
- fairmq-start-ex-region-advanced-external.sh
- test-ex-region.sh
</FileTree>
Each start script takes two arguments: the transport (default `shmem`) and the size of one part in bytes (default `1000000`).
```sh
cd build/examples/region
./fairmq-start-ex-region.sh
./fairmq-start-ex-region.sh zeromq 4096
./fairmq-start-ex-region-advanced.sh
```
The scripts set `FAIRMQ_PATH` to `build/fairmq`. A device with `--shm-monitor true` finds `fairmq-shmmonitor` there. The install step copies the executables and the scripts to `bin` in the install prefix. The installed scripts start the installed executables.
## The code
### Create the region
The sampler creates the region in `InitTask()`. The region is 10000000 bytes. The sampler creates it with the transport of sub-channel 0 of its output channel.
<Snippet file="examples/region/sampler.cxx" start="fair::mq::RegionConfig regionCfg;" end="^\s+\)\);$" />
- The lambda is the bulk callback. The transport calls it with the blocks that it no longer needs. Each [`RegionBlock`](/api/fair/mq/RegionBlock/) has the pointer, the size and the hint of one message.
- `linger` comes from `--region-linger` (default 100). On the shmem transport, the region receives outstanding acknowledgements for this time in ms when it is destroyed. The zeromq transport ignores it.
- `rcSegmentSize` comes from `--rc-segment-size` (default 10000000 in this example). It sets the size of the segment that keeps the reference counts of copied region messages.
- `lock` and `zero` lock the pages of the region in memory and fill the region with zeros. The sampler sets them only for a region that it creates itself.
### Send messages from the region
`Run()` makes 64 messages and sends them as one [`Parts`](/api/fair/mq/Parts/) object. All 64 messages point to the start of the region and have the size `--msg-size`. The counter of unacknowledged messages goes up by the number of parts.
<Snippet file="examples/region/sampler.cxx" start="while (!NewStatePending()) {" />
After the send loop, `Run()` waits until the counter is zero, or until a new state is pending. `ResetTask()` destroys the region and ends the subscription to region events.
### Log the region events
The sampler, the processor and the sink all subscribe to the region events of their transport:
<Snippet file="examples/region/sampler.cxx" start="SubscribeToRegionEvents" />
On the shmem transport, the events cover all managed segments and unmanaged regions of the [session](/shmem/sessions/). Thus the sink also logs the region of the sampler. On the zeromq transport, the events come only from the regions of the own process. There, the first event is `local_only`.
### Share a region message
The processor sends each received part to two channels. It makes both outgoing messages with `Copy()`:
<Snippet file="examples/region/processor.cxx" start="for (const auto& inPart : inParts) {" />
On the shmem transport, `Copy()` of a region message copies no data. It adds a reference count. The transport releases the block, and the sampler gets the acknowledgement, after the last copy is destroyed. See [`shmem/Message.h`](/source/fairmq/shmem/Message.h/#L273-L330) and [How shared memory works](/shmem/how-it-works/). On the zeromq transport, the copy shares the buffer of the original message.
### Keep segments and regions alive
`fairmq-ex-region-keep-alive` is not a device. At start, it removes all shared memory of the given `--shmid`. Then it creates managed segments and unmanaged regions for this `--shmid`, locks them in memory and fills them with zeros:
<Snippet file="examples/region/keep-alive.cxx" start="desc.add_options()" end="Print help" />
The program checks every 500 ms that the segments and regions are present. It stops and cleans up if one is missing. On `SIGUSR1`, it resets the content of the segments and regions. On `SIGINT` or `SIGTERM`, it removes all shared memory of the `--shmid`.
:::note
`--segments` and `--regions` need three comma-separated values for each entry, for example `1,10000000,0`. The program uses the first two values (id and size) and ignores the third. The help text of `--regions` shows only `<id>,<size>` for the first entry.
:::
## Output
The sampler, the processors and the sinks log each region event:
```txt
Region event: created: unmanaged, id: <id>, ptr: <address>, size: 10000000, flags: 0
```
With `--max-iterations` greater than 0, the sampler stops after that number of multipart messages. It also logs each bulk callback:
```txt
Configured maximum number of iterations reached. Stopping sending.
Received 64 acks
All acknowledgements received.
```
The acknowledgements can arrive in more than one callback. Then `Received <n> acks` shows more than once. If a new state is pending before all acknowledgements arrive, the sampler logs `Done, still not acknowledged: <n>` instead of the last line. With `--max-iterations`, the sink and the processor log `Configured max number of iterations reached. Leaving RUNNING state.`
## Test
`examples/region/CMakeLists.txt` adds the tests `Example.region.zeromq` and `Example.region.shmem`. Each test runs `test-ex-region.sh` with the transport as argument. The script starts one sampler and one sink with `--max-iterations 1`, `--control static` and an `ipc://` address. The timeout is 30 s. To write a script of this type for your own devices, see [Write the test script](/guides/test-devices/#write-the-test-script).
Configure with `-DBUILD_TESTING=ON` to register the tests. Then run them in the build directory:
```sh
ctest -R Example.region
```
## Things to try
- Limit the send rate of the sampler with `--sampling-rate 10` (in Hz). The default `0` sends as fast as possible.
- Start the advanced topology with `--rc-segment-size 0` on the sampler (the script has it as a comment). Then the transport keeps the reference counts of the copies in the managed segment.
- Look at the shared memory while the topology runs. Run `fairmq-shmmonitor --list-all` from `build/fairmq`. See [fairmq-shmmonitor](/tools/shmmonitor/).
### Use a region of another process
The external variant needs a region with id 1 and a size of 10000000 bytes, the size that the sampler requests. Create it with the keep-alive program:
<Steps>
1. In a terminal, start the keep-alive program in `build/examples/region`:
```sh
./fairmq-ex-region-keep-alive --shmid 1 --regions 1,10000000,0
```
2. In a second terminal, start the topology:
```sh
./fairmq-start-ex-region-advanced-external.sh
```
3. Stop the devices. Then stop the keep-alive program with `Ctrl-C`. It removes the shared memory of `--shmid 1`.
</Steps>
The opened region uses the `rcSegmentSize` of its creator. The keep-alive program creates the region with `rcSegmentSize` 0. Thus `--rc-segment-size 200000000` of the sampler has no effect, and the transport keeps the reference counts of the copies in the managed segment.
The devices of this variant use `--shm-no-cleanup true`. Thus their shared memory stays after they stop. Without the keep-alive program, remove it with `fairmq-shmmonitor --cleanup --shmid 00000001`. The shmem transport writes `--shmid 1` as the hexadecimal string `00000001`.
## Related pages
- [Unmanaged regions](/shmem/regions/): the region API and the acknowledgements in detail.
- [How shared memory works](/shmem/how-it-works/)
- [Sessions and segments](/shmem/sessions/)
- [readout: a readout chain](/examples/readout/): a region in a chain of devices.
- [Monitor and clean up](/shmem/monitor/)

View File

@@ -0,0 +1,149 @@
---
title: 'req-rep: request and reply'
description: 'A client sends a request on a req socket and waits for the reply. A server answers on a rep socket of the same channel.'
sidebar:
order: 3
code: [fairmq/Device.h, fairmq/Channel.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps, FileTree } from '@astrojs/starlight/components';
The req-rep example shows messages in two directions on one channel. The client sends a request and waits
for the reply. The server receives the request in a data handler and sends the reply on the same channel.
The files of the example are in
[`examples/req-rep`](https://github.com/FairRootGroup/FairMQ/tree/dev/examples/req-rep) on GitHub.
## Topology
| Device | Channel | Type | Method | Address |
| --- | --- | --- | --- | --- |
| `client` | `data` | `req` | `connect` | `tcp://127.0.0.1:5005` |
| `server` | `data` | `rep` | `bind` | `tcp://127.0.0.1:5005` |
A `req` socket must send and receive in turn: one request, then one reply. A `rep` socket receives a request
and sends the reply to the client of this request. The [Channels and sockets](/concepts/channels/) page
describes all socket types.
## Build the example
The examples build together with FairMQ when the CMake option `BUILD_EXAMPLES` is `ON` (the default):
<FileTree>
- build/examples/req-rep/
- fairmq-ex-req-rep-client
- fairmq-ex-req-rep-server
- fairmq-start-ex-req-rep.sh
- test-ex-req-rep.sh
</FileTree>
## Run the example
<Steps>
1. Go to the directory of the example in the build tree:
```sh
cd build/examples/req-rep
```
2. Run the start script. It opens two `xterm` windows, one for each device:
```sh
./fairmq-start-ex-req-rep.sh
```
</Steps>
To run the example without `xterm`, run each command in its own terminal in `build/examples/req-rep`:
```sh
./fairmq-ex-req-rep-client --id client \
--channel-config "name=data,type=req,method=connect,rateLogging=0,address=tcp://127.0.0.1:5005"
```
```sh
./fairmq-ex-req-rep-server --id server \
--channel-config "name=data,type=rep,method=bind,rateLogging=0,address=tcp://127.0.0.1:5005"
```
Push `q` in a terminal to stop the device in it.
## The client
<Snippet file="examples/req-rep/client.cxx" start="bool ConditionalRun()" />
- The request is a message for a new `std::string`, with a free function that deletes the string. The
[1-1 example](/examples/1-1/#the-sampler) explains this form of
[`NewMessage()`](/api/fair/mq/Device/#NewMessage).
- `NewMessage()` without arguments creates an empty message for the reply.
- [`Send()`](/api/fair/mq/Device/#Send) sends the request. Then
[`Receive()`](/api/fair/mq/Device/#Receive) waits for the reply on the same channel and puts it into
`rep`.
- The default receive timeout of a channel is `-1`. Thus `Receive()` waits until the reply arrives or the
device gets a new state. If the server ends before it replies, see
[A peer ends while the device sends or receives](/guides/errors-timeouts/#a-peer-ends-while-the-device-sends-or-receives).
- `ConditionalRun()` returns `false` if `Send()` returns `0` or less, or if `Receive()` returns a negative
value. Then the device goes to `READY`.
- After each reply, the client waits 1 s.
The client has the custom options `--text` (default `Hello`) and `--max-iterations` (default `0`, no limit).
## The server
<Snippet file="examples/req-rep/server.cxx" start="Server()" />
<Snippet file="examples/req-rep/server.cxx" start="bool HandleData" />
The server registers `HandleData()` for the channel `data` with [`OnData()`](/api/fair/mq/Device/#OnData).
The device calls the handler for each request. The handler puts the text of the request into the reply and
sends the reply with `Send()` on the same channel. The server has the option `--max-iterations`.
## Output
The listings show the severity and the message of each line, without the time. The client logs two lines
for each request:
```txt
[INFO] Sending "Hello" to server.
[INFO] Received reply from server: "Thank you for the "Hello"!"
```
The server logs two lines for each request:
```txt
[INFO] Received request from client: "Hello"
[INFO] Sending reply to client.
```
## Test the example
The test script `test-ex-req-rep.sh` starts the client and the server in the background. It uses an
`ipc://` address in `/tmp`, a new session, and `--control static`. Both devices stop after one request
(`--max-iterations 1`).
CTest runs the script once for each transport: `Example.req-rep.zeromq` and `Example.req-rep.shmem`. The
tests exist if you configure with `-DBUILD_TESTING=ON`.
```sh
cd build
ctest -R '^Example\.req-rep\.' --output-on-failure
```
## Things to try
- Send another text: start the client with `--text "Ping"`.
- Use shared memory: add `--transport shmem` to both commands.
- Stop after three requests: add `--max-iterations 3` to both commands.
- Start a second client with the same channel configuration and `--id client2`. The server receives the
requests of both clients, and each client gets its own replies.
## Related pages
- [Channels and sockets](/concepts/channels/): the socket types `req` and `rep`.
- [Receive data with callbacks or loops](/guides/receive-data/): `OnData()` and `Receive()`.
- [Handle errors and timeouts](/guides/errors-timeouts/): the return values of `Send()` and `Receive()`.
- [Transfer codes and errors](/reference/transfer-codes/): the negative return values.

View File

@@ -0,0 +1,253 @@
---
title: 'Run a benchmark'
description: 'Measure the throughput of the zeromq and shmem transports with fairmq-bsampler and fairmq-sink, and read the rate lines that the devices log.'
sidebar:
order: 10
code: [fairmq/devices/BenchmarkSampler.h, fairmq/devices/Sink.h, fairmq/Device.cxx, fairmq/shmem/Manager.h]
---
import { Steps } from '@astrojs/starlight/components';
import Snippet from '../../../components/Snippet.astro';
This guide measures the throughput between two devices on one host. `fairmq-bsampler` sends messages of a fixed size as fast as the channel accepts them. `fairmq-sink` receives the messages and discards them. Each device logs the message rate and the data rate of its channel every second. The options of the two devices are on [Built-in devices](/tools/builtin-devices/).
## Before you start
- Use an optimized build of FairMQ. If you give no `CMAKE_BUILD_TYPE`, FairMQ uses `RelWithDebInfo`.
- Keep the CMake option `FAIRMQ_DEBUG_MODE` at its default `OFF`. In debug mode, the `shmem` transport records each message in the shared memory under a lock.
- Find the executables. In a build directory, they are in `<build>/fairmq/`. In an installation, they are in the `bin` directory. The commands on this page expect them in `$PATH`.
- Open two terminals on the same host.
## Measure the zeromq transport
<Steps>
1. In the first terminal, start the sink:
```sh
fairmq-sink --id sink1 \
--channel-config name=data,type=pair,method=connect,address=tcp://127.0.0.1:5555
```
2. In the second terminal, start the sampler with messages of 1 MB:
```sh
fairmq-bsampler --id bsampler1 --msg-size 1000000 \
--channel-config name=data,type=pair,method=bind,address=tcp://127.0.0.1:5555
```
3. Wait some seconds. Then read the rate lines in the two terminals. See [Read the rate lines](#read-the-rate-lines).
4. Stop each device. Push `q` in its terminal, or push Ctrl+C.
</Steps>
The two devices connect with a `pair` channel. The [start script](#use-the-start-script) uses the same channel. The default of `--msg-size` is `1000000` bytes. The command gives the option only to show the value.
## Measure the shmem transport
With `--transport shmem`, the sampler makes each message in a shared memory segment. The socket sends only a small metadata message with the location of the buffer. The receiver finds the buffer in the same segment.
<Steps>
1. In the first terminal, start the sink:
```sh
fairmq-sink --id sink1 --transport shmem \
--channel-config name=data,type=pair,method=connect,address=tcp://127.0.0.1:5555
```
2. In the second terminal, start the sampler:
```sh
fairmq-bsampler --id bsampler1 --transport shmem --msg-size 1000000 \
--shm-throw-bad-alloc false \
--channel-config name=data,type=pair,method=bind,address=tcp://127.0.0.1:5555
```
3. Read the rate lines. Then stop the two devices.
</Steps>
The two devices must use the same shared memory:
- They must run on the same host.
- They must use the same `--session`. The default is `default`.
- They must run with the same effective user ID. The name of the segment comes from the session name and the user ID.
The default segment size is 2147483648 bytes (2 GiB, option `--shm-segment-size`). Messages that wait in the queues of the channel use memory in the segment. With `--shm-throw-bad-alloc false`, the sampler waits for free memory when the segment is full. Without this option, the sampler goes to the state `ERROR`. See [Problems that can occur](#problems-that-can-occur).
## Send a fixed number of messages
To measure the time for a number of messages, give the same `--max-iterations` to the two devices. Also give `--control static`, so that each process ends after the run.
<Steps>
1. Start the sink:
```sh
fairmq-sink --id sink1 --control static --max-iterations 100000 \
--channel-config name=data,type=pair,method=connect,address=tcp://127.0.0.1:5555
```
2. Start the sampler:
```sh
fairmq-bsampler --id bsampler1 --control static --max-iterations 100000 \
--channel-config name=data,type=pair,method=bind,address=tcp://127.0.0.1:5555
```
3. Read the last lines of each device:
```txt
Done 100000 iterations in <t>ms.
```
```txt
Received 100000 messages in <t>ms.
```
</Steps>
Each device sends or receives one more message than the value of `--max-iterations`. The log line shows the value. See [the note on fairmq-bsampler](/tools/builtin-devices/#fairmq-bsampler).
Each time starts when the device enters the state `RUNNING`. So the time includes the wait for the other device. Use the time of the device that you start last. The mean data rate is the number of messages multiplied by `--msg-size`, divided by the time.
With the default `--control dynamic`, the device does not end after the last message. It goes back to the state `READY` and waits for a key.
## Change the load
Give these options to the sampler. Give `--multipart` with the same value to the sink.
| Option | Effect |
| --- | --- |
| `--msg-size <bytes>` | Size of each message, or of each part. Small messages show the cost of each message. Large messages show the maximum data rate. |
| `--multipart true --num-parts <n>` | Send multipart messages of `n` parts. The rate lines count a multipart message as one message. |
| `--msg-rate <n>` | Send at most `n` messages per second. Use it to measure a fixed load. |
| `--memset true` | Write zeros into each buffer before the send. Without it, no device writes or reads the data. |
| `--msg-alignment <bytes>` | Alignment of each buffer. `0` is the default alignment of the transport. |
To keep the two devices on different CPU cores, start them with `taskset`:
```sh
taskset -c 1 fairmq-sink --id sink1 \
--channel-config name=data,type=pair,method=connect,address=tcp://127.0.0.1:5555
```
```sh
taskset -c 0 fairmq-bsampler --id bsampler1 \
--channel-config name=data,type=pair,method=bind,address=tcp://127.0.0.1:5555
```
## Use the start script
The build directory has the script `startMQBenchmark.sh`. It starts the sampler and the sink in two `xterm` windows, with the channel of this page. It needs `xterm` and a display.
<Steps>
1. Go to the directory of the script:
```sh
cd build/fairmq
```
2. Start the benchmark. The parameters are the message size, the number of iterations and the transport:
```sh
./startMQBenchmark.sh 1000000 0 shmem
```
3. Read the rate lines in the two windows.
</Steps>
The script also takes the parameters affinity, multipart and number of parts. It does not give `--control static`. See [The script startMQBenchmark.sh](/tools/builtin-devices/#the-script-startmqbenchmarksh).
## Read the rate lines
During the state `RUNNING`, a thread of each device logs one line for each sub-channel every second. These lines have the severity `info`:
```txt
data[0]: in: <msg/s> (<MB/s> MB) out: <msg/s> (<MB/s> MB)
```
- `data[0]` is the name of the sub-channel. The device pads the names on the left to the length of the longest name.
- `in` is the receive rate. `out` is the send rate.
- The first number is the number of messages per second.
- The number in parentheses is the data rate in megabytes per second. One MB is 1000000 bytes. A multipart message counts once, with the sum of the sizes of its parts.
- The device divides the counts by the measured time since the last line.
The device computes the values in [`Device::LogSocketRates()`](/source/fairmq/Device.cxx/#L613-L705):
<Snippet file="fairmq/Device.cxx" start="mbPerSecIn.at(i) = (static_cast" end='<< "out: "' />
The `in` values of the sampler and the `out` values of the sink are 0. The numbers in this example are not a measurement:
```txt
data[0]: in: 0 (0 MB) out: 2840.16 (2840.16 MB)
```
```txt
data[0]: in: 2840.16 (2840.16 MB) out: 0 (0 MB)
```
The channel property `rateLogging` sets the interval in seconds. The default is `1`. `0` turns the lines off for the sub-channel. Give the property in the channel configuration, for example `name=data,type=pair,method=bind,address=tcp://127.0.0.1:5555,rateLogging=0`. See [Channel properties](/reference/channel-properties/).
:::caution[Keep rateLogging at 1 for measurements]
With a value `n` above 1, the device adds up the counts of `n` seconds, but it divides them by the time of the last second. So the logged rates are about `n` times too high.
:::
With `--severity state`, `warn` or a higher severity, the device does not log the rate lines.
## Understand the numbers
- Compare the `out` rate of the sampler with the `in` rate of the sink. After some seconds, they are almost equal.
- Do not use the first lines. They include the time until the other device connects, and the time to fill the queues.
- The data rate is the message rate multiplied by the message size.
- With `shmem`, the data does not go through the socket. The data rate shows how fast the devices pass buffers, not how fast data moves in memory.
- Without `--memset true`, the measurement does not include the time to write or read the data. A real device writes and reads its data.
- Run each measurement more than one time. Other processes on the host change the result.
## Measure between two hosts
Only the `zeromq` transport connects devices on two hosts. The `shmem` transport works only on one host.
<Steps>
1. On the first host, start the sampler. It binds on all interfaces:
```sh
fairmq-bsampler --id bsampler1 \
--channel-config name=data,type=pair,method=bind,address=tcp://*:5555
```
2. On the second host, start the sink. Replace `<host1>` with the name or the IP address of the first host:
```sh
fairmq-sink --id sink1 \
--channel-config name=data,type=pair,method=connect,address=tcp://<host1>:5555
```
</Steps>
The firewall of the first host must accept connections on port 5555.
## Problems that can occur
| Problem | Cause | Solution |
| --- | --- | --- |
| The sampler goes to `ERROR` with `Requested message size (<n>) exceeds segment size (<m>)`. | With `shmem`, a message and its header must fit into the segment. | Give a larger `--shm-segment-size` to the two devices, or use a smaller `--msg-size`. |
| The sampler goes to `ERROR` with `shmem: could not create a message of size <n>, …, free memory: <m>`. | The segment is full. By default, the device tries one time. | Give `--shm-throw-bad-alloc false` to the sampler. It then tries again every `--bad-alloc-attempt-interval` ms (default 50) and logs no line. Or give `--bad-alloc-max-attempts <n>`. |
| The rate lines show `in: 0` on the sink. | The devices do not use the same address, transport, session or user. | Check the options of the two devices. |
| The rates of the sink do not agree with the sampler, or the sink logs errors. | The devices use different `--multipart` values. With `shmem`, single messages and multipart messages have different metadata. | Give the same `--multipart` value to the two devices. |
| Shared memory of an old run stays after a crash. | A device that crashes does not remove the shared memory. | Remove it with `fairmq-shmmonitor --cleanup --session default`. See [Monitor and clean up](/shmem/monitor/). |
| The rates change a lot between runs. | Other processes use the same CPU cores. | Pin the devices to different cores with `taskset`. |
## Related pages
- [Built-in devices](/tools/builtin-devices/): all options of `fairmq-bsampler` and `fairmq-sink`, and the start script.
- [Channel properties](/reference/channel-properties/): `rateLogging`, `sndBufSize`, `rcvBufSize` and the other properties.
- [Sessions and segments](/shmem/sessions/): the names of the shared memory objects.
- [Tune and debug](/shmem/tuning/): segment size and bad allocations.
- [fairmq-shmmonitor](/tools/shmmonitor/): look at and remove shared memory.
- [Transports](/concepts/transports/#tune-the-zeromq-transport): the I/O threads, queues and kernel buffers of the zeromq transport.

View File

@@ -0,0 +1,282 @@
---
title: 'Use channels without a device'
description: 'Make a transport factory and channels in your own program, send and receive messages, and close the channels, without fair::mq::Device.'
sidebar:
order: 6
code: [fairmq/TransportFactory.h, fairmq/TransportFactory.cxx, fairmq/Channel.h, fairmq/Channel.cxx]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
You can use the FairMQ transports and channels without
[`fair::mq::Device`](/api/fair/mq/Device/), for example
[in a test](/guides/test-devices/#test-without-a-device), or in a tool with its own main
loop. You make the transport factory and the channels yourself, bind and connect them,
and send and receive messages. You do not get the state machine, the plugins and the command-line
options of a device.
## Make and use channels
<Steps>
1. Make a [`fair::mq::ProgOptions`](/api/fair/mq/ProgOptions/) object. Set the properties that the
transport reads.
2. Make the transport factory with
[`TransportFactory::CreateTransportFactory()`](/api/fair/mq/TransportFactory/#CreateTransportFactory).
3. Make each channel with a constructor that takes the factory.
4. Bind or connect each channel. Make sure that the call returns `true`.
5. Make messages with the channel, and send and receive them with a timeout.
6. At the end, destroy the messages first, then the channels, and then the factory.
</Steps>
This program does all steps with the zeromq transport. It sends one message from a `push` channel
to a `pull` channel in the same program:
```cpp title="main.cxx"
#include <fairmq/Channel.h>
#include <fairmq/ProgOptions.h>
#include <fairmq/TransportFactory.h>
#include <iostream>
#include <string>
int main()
{
fair::mq::ProgOptions config;
config.SetProperty<int>("io-threads", 1);
auto factory = fair::mq::TransportFactory::CreateTransportFactory("zeromq", "my-program", &config);
fair::mq::Channel pull("data-in", "pull", factory);
fair::mq::Channel push("data-out", "push", factory);
if (!pull.Bind("tcp://127.0.0.1:5555") || !push.Connect("tcp://127.0.0.1:5555")) {
return 1;
}
auto out(push.NewSimpleMessage("hello"));
if (push.Send(out, 1000) < 0) {
return 1;
}
auto in(pull.NewMessage());
if (pull.Receive(in, 1000) < 0) {
return 1;
}
std::cout << std::string(static_cast<char*>(in->GetData()), in->GetSize()) << '\n';
return 0;
}
```
Link the program with the CMake target `FairMQ::FairMQ`, as in
[Use FairMQ in a CMake project](/start/cmake/). The program writes `hello`.
## Make the transport factory
`CreateTransportFactory(type, id, config)` returns a `std::shared_ptr<fair::mq::TransportFactory>`:
- `type` is `zeromq` or `shmem`. For other values, the function throws
[`fair::mq::TransportFactoryError`](/api/fair/mq/TransportFactoryError/).
- `id` names the factory. The zeromq sockets get the identity `<id>.<channel name>.<type>`. If `id`
is empty, the function makes a UUID.
- `config` is a pointer to a `ProgOptions` object. The factory reads its properties when you make
it. With `nullptr`, the factory uses the defaults.
A new `ProgOptions` object has only the log options and `help`, `version` and `print-options`. The
factory reads each other property with a default value, so set only the properties that you change.
The most important properties:
| Property | C++ type | Default | Transport |
| --- | --- | --- | --- |
| `io-threads` | `int` | `1` | both |
| `session` | `std::string` | `default` | shmem |
| `shm-segment-size` | `std::size_t` | 2 GiB | shmem |
| `shm-monitor` | `bool` | `false` | shmem |
| `shm-no-cleanup` | `bool` | `false` | shmem |
| `shm-metadata-msg-size` | `std::size_t` | `0` | shmem |
The shmem transport reads more properties, for example `shm-allocation`, `shm-segment-id` and
`shm-throw-bad-alloc`. Set each property with the C++ type that the transport reads. For another
type, the factory throws `boost::bad_any_cast`. For all properties, see
[Command-line options](/reference/options/). The test
helper of FairMQ sets the properties for the shmem transport:
<Snippet file="test/helper/Transport.h" start="inline auto Configure(ProgOptions& config," />
Each factory has its own zeromq context, and ZeroMQ connects `inproc://` endpoints only inside one
context. Thus an `inproc://` address connects only channels of the same factory. For the shmem transport, all factories with the same session share the shared memory.
See [Sessions and segments](/shmem/sessions/).
## Make the channels
[`fair::mq::Channel`](/api/fair/mq/Channel/) has two constructors that take a factory. Both make the
socket at once:
| Constructor | What it stores |
| --- | --- |
| [`Channel(name, type, factory)`](/api/fair/mq/Channel/#Channel-4) | The name and the socket type. |
| [`Channel(name, type, method, address, factory)`](/api/fair/mq/Channel/#Channel-5) | Also the method (`bind` or `connect`) and the address, for `Validate()`. |
The socket types are `push`, `pull`, `pub`, `sub`, `xpub`, `xsub`, `req`, `rep`, `dealer`, `router`
and `pair`. An unknown type throws an exception. The shmem transport throws
[`fair::mq::SocketError`](/api/fair/mq/SocketError/) for `pub` and `sub`.
The other constructors make a channel without a factory and without a socket. The device gives such
channels their factory. Your program cannot do this, because the function for it is private.
A copy of a channel has no factory and no socket. Move a channel, or make it in place, for example
with `emplace_back()`. Use each channel from one thread at a time, because the class is not
[thread-safe](/concepts/threads/#what-is-thread-safe). Different threads can use different channels.
## Bind and connect
| Function | What it does |
| --- | --- |
| [`Bind(address)`](/api/fair/mq/Channel/#Bind) | Sets the method `bind` and the address of the channel, and binds the socket. |
| [`Connect(address)`](/api/fair/mq/Channel/#Connect) | Sets the method `connect` and the address of the channel, and connects the socket. |
| [`BindEndpoint(endpoint)`](/api/fair/mq/Channel/#BindEndpoint) | Binds the socket. If the bind fails for a `tcp://` endpoint, it tries random ports. |
| [`ConnectEndpoint(endpoint)`](/api/fair/mq/Channel/#ConnectEndpoint) | Connects the socket. |
All four functions return `false` if the transport cannot bind or connect. Each call takes one
endpoint, for example `tcp://127.0.0.1:5555`, `ipc:///tmp/data` or `inproc://data`.
`BindEndpoint()` changes its argument. If the bind fails, the endpoint is a `tcp://` endpoint, and
the property `autoBind` is `true` (default), it tries up to 1000 random ports. The ports are in the
range from `portRangeMin` to `portRangeMax` (default 22000 to 23000). Then the string holds the
endpoint with the new port ([Channel.cxx](/source/fairmq/Channel.cxx/#L346-L386)). The tests use
the port 1, which a normal user cannot bind:
<Snippet file="test/channel/_tcp.cxx" start="TEST_P(Tcp, AutoBind)" />
### Apply the channel properties
A socket from the constructor has the defaults of the transport, for example a linger time of
1000 ms. The functions `UpdateLinger()`, `UpdateSndBufSize()`, `UpdateRcvBufSize()`,
`UpdateSndKernelSize()` and `UpdateRcvKernelSize()` change only the values in the channel object.
To apply them, do the steps of a device:
<Steps>
1. Make the channel with the method and the address.
2. Call [`Validate()`](/api/fair/mq/Channel/#Validate). It returns `false` for a wrong name or
address. It throws [`ChannelConfigurationError`](/api/fair/mq/Channel/ChannelConfigurationError/)
for a wrong type or method, and for a negative size or rate logging interval. It logs the cause.
3. Call [`Init()`](/api/fair/mq/Channel/#Init). It makes a new socket with the linger time, the
buffer sizes and the kernel sizes of the channel.
4. Call `BindEndpoint()` or `ConnectEndpoint()` with the address.
</Steps>
Call `Init()` before you bind or connect, because it replaces the socket. To change one option of a
bound socket, use the socket directly, for example
[`GetSocket().SetLinger(500)`](/api/fair/mq/Socket/#SetLinger).
Other properties apply at once: `Send()` and `Receive()` read the timeouts of
[`UpdateSndTimeout()`](/api/fair/mq/Channel/#UpdateSndTimeout) and
[`UpdateRcvTimeout()`](/api/fair/mq/Channel/#UpdateRcvTimeout). `BindEndpoint()` reads the values of
[`UpdateAutoBind()`](/api/fair/mq/Channel/#UpdateAutoBind) and of the port range.
## Send and receive
[`Send(msg, timeout)`](/api/fair/mq/Channel/#Send) and
[`Receive(msg, timeout)`](/api/fair/mq/Channel/#Receive) take a `MessagePtr`, a
[`fair::mq::Parts`](/api/fair/mq/Parts/) object or a `std::vector<fair::mq::MessagePtr>`, and a
timeout in milliseconds. They return the number of bytes, or a negative
[transfer code](/reference/transfer-codes/): `-1` error, `-2` timeout, `-3` interrupted.
Without a timeout, they use the channel properties `sndTimeoutMs` and `rcvTimeoutMs`. The default
is `-1`, which waits without a limit. A timeout of `0` returns at once.
The sockets wait in steps of 100 ms. Thus the transports round a positive timeout up to a multiple
of 100 ms.
Make messages with the channel, with [`NewMessage()`](/api/fair/mq/Channel/#NewMessage) or
[`NewSimpleMessage()`](/api/fair/mq/Channel/#NewSimpleMessage). Then the message has the transport
of the channel. A `pair` channel sends and receives:
<Snippet file="test/channel/_tcp.cxx" start="TEST_P(Tcp, Pair)" />
The test uses this function to receive a string:
<Snippet file="test/channel/_tcp.cxx" start="auto ReceiveString(Channel& channel) -> string" />
To wait for messages on several channels, use a poller from
[`CreatePoller()`](/api/fair/mq/TransportFactory/#CreatePoller-2) of the factory. See
[Poll several channels](/guides/poll-channels/).
## Stop a blocking call
[`Interrupt()`](/api/fair/mq/TransportFactory/#Interrupt) of the factory stops the waiting
`Send()` and `Receive()` calls of all channels of this factory. They return `-3`
(`TransferCode::interrupted`) within about 100 ms. Until you call
[`Resume()`](/api/fair/mq/TransportFactory/#Resume), each call that has to wait also returns `-3`.
A device calls `Interrupt()` on each transition request, and `Resume()` when the next state starts.
In your program, call `Interrupt()` from another thread. In this test, the function
`delayedInterruptor()` waits 100 ms and then calls `Interrupt()`:
<Snippet file="test/transport/_transfer_timeout.cxx" start="TEST_P(InterruptTransfer, Receive)" />
The test `Factory.ResumeAfterInterrupt` in
[`test/transport/_factory.cxx`](https://github.com/FairRootGroup/FairMQ/blob/dev/test/transport/_factory.cxx)
shows that the channels transfer messages again after `Resume()`.
## Close the channels
A channel has no close function. Its destructor closes the socket. `Socket::Close()` is deprecated.
<Steps>
1. Destroy the messages and the unmanaged regions, because they keep a pointer to the factory.
Destroy the pollers, because they keep the sockets of the channels.
2. Destroy the channels. Each channel keeps a `std::shared_ptr` to the factory.
3. Destroy your last `std::shared_ptr` to the factory.
</Steps>
C++ destroys local objects in the reverse order of their declaration. Thus declare the factory
first, then the channels, then the messages, as in the program above.
The destructor of the factory calls `zmq_ctx_term()`. In ZeroMQ, this call waits until the closed
sockets sent the messages in their queues, for the linger time of each socket at most.
For the shmem transport, the last factory of the session removes the shared memory, unless
`shm-no-cleanup` is `true`. If your program ends without this step, for example after a crash,
remove the shared memory with [`fairmq-shmmonitor`](/tools/shmmonitor/):
```sh
fairmq-shmmonitor --cleanup --session default
```
## What you do not get without a device
| Topic | With a device | Without a device |
| --- | --- | --- |
| [States](/concepts/states/) | The state machine calls your hooks, for example `InitTask()` and `Run()`. | Your program has its own main loop. |
| Interruptions | The device calls `Interrupt()` and `Resume()` on each transition. | Call them yourself. |
| [Options](/reference/options/) | A device program parses `--id`, `--transport`, `--channel-config`, `--mq-config`, `--session` and the other options. | `ProgOptions` knows only the log options and `help`, `version` and `print-options`. Set the properties with `SetProperty()`. |
| Channels | The device makes the channels from the configuration, and gives each channel the factory of its transport. | Make the factories and the channels yourself. |
| Addresses | The device accepts a list of endpoints, the modifiers `@`, `+` and `>`, and host names. It takes a bind address from `--network-interface`, and waits up to `--init-timeout` for the addresses of connecting channels. | One endpoint for each call. |
| Data | `OnData()` callbacks, `ConditionalRun()` with `--rate`, and the rate log of each channel. | Your own loop. |
| [Plugins](/concepts/plugins/) | Controllers and other plugins, for example `--control static`. | None. |
| [Logging](/tools/logging/) | The device runner applies `--severity` and the other log options. | Call `fair::Logger::SetConsoleSeverity()` yourself. |
## Related pages
- [Transports](/concepts/transports/): the transport factories and their properties.
- [Channels and sockets](/concepts/channels/): the socket types and the channel properties.
- [Messages and multipart](/concepts/messages/): how to make, send and receive messages.
- [Handle errors and timeouts](/guides/errors-timeouts/): the transfer codes and what to do.

View File

@@ -0,0 +1,237 @@
---
title: 'Configure channels'
description: 'Give a device its channels with --channel-config, a JSON file or properties from code, on one host or on several hosts.'
sidebar:
order: 2
code: [fairmq/SuboptParser.cxx, fairmq/JSONParser.cxx, fairmq/Device.cxx, fairmq/tools/Network.cxx, fairmq/plugins/config/Config.cxx]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps, Tabs, TabItem } from '@astrojs/starlight/components';
This guide shows how to give a device its channels: with `--channel-config`, with a JSON file, or as properties from code. The result is a topology in which each device binds or connects its sub-channels on the addresses that you select.
## Before you start
- You have a device made with `runDevice.h`, for example from [Your first device](/start/first-device/).
- You know the channel names that your code uses, for example `"data"` in [`Send(msg, "data")`](/api/fair/mq/Device/#Send) or in [`OnData("data", ...)`](/api/fair/mq/Device/#OnData). The configuration must give channels with the same names.
## Steps
<Steps>
1. Select the socket type of each channel, for example `push` for the sender and `pull` for the receiver. Refer to [Socket types and patterns](/concepts/channels/#socket-types-and-patterns) and [Select the socket pattern](/guides/design-topology/#select-the-socket-pattern).
2. Select the [device that binds](/guides/design-topology/#select-the-device-that-binds). Usually this is the device with a fixed place in the topology, for example the sink. Give it the method `bind` and an address such as `tcp://*:5555`.
3. Give the peers the method `connect` and the address of the binding device, for example `tcp://host1:5555`.
4. Give the configuration to the devices in one of the [three ways](#three-ways-to-give-the-configuration).
5. Start the devices, and [check the result](#check-the-result).
</Steps>
## Three ways to give the configuration
<Tabs>
<TabItem label="--channel-config">
Give one value for each channel. A value is a list of `key=value` pairs, separated by `,`, without spaces. Put the value in quotes if it contains `*`, so that the shell does not change it.
```sh
fairmq-ex-1-n-1-processor --id processor1 \
--channel-config 'name=data1,type=pull,method=connect,address=tcp://localhost:5555' \
'name=data2,type=push,method=connect,address=tcp://localhost:5556'
```
- Give all channels as values after one `--channel-config`, as the examples do.
- `name=data1,...` and `data1:...` give the same name ([SuboptParser.cxx](/source/fairmq/SuboptParser.cxx/#L91-L98)).
- Each `address=` key makes one sub-channel. All other keys apply to all sub-channels of the channel, at each position in the list ([SuboptParser.cxx](/source/fairmq/SuboptParser.cxx/#L100-L110)).
- The parser logs `Ignoring unknown argument in --channel-config` for an unknown key.
- Because `,` separates the keys, an address with several endpoints is not possible here.
</TabItem>
<TabItem label="JSON file">
Write one file for all devices of the topology, with one entry for each device. Give the file with `--mq-config`. The device reads the entry that matches `--config-key`, or `--id` if there is no `--config-key`. An entry matches by its `key`, or by its `id` if it has no `key`.
```sh
fairmq-ex-1-n-1-processor --id processor1 --mq-config ex-1-n-1.json --config-key processor
```
- The values of a channel are the defaults for its `sockets`. Each socket object makes one sub-channel.
- Several devices can use one entry with `--config-key`, for example the two processors of the 1-n-1 example.
- If you give `--mq-config` and `--channel-config`, the device reads only the JSON file.
[JSON configuration](/reference/json/) describes the format and the errors. The [complete example](#a-complete-example) below shows a file.
</TabItem>
<TabItem label="Properties from code">
Set the properties `chans.<name>.<index>.<property>` before the controller requests the transition `COMPLETE INIT`. Use the exact types: `std::string`, `int` or `bool`. Each sub-channel needs a `type` property, otherwise the device does not see it. For a plugin, set them when the device goes into `INITIALIZING DEVICE`:
```cpp
#include <fairmq/Plugin.h>
#include <string>
#include <utility>
struct ChannelSetup : fair::mq::Plugin
{
template<typename... Args>
ChannelSetup(Args&&... args)
: Plugin(std::forward<Args>(args)...)
{
SubscribeToDeviceStateChange([this](DeviceState state) {
if (state == DeviceState::InitializingDevice) {
SetProperty<std::string>("chans.data.0.type", "push");
SetProperty<std::string>("chans.data.0.method", "bind");
SetProperty<std::string>("chans.data.0.address", "tcp://*:5555");
SetProperty<int>("chans.data.0.rateLogging", 0);
}
});
}
~ChannelSetup() override { UnsubscribeFromDeviceStateChange(); }
};
```
Register and load the plugin as [Write a plugin](/guides/write-plugin/) describes. The device runner makes the plugins of `-P` before the config plugin. If `--mq-config` or `--channel-config` also gives the channel `data`, the config plugin replaces these values.
In the device, use the hook [`Init()`](/api/fair/mq/Device/#Init). It runs after the request of `COMPLETE INIT`, before the device reads the channel properties:
```cpp
void Init() override
{
fair::mq::Channel channel("push", "bind", "tcp://*:5555");
channel.UpdateRateLogging(0);
AddChannel("data", std::move(channel));
}
```
A device without `runDevice.h` can add its channels before it starts, as this test helper does:
<Snippet file="test/device/_data_callbacks.cxx" start="void AddInput(" />
:::caution
- [`AddChannel()`](/api/fair/mq/Device/#AddChannel) adds a sub-channel at the next free index, also when the channel exists. After `RESET DEVICE`, `Init()` runs again and adds one more sub-channel. If your device can go through `INITIALIZING DEVICE` again, set the properties with `fConfig->SetProperty()` instead.
- `AddChannel()` does not copy `sndTimeoutMs` and `rcvTimeoutMs`. Set them as properties.
- Do not set channels in the constructor of a device that uses `Device()`. With `runDevice.h`, the device runner replaces the store of the device after the constructor.
:::
</TabItem>
</Tabs>
## Several sub-channels
| Method | Several sub-channels |
| --- | --- |
| `--channel-config` | Give one `address=` key for each sub-channel: `name=data,type=push,method=bind,address=tcp://*:5555,address=tcp://*:5556`. Or give `numSockets=3` for sub-channels without an address. |
| JSON file | Give one object for each sub-channel in `sockets`, or give `numSockets` in the channel. |
| Properties | Set the properties of the indexes 0, 1, 2 and so on, without gaps. |
The [copypush example](/examples/copypush/) has a channel with two sub-channels. [Channel properties](/reference/channel-properties/#numsockets) describes `numSockets`.
## Addresses on one host
- `tcp://localhost:5555` or `tcp://127.0.0.1:5555` on the connecting side, and `tcp://*:5555` or `tcp://127.0.0.1:5555` on the binding side.
- `ipc:///tmp/fmq_data` gives a Unix domain socket file. The test scripts of the examples use `ipc://` addresses.
- `inproc://data` connects two sub-channels of the same device with the same transport.
The `shmem` transport uses the same addresses. It sends the metadata of the messages through its ZeroMQ socket on this address, and the data through the shared memory.
## Addresses on several hosts
- On the binding host, bind to `tcp://*:5555` (all interfaces) or to the IPv4 address of one interface.
- On the connecting hosts, give the host name or the IPv4 address of the binding host. The device uses the first IPv4 address of a host name ([Network.cxx](/source/fairmq/tools/Network.cxx/#L160-L177)).
A binding sub-channel without an address binds to the IPv4 address of the interface that `--network-interface` names, for example `eth0` ([Device.cxx](/source/fairmq/Device.cxx/#L185-L198)). With the default `default`, the device uses the interface of the default route. On Linux, it reads `/proc/net/route` and then the output of `ip route`. On macOS, it uses `route -n get default` ([Network.cxx](/source/fairmq/tools/Network.cxx/#L95-L158)). If it finds no interface, it binds to `tcp://*:1`. Without root rights, the bind to port 1 fails, and autobind selects a port. For the functions that find the interface and the addresses, see [Network.h](/reference/tools/#networkh).
The peers must then get the address. After the bind, the device writes the address to the property `chans.<name>.<index>.address`. A plugin can read it and give it to the peers. A connecting device reads its address property again every 50 ms in `CONNECTING`, until the time of `--init-timeout` is over.
## Automatic ports
By default, a binding sub-channel takes a random port from 22000 to 23000 when its TCP bind fails. For fixed ports, switch this off:
```sh
fairmq-ex-1-n-1-sink --id sink1 \
--channel-config 'name=data2,type=pull,method=bind,address=tcp://*:5556,autoBind=false'
```
In a JSON file, write `"autoBind": false`. The keys `portRangeMin` and `portRangeMax` change the range. Refer to [Channel properties](/reference/channel-properties/#portrangemin-portrangemax-and-autobind).
## A complete example
The [1-n-1 example](/examples/1-n-1/) has one sampler, two processors and one sink:
| Device | Channel | Type | Method | Address |
| --- | --- | --- | --- | --- |
| `sampler1` | `data1` | `push` | `bind` | `tcp://*:5555` |
| `processor1`, `processor2` | `data1` | `pull` | `connect` | `tcp://localhost:5555` |
| `processor1`, `processor2` | `data2` | `push` | `connect` | `tcp://localhost:5556` |
| `sink1` | `data2` | `pull` | `bind` | `tcp://*:5556` |
The JSON file has one entry for each device. The two processors use the entry with the key `processor`:
<Snippet file="examples/1-n-1/ex-1-n-1.json" />
The start script gives the file to all devices, and `--config-key processor` to the processors. The build writes it to `examples/1-n-1/fairmq-start-ex-1-n-1.sh` in the build directory, with the paths filled in:
<Snippet file="examples/1-n-1/fairmq-start-ex-1-n-1.sh.in" />
The same topology with `--channel-config`, in four terminals in the directory `examples/1-n-1` of the build directory:
```sh
./fairmq-ex-1-n-1-sampler --id sampler1 \
--channel-config 'name=data1,type=push,method=bind,address=tcp://*:5555,rateLogging=0'
./fairmq-ex-1-n-1-processor --id processor1 \
--channel-config 'name=data1,type=pull,method=connect,address=tcp://localhost:5555,rateLogging=0' \
'name=data2,type=push,method=connect,address=tcp://localhost:5556,rateLogging=0'
./fairmq-ex-1-n-1-processor --id processor2 \
--channel-config 'name=data1,type=pull,method=connect,address=tcp://localhost:5555,rateLogging=0' \
'name=data2,type=push,method=connect,address=tcp://localhost:5556,rateLogging=0'
./fairmq-ex-1-n-1-sink --id sink1 \
--channel-config 'name=data2,type=pull,method=bind,address=tcp://*:5556,rateLogging=0'
```
## Check the result
Start the devices with `--severity debug`. For each endpoint, the device logs the address and the method:
```txt
Attached channel data1[0] to tcp://*:5555 (bind) (push)
```
```txt
Attached channel data1[0] to tcp://127.0.0.1:5555 (connect) (pull)
```
The connecting device shows the resolved IPv4 address of `localhost`. In the interactive controller (the default `--control dynamic`), press `p`. The device logs the number of peers of each sub-channel, for example in `sampler1` with two processors:
```txt
data1[0]: 2 peers connected
```
## Problems
| Message or symptom | Cause | Fix |
| --- | --- | --- |
| `GetChannel(): 'data[0]' does not exist.` | The configuration has no channel with the name that the code uses, or the device did not read the configuration. | Compare the names. Look for parser errors at the start of the log. |
| `fair::mq::plugins::Config: no channels configuration provided via --mq-config or --channel-config` | The device has no channel configuration. A misspelled option, for example `--chanel-config`, has the same effect, because the device ignores unknown options. | Give `--channel-config` or `--mq-config`. For a misspelled option, the debug log shows `detected unregistered option`. |
| `No device ID or config-key provided for the configuration parser.` | `--id` and `--config-key` are empty. | Give `--id`. |
| `missing channel name in argument of option --channel-config` | A value of `--channel-config` has no `name`. | Add `name=`. |
| `Invalid channel type: 'unspecified'` | A sub-channel has no `type`. | Give `type`. |
| `Cannot update configuration. Socket method (bind/connect) for channel 'data[0]' not specified.` | A sub-channel has no `method` and no modifier. | Give `method=bind` or `method=connect`. |
| `1 of the binding channels could not initialize` | A bind failed, for example because the port is in use and `autoBind` is `false`. | Free the port, or select another port. |
| `could not connect all channels after 120 attempts` | A connecting sub-channel has no valid address, or its host name does not resolve. | Correct the address. |
| The peers do not find the binding device. | The port was in use, and autobind selected a random port. | Set `autoBind=false`. |
## Related pages
- [Channels and sockets](/concepts/channels/): sub-channels, socket types, methods and addresses.
- [Channel properties](/reference/channel-properties/): all keys, with their defaults.
- [JSON configuration](/reference/json/): the format of the file for `--mq-config`.
- [Configuration and properties](/concepts/configuration/): how the device reads its configuration.
- [1-n-1 example](/examples/1-n-1/): the example of this guide.
- [Design a topology](/guides/design-topology/): the patterns, the binding devices and the transports of a topology.

View File

@@ -0,0 +1,540 @@
---
title: 'Control a device from code'
description: 'Change the state of a device and read its properties from your program or a plugin.'
sidebar:
order: 8
code: [fairmq/Device.h, fairmq/PluginServices.h, fairmq/StateMachine.h, fairmq/StateQueue.h, fairmq/ProgOptions.h, fairmq/PluginManager.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
A controller requests the transitions of a device. This guide shows the ways to write your own controller, also
without `DeviceRunner`. It also shows how to read and change properties while the device runs.
## Choose a way
| Way | Use it when |
| --- | --- |
| [A controller plugin](#control-the-device-from-a-plugin) | The device starts with `runDevice.h` or `DeviceRunner`, and no mode of `--control` fits. |
| [A plugin in your program](#put-the-controller-in-your-program) | You want one executable that contains the device and its controller. |
| [A device in a thread](#run-the-device-in-a-thread) | Your program creates the device without `DeviceRunner`, for example in a test. |
| [Your own `main()` with plugins](#load-plugins-without-devicerunner) | You want the plugins and the command line of a device, but not `DeviceRunner`. |
All ways use the same states and transitions. See [Device states](/concepts/states/) and
[States and transitions](/reference/states/).
## Control the device from a plugin
A plugin requests a transition with [`ChangeDeviceState()`](/api/fair/mq/Plugin/#ChangeDeviceState). Only the plugin
with the controller role can do this. See [The controller role](/concepts/plugins/#the-controller-role).
<Steps>
1. Write a plugin. See [Write a plugin](/guides/write-plugin/).
2. In the constructor, call [`TakeDeviceControl()`](/api/fair/mq/Plugin/#TakeDeviceControl). The plugins of `-P` are
created before the control plugin. Thus your plugin gets the role first.
3. In the constructor, subscribe to the state changes with
[`SubscribeToDeviceStateChange()`](/api/fair/mq/Plugin/#SubscribeToDeviceStateChange).
4. In the callback, request the next transition in each idling state. In `INITIALIZING DEVICE`, request
`CompleteInit`.
5. In `EXITING`, call [`ReleaseDeviceControl()`](/api/fair/mq/Plugin/#ReleaseDeviceControl). `DeviceRunner::Run()`
returns only after the controller releases the role.
6. Call `ReleaseDeviceControl()` in the destructor too. Without the role, the call does nothing.
</Steps>
The plugin of the [custom-controller](/examples/custom-controller/) example does these steps:
<Snippet file="examples/custom-controller/MyController.h" start="struct MyController" />
The control plugin then cannot take the role. It logs the reason with the severity `debug` and starts no controller.
Its signal handling still works.
### Rules for the state callback
- The callback runs in the thread of the state machine, at the start of each state. The device calls the hooks of
the state after all state callbacks return. See [Threads in a device](/concepts/threads/#which-thread-runs-your-code).
- Request no transition in `BINDING`, `CONNECTING`, `INITIALIZING TASK`, `RESETTING TASK` and `RESETTING DEVICE`. The
device ends these states by itself with the transition `Auto`.
- `INITIALIZING DEVICE` waits until the controller requests `CompleteInit`. Set the configuration of the device before
this request.
- The device ends `RUNNING` by itself when its work ends: it requests `Stop`. A `Stop` from the callback of `RUNNING`
is pending before the work starts. Then `ConditionalRun()` and the data callbacks do not run. `PreRun()` and
`PostRun()` still run. `Run()` also runs, but only in a device without data callbacks.
- `ChangeDeviceState()` returns `false` when the state machine refuses the transition.
- `ChangeDeviceState()` throws `fair::mq::PluginServices::DeviceControlError` when another plugin has the role. If no
plugin has the role, the call gives the role to the calling plugin.
- An exception that leaves the callback moves the device to `ERROR`. Catch the exceptions in the callback.
### A controller with its own thread
The device waits until the state callback returns. For a controller that waits, for example for a timer or for input,
use a thread. The built-in control plugin works so:
1. Its state callback puts each new state into a [`fair::mq::StateQueue`](/api/fair/mq/StateQueue/).
2. Its controller thread requests a transition. Then it waits in the queue for the next state.
<Snippet file="fairmq/plugins/control/Control.cxx" start="SubscribeToDeviceStateChange(" />
<Snippet file="fairmq/plugins/control/Control.cxx" start="auto Control::RunStartupSequence()" />
- [`WaitForState(state)`](/api/fair/mq/StateQueue/#WaitForState) takes states from the queue until it gets `state`.
- [`WaitForStateOrCustom(state, predicate)`](/api/fair/mq/StateQueue/#WaitForStateOrCustom) also returns when the
predicate is `true`. The queue checks the predicate after each `Push()` and `Notify()`.
- [`WaitForNext()`](/api/fair/mq/StateQueue/#WaitForNext) returns the next state of the queue.
- When the next state of the queue is `ERROR`, these functions throw
[`fair::mq::DeviceErrorState`](/api/fair/mq/DeviceErrorState/).
## Put the controller in your program
A plugin can be part of the executable. The [custom-controller](/examples/custom-controller/) example works so.
<Steps>
1. Put the plugin class and the macro `REGISTER_FAIRMQ_PLUGIN` into the code of your program.
2. In `main()`, create a [`fair::mq::DeviceRunner`](/api/fair/mq/DeviceRunner/) with `argc` and `argv`.
3. In the hook `hooks::LoadPlugins`, load the plugin with the prefix `s:` and its name, for example `s:mycontroller`.
4. In the hook `hooks::InstantiateDevice`, create the device with `r.fConfig` and put it into `r.fDevice`.
5. Return the result of [`RunWithExceptionHandlers()`](/api/fair/mq/DeviceRunner/#RunWithExceptionHandlers).
6. In CMake, set the target property `ENABLE_EXPORTS` to `ON`. The plugin manager finds the plugin in the symbols of the
executable.
</Steps>
<Snippet file="examples/custom-controller/main.cxx" />
<Snippet file="examples/custom-controller/CMakeLists.txt" start="add_executable(" end="ENABLE_EXPORTS" />
`DeviceRunner` keeps one function for each type of hook. A second `AddHook()` of the same type replaces the first.
The order of the hooks is in [How a device starts](/concepts/plugins/#how-a-device-starts).
## Run the device in a thread
Without `DeviceRunner`, the device has no config plugin and no control plugin. Your program sets the configuration
and requests all transitions.
<Steps>
1. Create the device: a `fair::mq::Device` or an object of your device class.
2. Configure the device, for example with `SetTransport()` and `AddChannel()`.
3. Start [`RunStateMachine()`](/api/fair/mq/Device/#RunStateMachine) in a thread. It returns when the device reaches
`EXITING`.
4. Request each transition with [`ChangeStateOrThrow()`](/api/fair/mq/Device/#ChangeStateOrThrow).
5. Wait for the next idling state with [`WaitForState()`](/api/fair/mq/Device/#WaitForState).
6. In `IDLE`, request `End`. Then join the thread.
</Steps>
The test `Config.SetTransport` does these steps:
<Snippet file="test/device/_config.cxx" start="string TestDeviceSetTransport(" />
The test helper `Control()` requests the transitions of a full cycle. The device of the test has no own `Run()` code.
It goes back to `READY` by itself, so `Control()` waits for `READY` after `RUNNING`.
<Snippet file="test/helper/ControlDevice.h" start="inline auto Control(Device& device" />
### The configuration of the device
- Without a `ProgOptions` object, the device uses its own internal object.
- To use your object, give it to the constructor `Device(ProgOptions&)` or to
[`SetConfig()`](/api/fair/mq/Device/#SetConfig). `SetConfig()` deletes the internal object. Thus call it before the
other setters.
- Set the device ID with the property `id`. [`SetId()`](/api/fair/mq/Device/#SetId) has no effect on a device that
you initialize, because `INITIALIZING DEVICE` reads the property `id`.
### The functions of the device
| Function | What it does |
| --- | --- |
| [`ChangeState(transition)`](/api/fair/mq/Device/#ChangeState) | Requests a transition. Returns `false` when the current state does not accept it, or when another transition is pending. [`ChangeState(name)`](/api/fair/mq/Device/#ChangeState-2) takes the name, for example `"INIT DEVICE"`. |
| `ChangeStateOrThrow()` | Requests a transition. Throws `std::system_error` when `ChangeState()` returns `false`. The text starts with the name of the transition, for example `Invalid transition: CONNECT`. The error code is `ErrorCode::DeviceChangeStateFailed`. |
| `WaitForState(state)` | Waits until the device enters `state`. [`WaitForState(name)`](/api/fair/mq/Device/#WaitForState-2) takes the name, for example `"READY"`. |
| [`WaitForNextState()`](/api/fair/mq/Device/#WaitForNextState) | Waits for the next state and returns it. |
| [`GetCurrentState()`](/api/fair/mq/Device/#GetCurrentState), [`GetCurrentStateName()`](/api/fair/mq/Device/#GetCurrentStateName) | Return the current state. |
| [`SubscribeToStateChange(key, callback)`](/api/fair/mq/Device/#SubscribeToStateChange) | Calls `callback` at the start of each state, in the thread of the state machine. `UnsubscribeFromStateChange(key)` removes it. |
| [`SubscribeToNewTransition(key, callback)`](/api/fair/mq/Device/#SubscribeToNewTransition) | Calls `callback` when the state machine accepts a transition, in the thread that requests the transition. |
| [`NewStatePending()`](/api/fair/mq/Device/#NewStatePending) | Returns `true` when a transition is requested and the next state has not started yet. |
`ChangeState()` is `[[nodiscard]]`. A name that does not exist makes `ChangeState(name)` and `WaitForState(name)`
throw `std::out_of_range`. The names are in [States and transitions](/reference/states/).
### How WaitForState() works
The device puts each new state into a queue. `WaitForState()` takes states from the queue until it finds the given
state. Thus it returns at once for a state that is in the queue already.
- The first `IDLE` is not in the queue. Do not wait for it.
- After the transition `ErrorFound`, the queue gets `ERROR`. Then `WaitForState()` and `WaitForNextState()` throw
`fair::mq::DeviceErrorState` with the text `Controlled device transitioned to error state.`
- After an exception in a hook, the queue gets no `ERROR`. Then `WaitForState()` does not return.
`RunStateMachine()` lets the exception of a hook pass to its caller. Catch it in the thread: an exception that leaves
the function of a `std::thread` calls `std::terminate()`. To see `ERROR` in all cases, use `SubscribeToStateChange()`. The
state machine calls the subscribers with `ERROR` also after an exception.
### The class StateMachine
Each device has a private [`fair::mq::StateMachine`](/api/fair/mq/StateMachine/). Use the functions of the device for
it. The class also works without a device. The tests in `test/state_machine/_state_machine.cxx` use it so.
| Function | What it does |
| --- | --- |
| [`Start()`](/api/fair/mq/StateMachine/#Start) | Starts the state machine in `IDLE`. Call it before the first transition. |
| [`ProcessWork()`](/api/fair/mq/StateMachine/#ProcessWork) | Runs the loop. It first calls the subscribers with `IDLE`. For each new state, it calls the `PrepareState()` function, the subscribers and the `HandleStates()` function. It returns in `EXITING`. |
| [`PrepareState(f)`](/api/fair/mq/StateMachine/#PrepareState), [`HandleStates(f)`](/api/fair/mq/StateMachine/#HandleStates) | Set the functions for each new state. Each takes one function. A second call logs an error. `StopHandlingStates()` removes both. |
| [`WaitForPendingState()`](/api/fair/mq/StateMachine/#WaitForPendingState), [`WaitForPendingStateFor(ms)`](/api/fair/mq/StateMachine/#WaitForPendingStateFor) | Wait until a transition is requested. `WaitForPendingStateFor()` returns `false` after the timeout. |
| `ChangeState()`, `SubscribeToStateChange()`, `SubscribeToNewTransition()`, `NewStatePending()`, `GetCurrentState()` | Work as the functions of the device. |
In `ERROR`, `ProcessWork()` throws [`StateMachine::ErrorStateException`](/api/fair/mq/StateMachine/ErrorStateException/).
When a function of the loop throws, `ProcessWork()` sets `ERROR`, calls the subscribers with `ERROR`, and passes the
exception on.
## Parse options without DeviceRunner
Without `DeviceRunner`, no code reads the command line. Your program can parse it with a
[`fair::mq::ProgOptions`](/api/fair/mq/ProgOptions/) object and give this object to the device.
<Steps>
1. Create a `ProgOptions` object. It knows only the general options: `--help`, `--version`, `--severity`,
`--file-severity`, `--verbosity`, `--color`, `--log-to-file` and `--print-options`
([ProgOptions.cxx](/source/fairmq/ProgOptions.cxx/#L69-L83)).
2. Add your options with [`AddToCmdLineOptions()`](/api/fair/mq/ProgOptions/#AddToCmdLineOptions). It takes a
`boost::program_options::options_description`. Add all options before the parse.
3. Call [`ParseAll(argc, argv, true)`](/api/fair/mq/ProgOptions/#ParseAll-2).
4. To apply the log options, call
[`DeviceRunner::HandleGeneralOptions(config, false)`](/api/fair/mq/DeviceRunner/#HandleGeneralOptions). It is
static. For `--help` and `--print-options`, it prints the options and returns `false`. The second argument
`true` prints the FairMQ logo.
5. Call [`Notify()`](/api/fair/mq/ProgOptions/#Notify). It calls `boost::program_options::notify()`. `DeviceRunner`
calls it after `HandleGeneralOptions()` too.
6. Give the object to the device: use the constructor `Device(ProgOptions&)` or
[`SetConfig()`](/api/fair/mq/Device/#SetConfig). See [The configuration of the device](#the-configuration-of-the-device).
7. Request the transitions as in [Run the device in a thread](#run-the-device-in-a-thread).
</Steps>
The test `Config.SetConfig` parses two options and gives the object to the device:
<Snippet file="test/device/_config.cxx" start="string TestDeviceSetConfig(" />
- `ParseAll()` first removes all properties, also the values of `SetProperty()`
([ProgOptions.cxx](/source/fairmq/ProgOptions.cxx/#L108-L132)). Then it stores the values of the command line and
the defaults of the registered options. Call `SetProperty()` after `ParseAll()`, as the test does.
- The last argument `true` accepts options that are not registered. `ParseAll()` does not store them as
properties. [`PrintOptions()`](/api/fair/mq/ProgOptions/#PrintOptions) logs each of them at the severity `debug`:
`detected unregistered option: …`. In the test above, `--id` is not registered, so the device ID stays empty.
- With `false`, an option that is not registered throws `boost::program_options::unknown_option`. The test in
`test/properties/_properties.cxx` checks this.
- The first element of `argv`, or of the vector of the other overload, is the name of the program. The parser skips
it (Boost behavior).
### The device options and the channels
The device options, for example `--id`, `--transport`, `--session`, `--mq-config` and `--channel-config`, are the
options of the config plugin ([Config.cxx](/source/fairmq/plugins/config/Config.cxx/#L56-L87)). In
`INITIALIZING DEVICE`, the config plugin also turns `--mq-config` or `--channel-config` into channel properties
([Config.cxx](/source/fairmq/plugins/config/Config.cxx/#L22-L53)). A program without `DeviceRunner` has two ways to get
them:
- Load the config plugin with a plugin manager, and add its options before the parse. See
[Load plugins without DeviceRunner](#load-plugins-without-devicerunner). The test `Config.SetConfigWithPlugins`
does this:
<Snippet file="test/device/_config.cxx" start="string TestDeviceSetConfigWithPlugins(" />
- Register only the options that you need, and make the channel properties yourself.
[`SuboptParser()`](/api/fair/mq/#SuboptParser) turns the values of `--channel-config` into channel properties.
[`JSONParser()`](/api/fair/mq/#JSONParser) reads them from a JSON file.
[`SetProperties()`](/api/fair/mq/ProgOptions/#SetProperties) stores them. Store them before you request
`CompleteInit`, because the device reads the channel properties after this request.
This function does the second way for the options `--id` and `--channel-config`:
```cpp
#include <fairmq/ProgOptions.h>
#include <fairmq/SuboptParser.h>
#include <boost/program_options.hpp>
#include <string>
#include <vector>
void Configure(fair::mq::ProgOptions& config, int argc, char* argv[])
{
namespace bpo = boost::program_options;
bpo::options_description options("My device");
options.add_options()
("id", bpo::value<std::string>()->default_value("sampler1"), "Device ID")
("channel-config", bpo::value<std::vector<std::string>>()->multitoken()->composing(), "Channels");
config.AddToCmdLineOptions(options);
config.ParseAll(argc, argv, true);
config.Notify();
if (config.Count("channel-config")) {
auto const id = config.GetProperty<std::string>("id");
auto const channels = config.GetProperty<std::vector<std::string>>("channel-config");
config.SetProperties(fair::mq::SuboptParser(channels, id));
}
}
```
For a value without `name`, `SuboptParser()` throws `boost::property_tree::ptree_bad_path`. For an empty device ID,
it throws [`fair::mq::ParserError`](/api/fair/mq/ParserError/). The test `SuboptParser.Errors` checks both. The
device options that you do not register, for example `transport` and `rate`, have the defaults of the device.
## Load plugins without DeviceRunner
A [`fair::mq::PluginManager`](/api/fair/mq/PluginManager/) loads, creates and owns the plugins of a device. Without
`DeviceRunner`, your program must call its functions in the sequence of
[`DeviceRunner::Run()`](/source/fairmq/DeviceRunner.cxx/#L108-L194):
| Step | Call | Notes |
| --- | --- | --- |
| 1 | [`LoadPlugin(name)`](/api/fair/mq/PluginManager/#LoadPlugin) or [`LoadPlugins(names)`](/api/fair/mq/PluginManager/#LoadPlugins) | Finds the plugin and its options. It does not create the plugin. `DeviceRunner` loads the plugins of `-P` (in the constructor of the plugin manager), then `s:config`, then the plugins of the hook `LoadPlugins`, then `s:control`. For the prefixes, see [Load a plugin](/concepts/plugins/#load-a-plugin). |
| 2 | [`ForEachPluginProgOptions()`](/api/fair/mq/PluginManager/#ForEachPluginProgOptions) with `AddToCmdLineOptions()` | Adds the options of the loaded plugins. `DeviceRunner` also adds [`PluginManager::ProgramOptions()`](/api/fair/mq/PluginManager/#ProgramOptions) (`-P` and `-S`). |
| 3 | `ParseAll()`, `HandleGeneralOptions()`, `Notify()` | See [Parse options without DeviceRunner](#parse-options-without-devicerunner). |
| 4 | `SetConfig()` of the device | Give the device the `ProgOptions` object of the plugins. Otherwise the device does not see the properties that the plugins set, for example the channels of the config plugin. |
| 5 | [`EmplacePluginServices(config, device)`](/api/fair/mq/PluginManager/#EmplacePluginServices) | Makes the [`PluginServices`](/api/fair/mq/PluginServices/) object, which connects the plugins to the device and to the properties. |
| 6 | [`InstantiatePlugins()`](/api/fair/mq/PluginManager/#InstantiatePlugins) | Creates the plugins in the load sequence. The constructors run now, and a controller takes its role. |
| 7 | [`RunStateMachine()`](/api/fair/mq/Device/#RunStateMachine) of the device | Returns in `EXITING`. |
| 8 | [`WaitForPluginsToReleaseDeviceControl()`](/api/fair/mq/PluginManager/#WaitForPluginsToReleaseDeviceControl) | Waits until no plugin has the controller role. |
This `main()` has the minimum sequence for the built-in plugins. `MyDevice` is your device class:
```cpp
#include <fairmq/Device.h>
#include <fairmq/DeviceRunner.h> // DeviceRunner::HandleGeneralOptions()
#include <fairmq/PluginManager.h>
#include <fairmq/ProgOptions.h>
#include <fairmq/tools/Strings.h> // tools::ToStrVector()
#include <boost/program_options.hpp>
int main(int argc, char* argv[])
{
// Declare the configuration and the device before the plugin manager.
// Then the plugin manager and its plugins are destroyed first.
fair::mq::ProgOptions config;
MyDevice device;
fair::mq::PluginManager mgr(fair::mq::tools::ToStrVector(argc, argv, false)); // reads -S and -P
mgr.LoadPlugin("s:config");
mgr.LoadPlugin("s:control");
mgr.ForEachPluginProgOptions([&](boost::program_options::options_description options) {
config.AddToCmdLineOptions(options);
});
config.AddToCmdLineOptions(fair::mq::PluginManager::ProgramOptions());
config.ParseAll(argc, argv, true);
if (!fair::mq::DeviceRunner::HandleGeneralOptions(config, false)) {
return 0; // --help or --print-options
}
config.Notify();
device.SetConfig(config);
mgr.EmplacePluginServices(config, device);
mgr.InstantiatePlugins();
device.RunStateMachine();
mgr.WaitForPluginsToReleaseDeviceControl();
return 0;
}
```
The test `PluginManager.LoadPluginStatic` uses the control plugin without a parse. It sets the two options of the
control plugin with `SetProperty()` before `InstantiatePlugins()`:
<Snippet file="test/plugins/_plugin_manager.cxx" start="TEST(PluginManager, LoadPluginStatic)" />
Rules for the sequence:
- Call `EmplacePluginServices()` before `InstantiatePlugins()` and before `WaitForPluginsToReleaseDeviceControl()`.
Both use the `PluginServices` object, and the plugin manager does not check that it exists.
- The plugins read their options in their constructors. The control plugin reads `control` and `catch-signals`. If a
property is missing, `InstantiatePlugins()` throws
[`PluginManager::PluginInstantiationError`](/api/fair/mq/PluginManager/PluginInstantiationError/), for example
`An error occurred while instantiating plugin control: Config has no key: control`.
- The plugins unsubscribe from the device in their destructors. Thus the device must exist until the plugin manager is
destroyed.
- The constructor `PluginManager(args)` reads `-S` and `-P` from `args` and loads the plugins of `-P`. It throws
[`PluginManager::ProgramOptionsParseError`](/api/fair/mq/PluginManager/ProgramOptionsParseError/) for an option
value that it cannot parse. The default constructor reads nothing.
- With the default `--control dynamic`, the control plugin reads keys from the terminal. For a program without a
terminal, use `--control static`. See [Control modes](/concepts/plugins/#control-modes).
## Several devices in one process
One process can run more than one device. The test `MultipleDevices.TwoInSameProcess` runs a sender and a receiver
in one process. Each device runs `RunStateMachine()` in its own thread, and its controller requests the transitions
from another thread:
<Snippet file="test/device/_multiple_devices.cxx" start="class MultipleDevices" />
Each device has its own objects:
- **A state machine.** Each `Device` object has a private `StateMachine`. The transitions of one device do not change
the other devices.
- **A property store.** Without `SetConfig()`, each device uses its own internal `ProgOptions` object. If you give
your own object, give each device its own. The device reads `id` and the `chans.` properties from it, and it writes
the bound addresses back.
- **Transports.** In `INITIALIZING DEVICE`, [`AddTransport()`](/api/fair/mq/Device/#AddTransport) makes one transport
factory for each transport type of the device, from the property store of the device
([Device.cxx](/source/fairmq/Device.cxx/#L586-L605)). All channels of the device with this type use it.
Two devices do not share a transport factory. No constructor of `Device` takes a factory, and
[`SetTransport()`](/api/fair/mq/Device/#SetTransport) only sets the property `transport` (the name). The public API
has no function that gives a device an existing factory. Only a derived class has access to the protected member
`fTransports`, in which `AddTransport()` looks for an existing factory. No test or example uses this, and
`RESETTING DEVICE` clears the member. For channels that share one factory, use channels without a
device. See [Use channels without a device](/guides/channels-without-device/).
What this means for each transport:
- **zeromq:** Each factory has its own ZeroMQ context, with its own I/O threads
([zeromq/TransportFactory.h](/source/fairmq/zeromq/TransportFactory.h/#L30-L45)). An `inproc://` address connects only
sockets of one context (ZeroMQ behavior). Thus use `ipc://` or `tcp://` between two devices of one process. The
test above uses `ipc://`.
- **shmem:** Each factory opens the segments of its session and increments the device counter. Devices in one
process with the same session (the property `session`) exchange messages in the same way as devices in different processes. The test
`ShmMessages.ZeroCopyFromUnmanaged` (`test/message/_message.cxx`) makes two shmem factories with one session in one
process and sends messages between them.
The limits are in the parts of FairMQ that exist once per process:
- **The logger is global.** FairLogger keeps its settings in static members. A change of the severity, the verbosity
or the log file applies to all devices of the process. The prefix of a log line does not contain the device ID.
See [Logging](/tools/logging/).
- **The signal handling of the control plugin is global.** The control plugin installs its handlers for `SIGINT` and
`SIGTERM` with `signal()`. It counts the signals in global variables, and no code resets them
([Control.cxx](/source/fairmq/plugins/control/Control.cxx/#L25-L45)). One signal starts the shutdown of each device
with a control plugin in the process. The next `SIGINT` ends the process with `std::abort()`. A control plugin that
starts after a signal, with `--catch-signals 1`, shuts down its device at once.
- **The interactive mode reads the standard input** ([Control.cxx](/source/fairmq/plugins/control/Control.cxx/#L157-L180)).
Two interactive controllers in one process read the same keys.
- **One `DeviceRunner` for each process.** `DeviceRunner` sets the global logger, and it loads the control plugin.
FairMQ has no test with two `DeviceRunner` objects in one process. Run the other devices without `DeviceRunner`,
and control them from your code, as the test above does.
For the threads of each device, see [Threads in a device](/concepts/threads/).
## Read and change properties at run time
The device, the plugins and the hooks of `DeviceRunner` share one
[`fair::mq::ProgOptions`](/api/fair/mq/ProgOptions/) object. Each option of the command line is a property in it. See
[Configuration and properties](/concepts/configuration/).
| Code | Access to the properties |
| --- | --- |
| A plugin | The property functions of [`Plugin`](/api/fair/mq/Plugin/#GetProperty), for example `GetProperty<T>()` and `SetProperty<T>()`. |
| A device | [`GetConfig()`](/api/fair/mq/Device/#GetConfig) returns a pointer to the `ProgOptions` object. |
| A hook of `DeviceRunner` | The member `fConfig` of the runner. |
| A program without `DeviceRunner` | Your `ProgOptions` object, or `GetConfig()` of the device. |
### Read and set a property
- [`GetProperty<T>(key)`](/api/fair/mq/ProgOptions/#GetProperty) throws
[`fair::mq::PropertyNotFoundError`](/api/fair/mq/PropertyNotFoundError/) when the key does not exist. The text is
`Config has no key: <key>`.
- [`GetProperty<T>(key, fallback)`](/api/fair/mq/ProgOptions/#GetProperty-2) returns `fallback` when the key does not
exist.
- `T` must be the type of the stored value, for example `float` for `rate` and `int` for `io-threads`. For another
type, both functions throw an exception.
- [`GetPropertyAsString(key)`](/api/fair/mq/ProgOptions/#GetPropertyAsString) returns the value as text. For a type
that [`PropertyHelper`](/api/fair/mq/PropertyHelper/) does not know, the text is `[unidentified_type]`.
- [`SetProperty<T>(key, value)`](/api/fair/mq/ProgOptions/#SetProperty) adds or changes a property.
[`UpdateProperty<T>()`](/api/fair/mq/ProgOptions/#UpdateProperty) changes only a property that exists. It returns
`false` otherwise.
- The type of the value is the type of the property. `SetProperty("key", "text")` stores a `const char*`. Use
`SetProperty<std::string>("key", "text")` for a text property.
### Follow the changes
[`Subscribe<T>(subscriber, callback)`](/api/fair/mq/ProgOptions/#Subscribe) calls `callback` with the key and the new
value of each change. A plugin uses [`SubscribeToPropertyChange<T>()`](/api/fair/mq/Plugin/#SubscribeToPropertyChange).
- The callback runs in the thread that changes the property, before `SetProperty()` returns ([Threads in a device](/concepts/threads/#which-thread-runs-your-code)). Protect the data that the
callback changes, for example with `std::atomic`.
- The callback gets only the changes with a value of the type `T`. A subscription for `std::string` gets no call for a
`const char*` value.
- [`SubscribeAsString()`](/api/fair/mq/ProgOptions/#SubscribeAsString) gets the changes of all types, with the value
as text.
- `SetProperty()`, `UpdateProperty()`, `SetProperties()` and `UpdateProperties()` call the subscribers.
`DeleteProperty()` and `AddChannel()` do not.
- A subscriber name has one subscription for each type. A second subscription with the same name and type replaces the
first.
- [`Unsubscribe<T>(subscriber)`](/api/fair/mq/ProgOptions/#Unsubscribe) throws `std::out_of_range` when the
subscription does not exist.
The dispatcher of the [qc](/examples/qc/) example subscribes in `InitTask()` and unsubscribes in `ResetTask()`. The
value `active` of the property `qc` sets the flag `fDoQC`. The value `inactive` clears it.
<Snippet file="examples/qc/qCDispatcher.cxx" start="void InitTask()" />
A plugin can set the flag with `SetProperty<std::string>("qc", "active")`. The callback runs in the thread that calls
`SetProperty()`. Thus `fDoQC` is a `std::atomic<bool>`.
### When a change has an effect
| Property | The device uses a new value |
| --- | --- |
| `severity`, `file-severity`, `verbosity`, `log-to-file` (type `std::string`), `color` (type `bool`) | At once. `DeviceRunner` subscribes to these keys after it parses the command line. See [Logging](/tools/logging/). |
| `id`, `rate`, `init-timeout`, `transport`, `network-interface`, `chans.<name>.<index>.<key>` | In `INITIALIZING DEVICE`, after the request of `CompleteInit`. |
| `io-threads`, `session`, the options of shared memory | In `INITIALIZING DEVICE`, when the device creates the transport. |
| `chans.<name>.<index>.address` of a channel that is not connected yet | In `CONNECTING`. The device reads the address again every 50 ms, until the time of `init-timeout` ends. |
| Your own properties | When your code reads them, or in your subscription callback. |
[When the device reads a property](/concepts/configuration/#when-the-device-reads-a-property) has the details for
each property.
- In its state callback of `INITIALIZING DEVICE`, the config plugin writes the channel properties of `--mq-config` or
`--channel-config`. The device reads the properties after all state callbacks return and after the request of
`CompleteInit`.
- The state callbacks of the plugins run in the sequence in which the plugin manager creates the plugins. The plugins
of `-P` come first, then `config`, the plugins of the hook `LoadPlugins`, and `control`.
- After `BINDING`, `chans.<name>.<index>.address` holds the address that the channel bound to.
- To use new values of the `INITIALIZING DEVICE` properties, request `ResetDevice` and initialize the device again.
`RESETTING DEVICE` removes the channels and the transports.
## Problems
| Problem | Cause and solution |
| --- | --- |
| `ChangeState()` or `ChangeDeviceState()` returns `false`. | The log shows the cause. `No transition from state … on transition …`: the current state does not accept the transition. `Transition … incoming, but another state transition is already ongoing.`: wait for the next state first. |
| The device stays in `INITIALIZING DEVICE`. | The device waits for `CompleteInit`. Request it. |
| `WaitForState()` does not return. | The state does not come. Check the transition that you requested, and check the log for an exception in a hook. |
| `DeviceRunner::Run()` does not return after `EXITING`. | A plugin has the controller role. Call `ReleaseDeviceControl()` in `EXITING`. |
| `RUNNING` ends at once. | The controller requested `Stop` in the callback of `RUNNING`, or the work of the device ended. |
| A subscription callback gets no call. | The type of the new value is not the type of the subscription. Give the type to `SetProperty<T>()`. |
| `could not connect all channels after 120 attempts` | A channel did not connect in the time of `init-timeout`. The number in the text is the value of `init-timeout` in seconds. |
## Related pages
- [Plugins and control](/concepts/plugins/): the control plugin, its modes and the controller role.
- [Write a plugin](/guides/write-plugin/): build and load your own plugin.
- [custom-controller](/examples/custom-controller/): the complete controller example.
- [Device states](/concepts/states/): the states, the hooks and the state `ERROR`.

View File

@@ -0,0 +1,284 @@
---
title: Design a topology
description: 'Select the patterns, the binding devices, the channels and the transports of a topology: fan-out, fan-in, n to m, broadcast, one host and several hosts.'
sidebar:
order: 2.5
code: [fairmq/Channel.h, fairmq/Device.cxx, fairmq/devices/Splitter.h, fairmq/devices/Merger.h, fairmq/devices/Multiplier.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
A topology is a set of devices and the channels that connect them. This guide shows how to select the
socket type, the binding side, the channels and the transport of each link, and how to plan the
addresses. Each decision refers to an example of the repository that uses it.
## Before you start
- Read [Channels and sockets](/concepts/channels/). This guide uses its terms and does not repeat its
tables.
- Draw your devices and the direction of the data between them. Each arrow is a link.
## Steps
<Steps>
1. For each link, [select the socket pattern](#select-the-socket-pattern).
2. For each link, [select the device that binds](#select-the-device-that-binds).
3. Decide where you need [sub-channels or several channels](#sub-channels-or-several-channels).
4. [Select the transport](#select-the-transport-of-each-link) of each link.
5. Write the [address plan](#plan-the-addresses).
6. Write the configuration as [Configure channels](/guides/configure-channels/) shows, and
[check the result](#check-the-result).
</Steps>
## Select the socket pattern
The [socket types](/concepts/channels/#socket-types-and-patterns) give four patterns. Select the
pattern from what the link must do:
| What the link must do | Pattern | Transports | Example |
| --- | --- | --- | --- |
| Give each message to one of several workers | `push` to `pull` | `zeromq`, `shmem` | [1-n-1](/examples/1-n-1/) |
| Collect the messages of several senders | `push` to `pull` | `zeromq`, `shmem` | [1-n-1](/examples/1-n-1/), [n-m](/examples/n-m/) |
| Send each message to all receivers | `pub` to `sub` | `zeromq` only | [multiple-channels](/examples/multiple-channels/) |
| Send the same data to all receivers with `shmem` | `push` sub-channels and `Copy()` | `zeromq`, `shmem` | [copypush](/examples/copypush/) |
| Send a request and wait for the reply | `req` to `rep` | `zeromq`, `shmem` | [req-rep](/examples/req-rep/) |
| Connect exactly two devices | `pair` | `zeromq`, `shmem` | [readout](/examples/readout/) |
Know these properties of the patterns before you select one. For the details, see
[Behavior of each socket type](/concepts/channels/#behavior-of-each-socket-type).
- A `push` socket with several peers gives each message to one peer, in turn. A `pull` socket
receives from all its peers. When the queues of all peers are full, `Send()` waits (ZeroMQ
behavior). Thus the receivers slow down the sender when they cannot keep up.
- The channel properties `sndBufSize` and `rcvBufSize` (default 1000 messages) set the size of the
send queue and the receive queue. FairMQ gives them to ZeroMQ as `ZMQ_SNDHWM` and `ZMQ_RCVHWM`
([Channel.cxx](/source/fairmq/Channel.cxx/#L328-L330)).
- A `pub` socket does not wait for slow `sub` peers. For a peer with a full queue, it drops the
messages. A `sub` socket that connects late misses the earlier messages (ZeroMQ behavior). Do not
use `pub` and `sub` for data that must arrive.
- The `zeromq` transport subscribes each `sub` socket to all messages
([zeromq/Socket.h](/source/fairmq/zeromq/Socket.h/#L70-L74)). FairMQ has no option for a topic
filter ([zeromq/Common.h](/source/fairmq/zeromq/Common.h/#L91-L123)).
- The `shmem` transport throws `SocketError` for `pub` and `sub`. Give such a channel
`transport=zeromq`, as the channel `ack` of the
[multiple-transports example](/examples/multiple-transports/) does.
- A `req` socket must send and receive in turn. One `rep` server can answer several `req` clients
(ZeroMQ behavior).
- A `pair` socket has one peer (ZeroMQ behavior). For n peers, the device needs n sub-channels.
## Patterns of the examples
### Fan-out and fan-in
In the [1-n-1 example](/examples/1-n-1/), the sampler binds a `push` channel, and the processors
connect to it. The processors also connect to the `pull` channel of the sink. The `push` socket
distributes the messages, and the `pull` socket of the sink collects them. All processors have the
same configuration. A binding socket accepts new peers at any time (ZeroMQ behavior), so you can add a
processor while the other devices run.
You can also distribute the messages in your code. Give the output channel one sub-channel for each
receiver, and select the index in `Send()`. The built-in devices do this:
- [`fairmq-splitter`](/tools/builtin-devices/#fairmq-splitter) sends each message on the next
sub-channel of its output channel, in turn.
- [`fairmq-merger`](/tools/builtin-devices/#fairmq-merger) polls all sub-channels of its input channel
and sends on one output.
- [`fairmq-multiplier`](/tools/builtin-devices/#fairmq-multiplier) sends each message to all
sub-channels of all output channels, with `Copy()` for all except the last.
<Snippet file="fairmq/devices/Splitter.h" start="bool HandleData(T& payload, int)" />
The [copypush example](/examples/copypush/) sends a copy of each message on each sub-channel.
`Copy()` does not copy the data. Use this form for a broadcast with `shmem`.
### n senders to m receivers
In the [n-m example](/examples/n-m/), each of the three senders connects to all four receivers. The
`data` channel of a sender has one sub-channel for each receiver:
<Snippet file="examples/n-m/fairmq-start-ex-n-m.sh.in" start='SENDER0="fairmq-ex-n-m-sender"' end="num-receivers 4" />
- A synchronizer sends an id on a `pub` channel. All senders get the same id.
- Each sender selects the sub-channel from the id: the id modulo `--num-receivers`. Thus all parts of
one id go to the same receiver.
- Each receiver binds one `pull` channel and collects the parts of all senders.
- The senders send with a timeout of 0 ms. If the queue of one receiver is full, the sender drops the
parts and continues with the other receivers. See
[Timeout for one call](/guides/errors-timeouts/#timeout-for-one-call).
The pair variant of the example uses `pair` channels. Each receiver then binds one sub-channel for
each sender. The push and pull variant needs 4 ports for the data, and the pair variant needs 12 (3
senders × 4 receivers).
### Broadcast and data
In the [multiple-channels example](/examples/multiple-channels/), the sampler sends data to the sink
on `data` (`push` to `pull`). A broadcaster binds a `pub` channel, and the sampler and the sink connect
a `sub` channel to it. The two links have different socket types, so each device has two channels. The
sampler polls both channels in its `Run()` loop. The sink registers one data callback for each channel.
### A readout chain
In the [readout example](/examples/readout/), the readout device creates an
[unmanaged region](/shmem/regions/) with the transport of its output channel and sends messages that
point into it. The start script gives each channel its transport:
<Snippet file="examples/readout/fairmq-start-ex-readout.sh.in" start='READOUT="fairmq-ex-readout-readout"' end="name=sr,type=pair,method=bind" />
- The links on the readout host use `shmem`. The messages go from the readout device through the
builder to the sender without a copy.
- The sender forwards the messages to the receiver on a `zeromq` channel. The receiver can run on
another host.
- The readout device gets the acknowledgement for a block of the region when the last device releases
it. For the link to the other host, this is after the zeromq transport releases the data.
## Select the device that binds
Bind on the device with a stable place in the topology. Connect on the devices that you add, remove or
start several times:
| Link | Binds | Connects | Example |
| --- | --- | --- | --- |
| One source, n workers, one sink | Source and sink | Workers | [1-n-1](/examples/1-n-1/) |
| n senders, m receivers | Receivers | Senders | [n-m](/examples/n-m/) |
| One broadcaster, n listeners | Broadcaster | Listeners | [multiple-channels](/examples/multiple-channels/) |
| One server, n clients | Server | Clients | [req-rep](/examples/req-rep/) |
| A chain of devices | `readout1`, `sender1`, `receiver1` | `builder1`, `sender1` | [readout](/examples/readout/) |
- The method does not depend on the socket type. In the [multipart example](/examples/multipart/), the
`pull` side binds. In the multiple-transports example, the `sub` channel `ack` binds and the `pub`
channel connects.
- The connecting devices need the address of the binding device. With one binding device, all
connecting devices can use one configuration. The processors of the 1-n-1 example share one entry of
the JSON file with `--config-key processor`.
- You can start the devices in any sequence. See [Bind and connect](/concepts/channels/#bind-and-connect).
## Sub-channels or several channels
| Use | When | Example |
| --- | --- | --- |
| One sub-channel with several peers | The socket distributes the messages, and all peers are equal. You can add peers without a change in the binding device. | [1-n-1](/examples/1-n-1/) |
| Several sub-channels of one channel | All links have the same role, socket type and transport, and your code selects the peer with the index. | [copypush](/examples/copypush/), [n-m](/examples/n-m/) |
| Several channels | The links have different roles, socket types or transports. | [multiple-channels](/examples/multiple-channels/), [multiple-transports](/examples/multiple-transports/) |
- In `--channel-config`, each `address=` key makes one sub-channel. See
[Several sub-channels](/guides/configure-channels/#several-sub-channels).
- Give all sub-channels of one channel the same transport. The pollers and the data callbacks use the
transport of the sub-channel 0 for all sub-channels ([Device.cxx](/source/fairmq/Device.cxx/#L452-L481)).
- A data callback gets the index of the sub-channel. With more than one input sub-channel, the device
polls all of them. See [Several input channels](/guides/receive-data/#several-input-channels).
## Select the transport of each link
- Use `shmem` for the links inside one host. The receiver finds the data in the shared memory, and
only the metadata goes through the socket. Both peers must use the same `--session`. See
[Transports](/concepts/transports/).
- Use `zeromq` for the links between hosts, and for `pub` and `sub`.
- A device on the border of a host has channels of both transports. Make its messages with
`NewMessageFor()`. A shmem message goes out on a zeromq channel without a copy. A zeromq message on
a shmem channel is copied. See [Use several transports](/guides/several-transports/).
- If a device receives with data callbacks from channels of two transports, the device polls each
transport in its own thread. See [Threads in a device](/concepts/threads/).
- Create a region in the first device of a chain, with the transport of its output channel. See
[Unmanaged regions](/shmem/regions/).
- To run two topologies on one host, give them different sessions. See
[Keep two topologies apart](/shmem/sessions/#keep-two-topologies-apart).
## Plan the addresses
### Fixed ports
Give each binding sub-channel its own port. The examples use fixed ports, for example 5555 and
5556 in 1-n-1, and 8010 and 8021 to 8024 in n-m.
- Set `autoBind=false` on the binding sub-channels. Otherwise a port in use gives a random port, and
the peers do not find the device. See [Automatic ports](/concepts/channels/#automatic-ports).
- Bind to `tcp://*:<port>` for all interfaces (ZeroMQ behavior). The start scripts of n-m and
readout bind to `tcp://localhost:<port>`. This works only on one host.
- On the connecting side, give the host name or the IPv4 address of the binding host. See
[Addresses on several hosts](/guides/configure-channels/#addresses-on-several-hosts).
### Automatic ports
A binding sub-channel without an address binds to port 1 of the interface of `--network-interface`.
Without root rights, this bind fails. Then autobind (`autoBind`, default `true`) selects a random port
from `portRangeMin` to `portRangeMax` (default 22000 to 23000). After the bind, the device writes the
address to the property `chans.<name>.<index>.address`. Your code, for example a plugin, must give this
address to the connecting devices. A connecting device reads its
address property again every 50 ms in `CONNECTING`, until `--init-timeout` (default 120 s) ends. See
[Addresses on several hosts](/guides/configure-channels/#addresses-on-several-hosts).
The topologies of the [dds](/examples/dds/) and [qc](/examples/qc/) examples have no addresses. The DDS
plugin of FairMQ v1.4.56 gave the addresses to the peers. This repository has no such plugin.
### ipc on one host
On one host, `ipc://` endpoints need no ports. The test scripts of the examples use one file for each
sub-channel, with the session in the name. The channels then get the address `ipc://$chan1Addr`:
<Snippet file="examples/1-n-1/test-ex-1-n-1.sh.in" start='chan1Addr="/tmp/fmq_' end="chan2Addr=" />
Both transports work with `ipc://`. The shmem transport sends the metadata of the messages on this
endpoint. Use `inproc://` only between channels of one transport in one device. An `inproc://`
endpoint works only inside one ZeroMQ context (ZeroMQ behavior), and each transport of a device has
its own context.
## Example for each need
| Need | Example |
| --- | --- |
| Two devices, one direction | [1-1](/examples/1-1/) |
| Distribute work and collect the results | [1-n-1](/examples/1-n-1/) |
| Request and reply | [req-rep](/examples/req-rep/) |
| Several parts in one message | [multipart](/examples/multipart/) |
| The same data to each receiver, also with `shmem` | [copypush](/examples/copypush/) |
| Data and a broadcast in one device | [multiple-channels](/examples/multiple-channels/) |
| `shmem` and `zeromq` in one device | [multiple-transports](/examples/multiple-transports/) |
| Messages from your own shared memory, with acknowledgements | [region](/examples/region/) |
| A readout chain from one host to another | [readout](/examples/readout/) |
| Split, merge and copy without your own code | [builtin-devices](/examples/builtin-devices/) |
| n senders to m receivers | [n-m](/examples/n-m/) |
| A topology without addresses, started by DDS | [dds](/examples/dds/), [qc](/examples/qc/) |
| Your own controller | [custom-controller](/examples/custom-controller/) |
## Check the result
<Steps>
1. Start the devices with `--severity debug`.
2. Find the line `Attached channel <name>[<index>] to <address> (<method>) (<type>)` for each
sub-channel. See [Check the result](/guides/configure-channels/#check-the-result).
3. In the interactive controller, press `p`. Each sub-channel must show the number of peers of your
plan.
4. Look at the rate lines of each sub-channel. The device logs them only for sub-channels with
`rateLogging` above 0 (default 1). A sub-channel with 0 messages per second has no traffic.
</Steps>
## Problems that can occur
| Symptom | Cause | Fix |
| --- | --- | --- |
| `PUB/SUB socket type is not supported for shared memory transport` | A `pub` or `sub` channel uses `shmem`. | Add `transport=zeromq` to both ends. |
| A sender stops when one receiver stops. | The sender selects the sub-channel, and the queue of that sub-channel is full. `Send()` waits. | Send with a timeout, as the n-m sender does, or let one `push` socket distribute. It waits only when the queues of all peers are full (ZeroMQ behavior). |
| The `sub` peers miss messages. | `pub` drops messages for slow peers, and a late `sub` misses the earlier messages (ZeroMQ behavior). | Use `push` and `pull`, or `push` sub-channels with `Copy()`. |
| The peers do not find the binding device. | The port was in use, and autobind selected a random port. | Set `autoBind=false`, and select a free port. |
| Two topologies on one host disturb each other. | They use the same ports, `ipc://` files or session. | Give each topology its own ports or files, and its own `--session`. |
## Related pages
- [Channels and sockets](/concepts/channels/): socket types, methods, addresses and automatic ports.
- [Configure channels](/guides/configure-channels/): write the plan as `--channel-config` or JSON.
- [Use several transports](/guides/several-transports/): a device with `shmem` and `zeromq` channels.
- [Built-in devices](/tools/builtin-devices/): splitter, merger, multiplier and proxy.

View File

@@ -0,0 +1,344 @@
---
title: Stop a topology without losing messages
description: 'End a run so that each sent message arrives: what the transitions do to queued messages, linger, end-of-stream messages, the stop order and the checks.'
sidebar:
order: 9.5
code: [fairmq/Device.cxx, fairmq/Channel.h, fairmq/Channel.cxx, fairmq/plugins/control/Control.cxx, fairmq/zeromq/Context.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
At the end of a run, messages can still wait in the queues of the sockets. A device that resets its
channels too early loses them. This guide shows what each transition does to these messages, and
how each receiver learns that it has all data. It also gives the order in which the devices must
stop, and shows how you check that no message is lost.
## What the transitions do to the messages
Each transition that the state machine accepts interrupts the transports of the device. This is also
true for `Stop` and `Auto`, which the device requests itself
([Device.cxx](/source/fairmq/Device.cxx/#L96-L99)). When the next state starts, the device resumes
the transports ([Device.cxx](/source/fairmq/Device.cxx/#L101-L104)). While the transports are
interrupted, a `Send()` or `Receive()` that must wait returns `TransferCode::interrupted` (-3). A
transfer that is possible at once still completes, because the socket tries the transfer before it
checks the interruption ([zeromq/Socket.h](/source/fairmq/zeromq/Socket.h/#L96-L124)).
| Transition or state | What happens to the messages |
| --- | --- |
| `Stop` (end of `RUNNING`) | The device does not call `ConditionalRun()` or the data callbacks again. A `Send()` that waits returns `interrupted`. This message is not sent, and your `MessagePtr` keeps it. The messages in the queues of the sockets stay there. |
| `READY`, `RESETTING TASK`, `DEVICE READY` | The channels and their queues still exist. After a new `Run`, the device receives the queued messages. |
| `RESETTING DEVICE` | The device resets its transports, calls `Reset()`, and destroys all channels and transports ([Device.cxx](/source/fairmq/Device.cxx/#L732-L749)). The sockets close. The messages in a send queue get the linger time, see [Linger](#linger). The messages in a receive queue are lost (ZeroMQ behavior). |
| `ERROR` | The control plugin requests no more transitions. The device does not call `ResetTask()` and `Reset()`. With `runDevice.h`, the process ends with the exit code 1, and the messages in its receive queues are lost. |
Thus a device must have all its data before it goes to `RESETTING DEVICE`. The transitions are in
[Device states](/concepts/states/#transitions).
## Linger
The channel property `linger` is a time in ms. The default is 500
([Channel.h](/source/fairmq/Channel.h/#L378)). [`Channel::Init()`](/api/fair/mq/Channel/#Init) sets
it as the ZeroMQ option `ZMQ_LINGER` on the socket ([Channel.cxx](/source/fairmq/Channel.cxx/#L325-L326)).
The shmem transport sets it on the ZeroMQ socket that carries the metadata of its messages.
In `RESETTING DEVICE`, the device destroys its transports. The destructor of a transport calls
`zmq_ctx_term()` ([zeromq/Context.h](/source/fairmq/zeromq/Context.h/#L156-L175)). This call waits
until the closed sockets sent the messages in their send queues, for the linger time at most. Then
ZeroMQ discards the remaining messages. This is ZeroMQ behavior. Thus:
- A device can stay up to `linger` ms in `RESETTING DEVICE`.
- Linger helps only if the peer still exists and takes the messages (ZeroMQ behavior). It does not
help the messages in the receive queue of a device that resets.
- With `-1`, ZeroMQ waits without a time limit. If the peer does not take the messages, the device
does not leave `RESETTING DEVICE`.
- With `0`, ZeroMQ discards the queued messages at once.
The test script of the [multipart example](/examples/multipart/#test-the-example) gives the sampler
`linger=1000`. The sampler resets at once after its only message. The longer linger time gives
ZeroMQ more time to deliver this message. Set the value in the channel configuration, for
example `--channel-config name=data,type=push,method=connect,address=tcp://localhost:5555,linger=2000`,
or with `"linger": 2000` in a JSON file. See [Channel properties](/reference/channel-properties/#linger).
With shmem, the data of a message stays in the managed segment, and the linger time applies to the
metadata. After a successful `Send()`, the sender does not free the block any more. If ZeroMQ
discards the metadata, no process frees the block. It stays in the segment until the shared memory of
the session is removed (see [Sessions and segments](/shmem/sessions/#the-device-counter-and-cleanup)).
## Tell each receiver that the data ends
A receiver cannot see if more messages come. The sender must tell it with an end message after its
last data message. Send the end message on the same sub-channel as the data. ZeroMQ delivers the
messages of one connection in the order of the `Send()` calls (ZeroMQ behavior). Messages on
different channels or sub-channels have no fixed order.
The [multipart example](/examples/multipart/) puts a flag into its header. The sampler sets the flag
in its last message:
<Snippet file="examples/multipart/sampler.cxx" start="if (fMaxIterations > 0 && fNumIterations == fMaxIterations - 1)" />
After the last message, `ConditionalRun()` returns `false`. The device then requests `Stop` itself:
<Snippet file="examples/multipart/sampler.cxx" start='Send(parts, "data");' end="^ }" />
The sink leaves `RUNNING` when it gets the flag. The callback returns `false`, and the device goes to
`READY`:
<Snippet file="examples/multipart/sink.cxx" start="if (header.stopFlag == 1)" />
The sampler ignores the return value of `Send()`. Your source must check it. If the end message is
not sent, the receiver does not stop.
### Several receivers and several senders
- **One sender, several receivers.** A `push` socket gives each message to one of its peers
(ZeroMQ behavior). Thus one end message reaches one receiver only. The page of the multipart
example shows this with [two sinks](/examples/multipart/#send-to-two-sinks). Give each receiver its own sub-channel, and send an end message on each sub-channel. The
sender of the [n-m example](/examples/n-m/#sender-select-the-receiver) has one sub-channel for each
receiver. It selects the sub-channel with the index argument of `Send()`. See
[Several sub-channels](/guides/configure-channels/#several-sub-channels).
- **Several senders, one receiver.** The receiver needs one end message from each sender. It must
know the number of senders. The receiver of the n-m example gets this number from its option
`--num-senders`.
- **Processors.** A processor between the senders and the receivers waits for the end messages of
all its inputs. Then it sends an end message on each output and returns `false`.
This sink receives the multipart messages of the example from several senders. It leaves `RUNNING`
after the end message of the last sender:
```cpp
#include "Header.h" // example_multipart::Header
#include <fairmq/Device.h>
#include <fairmq/runDevice.h>
#include <cstdint>
#include <cstring>
#include <stdexcept>
namespace bpo = boost::program_options;
struct Sink : fair::mq::Device
{
Sink() { OnData("data", &Sink::HandleData); }
void InitTask() override { fNumSenders = fConfig->GetProperty<int>("num-senders"); }
bool HandleData(fair::mq::Parts& parts, int /*index*/)
{
if (parts.Size() < 1 || parts.At(0)->GetSize() != sizeof(example_multipart::Header)) {
throw std::runtime_error("unexpected message format");
}
example_multipart::Header header;
std::memcpy(&header, parts.At(0)->GetData(), sizeof(header));
if (header.stopFlag == 1) {
++fNumEnded;
LOG(info) << "End message " << fNumEnded << " of " << fNumSenders;
return fNumEnded < fNumSenders; // false ends RUNNING
}
++fNumReceived;
return true;
}
void PostRun() override { LOG(info) << "Received " << fNumReceived << " data messages"; }
private:
int fNumSenders = 1;
int fNumEnded = 0;
std::uint64_t fNumReceived = 0;
};
void addCustomOptions(bpo::options_description& options)
{
options.add_options()
("num-senders", bpo::value<int>()->default_value(1), "Number of senders");
}
std::unique_ptr<fair::mq::Device> getDevice(fair::mq::ProgOptions& /*config*/)
{
return std::make_unique<Sink>();
}
```
The checks of the size come from [Send your own data types](/guides/send-data-types/#read-the-data-safely).
## Stop the devices in the right order
The data flows from the sources through the processors to the sinks. End `RUNNING` in the same order:
<Steps>
1. End `RUNNING` of the sources. A source that ends by itself sends its end messages and returns
`false`.
2. Let each processor and each sink end `RUNNING` by itself, after its end messages.
3. Wait until all sinks are in `READY`. The log line of each sink contains `RUNNING ---> READY`.
4. Then request `ResetTask`, `ResetDevice` and `End` for all devices.
</Steps>
If a controller stops a sink first, the sink does not read its queue any more. New messages fill
the receive queue of the sink and then the send queue of the sender (ZeroMQ behavior). Then
`Send()` of the sender waits until its timeout ends or a transition interrupts it. When the sink
resets, the messages in its queue are lost.
A signal starts the shutdown sequence of the control plugin: `Stop`, `ResetTask`, `ResetDevice`
and `End`. Thus a signal to all devices at the same time also resets the sinks while data is on the
way. Send the signal to the sources first. Signal the other devices after the sinks left `RUNNING`.
The test script of the [1-n-1 example](/examples/1-n-1/#test-the-example) waits for the sampler and
the sink, which end by themselves. Then it stops the processors with `SIGINT`:
<Snippet file="examples/1-n-1/test-ex-1-n-1.sh.in" start="# wait for sampler and sink to finish" end="wait $PROCESSOR2_PID" />
### A source that a controller stops
A controller can request `Stop` for a source, for example with the key `s` or with a signal. Then
the source cannot send the end message in `RUNNING`. In `PostRun()`, `Stop` is pending and the
transports are interrupted, so a `Send()` that must wait returns `interrupted`. Send the end message
in [`ResetTask()`](/api/fair/mq/Device/#ResetTask) instead. In `RESETTING TASK`, the transports are
not interrupted, and the state machine accepts only `Auto` and `ErrorFound`. Give the `Send()` a
timeout:
```cpp
void ResetTask() override
{
if (fEndSent) {
return; // ConditionalRun() sent the end message already
}
example_multipart::Header header;
header.stopFlag = 1;
fair::mq::Parts parts;
parts.AddPart(NewSimpleMessage(header));
if (Send(parts, "data", 0, 1000) < 0) {
LOG(error) << "Could not send the end message in 1 s";
}
fEndSent = true;
}
```
The sink of the previous section accepts this end message with one part. The sink of the multipart
example expects seven parts and throws an exception for it.
## Wait in PostRun() or ResetTask()
A sink that a controller stops can still read the messages that arrived. The two hooks after
`RUNNING` behave differently:
- **[`PostRun()`](/api/fair/mq/Device/#PostRun):** `Stop` is pending, and the transports are
interrupted. A `Receive()` returns the messages that are already in the receive queue. When the
queue is empty, it returns `interrupted`: at once for the timeout 0, otherwise within 100 ms. Thus
`PostRun()` can empty the queue, but it cannot wait for more messages.
- **[`ResetTask()`](/api/fair/mq/Device/#ResetTask):** the transports are not interrupted. A
`Receive()` with a timeout waits for more messages. Always give a timeout. In `RESETTING TASK`,
the state machine accepts only `Auto` and `ErrorFound`, and the control plugin requests neither.
Thus a `Receive()` without a timeout can block the device.
This `ResetTask()` reads messages until no message arrives for 1 s:
```cpp
void ResetTask() override
{
while (true) {
auto msg(NewMessage());
if (Receive(msg, "data", 0, 1000) < 0) {
break; // no message in 1 s, or an error
}
++fNumReceived;
}
LOG(info) << "Received " << fNumReceived << " messages in total";
}
```
Receive into a [`fair::mq::Parts`](/api/fair/mq/Parts/) object if the sender sends multipart
messages. The four-argument form of [`Receive()`](/api/fair/mq/Device/#Receive-2) takes the
timeout in ms. A wait in `ResetTask()` does not replace the end message: it cannot know whether
the senders sent everything.
## What the controllers do
The built-in control plugin handles the end of `RUNNING` in a different way in each mode
([interactive](/source/fairmq/plugins/control/Control.cxx/#L274-L290),
[static and gui](/source/fairmq/plugins/control/Control.cxx/#L403-L437)):
| `--control` | When `RUNNING` ends | What this means for the end of the run |
| --- | --- | --- |
| `static` | When the device goes to `READY`, the plugin runs the shutdown sequence at once. | The device resets right after its last message. Its linger time must be long enough for its send queue. Use this mode with end messages. |
| `dynamic` (default), `interactive`, `external` | The device stays in `READY`. The plugin waits for keys: `s` requests `Stop`, `q` runs the shutdown sequence. | You select the order. Press `s` for the sources, wait for the sinks, then press `q` in each device. |
| `gui` | The device stays in `READY` until a signal. | Send the signals in the order of this guide. |
| `none` | The plugin requests no transitions. A signal still starts its shutdown sequence. | Your controller must request the transitions in the order of this guide. |
With `--catch-signals 1` (default), the first `SIGINT` or `SIGTERM` runs the shutdown sequence
from the current state. A second `SIGINT` ends the process at once with `std::abort()`, and all
queued messages are lost. After `ERROR`, the plugin runs no shutdown sequence. For the details, see
[Control modes](/concepts/plugins/#control-modes) and
[Startup and shutdown sequences](/reference/states/#startup-and-shutdown-sequences).
## Check that no message is lost
<Steps>
1. Count the successful transfers in each device: each `Send()` that returns 0 or more, and each
received message.
2. Log the counters in `PostRun()` or `ResetTask()`, and compare the numbers of the senders with
the numbers of the receivers.
3. Put the number of data messages into the end message. The receiver then compares it with its own
count. A sequence number in each header also shows which message is missing.
4. Test with a fixed number of messages, and let the receiver stop after this number.
</Steps>
Each channel also counts its transfers.
[`GetMessagesTx()`](/api/fair/mq/Channel/#GetMessagesTx),
[`GetMessagesRx()`](/api/fair/mq/Channel/#GetMessagesRx),
[`GetBytesTx()`](/api/fair/mq/Channel/#GetBytesTx) and
[`GetBytesRx()`](/api/fair/mq/Channel/#GetBytesRx) return the counters of the socket. The socket
increments them after each successful transfer. A multipart message counts as one message. The
counters start when the device makes the socket, and they include all runs since then. Read them
before `RESETTING DEVICE`, because the device destroys the channels there:
```cpp
void ResetTask() override
{
auto& channel = GetChannel("data");
LOG(info) << "data: " << channel.GetMessagesTx() << " messages, " << channel.GetBytesTx() << " bytes sent";
}
```
The tests of the examples use a fixed number. In the test script of the [1-1 example](/examples/1-1/#test-the-example),
the sampler and the sink both have `--max-iterations 1` and `--control static`. The sink ends only
after it received the message. If the message is lost, the sink stays in `RUNNING`, and CTest stops
the test after its timeout of 30 s (`examples/CMakeLists.txt`). See
[Test your devices](/guides/test-devices/).
## Problems that can occur
- **The sink gets fewer messages than the source sent, with `--control static`:** the source reset
before ZeroMQ sent its queue. Increase `linger` on the output channel of the source.
- **A device does not leave `RESETTING DEVICE`:** its `linger` is `-1`, and the peer does not take
the messages. Use a time limit.
- **Only one of several sinks leaves `RUNNING`:** the `push` socket gave the end message to one
peer only. Send an end message on a sub-channel for each receiver.
- **The sink does not leave `RUNNING`:** an end message did not arrive, or the sink expects too many
senders. Check the log of the senders and the number of senders of the sink.
- **`Send()` returns -3 in `PostRun()`:** the transports are interrupted. Send the end message
before `RUNNING` ends, or in `ResetTask()`.
- **Messages are lost after Ctrl-C in all terminals:** each device stopped and reset at once. Stop
the sources first.
- **A device does not leave `RESETTING TASK`:** your `ResetTask()` calls `Receive()` without a
timeout. Give a timeout.
## Related pages
- [Device states](/concepts/states/): the transitions, `PostRun()` and the interruption of the
transports.
- [Plugins and control](/concepts/plugins/#control-modes): the control modes and the signals.
- [Channel properties](/reference/channel-properties/#linger): `linger` and the queue sizes.
- [Handle errors and timeouts](/guides/errors-timeouts/): transfer codes and timeouts.
- [When a peer stops or restarts](/guides/errors-timeouts/#when-a-peer-stops-or-restarts): the queues
and the shared memory of a peer that ends.
- [multipart: several parts in one message](/examples/multipart/): the example with the stop flag.

View File

@@ -0,0 +1,421 @@
---
title: 'Handle errors and timeouts'
description: 'Check the return values of Send() and Receive(), set timeouts, handle interrupted transfers and exceptions, and know what happens in ERROR.'
sidebar:
order: 9
code: [fairmq/Socket.h, fairmq/Channel.h, fairmq/Device.cxx, fairmq/Error.h, fairmq/shmem/Manager.h, fairmq/shmem/Message.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
This guide shows how your device detects failed transfers, uses timeouts and reacts to errors. When
you complete it, your device continues after a timeout, stops cleanly after an interruption, and
goes to `ERROR` only for a real error.
## Check the return value of a transfer
`Send()` and `Receive()` return an `int64_t`. A value of 0 or more is the number of bytes. A negative
value is a [`TransferCode`](/api/fair/mq/TransferCode/):
| Return value | Meaning | Typical reaction |
| --- | --- | --- |
| 0 or more | The transfer is complete. For `Send()`, the message is in the queue of the socket. 0 is the size of an empty message. | Continue. |
| `TransferCode::timeout` (-2) | The timeout ended before the transfer was possible. | Try again, or do other work. |
| `TransferCode::interrupted` (-3) | A transition is pending, and the device interrupted its transports. | Return from the hook. |
| `TransferCode::error` (-1) | The transfer failed. The transport logs the reason. | End `RUNNING`, or throw an exception. |
<Steps>
1. Store the return value of each `Send()` and `Receive()`.
2. Compare a negative value with the codes. Use `static_cast<int64_t>(fair::mq::TransferCode::timeout)`.
3. Select the reaction from the table above.
</Steps>
Many examples only check for a negative value. The sampler of the example [1-1](/examples/1-1/)
ends `RUNNING` for each failed transfer:
<Snippet file="examples/1-1/sampler.cxx" start="bool ConditionalRun()" />
This hook handles each code in a different way. It waits up to 1000 ms for a message:
```cpp
bool ConditionalRun() override
{
auto msg(NewMessage());
auto const result = Receive(msg, "data", 0, 1000);
if (result >= 0) {
LOG(info) << "Received " << result << " bytes";
return true;
}
if (result == static_cast<int64_t>(fair::mq::TransferCode::timeout)) {
LOG(warn) << "No message in 1 s";
return true; // try again in the next call
}
if (result == static_cast<int64_t>(fair::mq::TransferCode::interrupted)) {
return false; // a transition is pending
}
throw std::runtime_error("Receive on channel data failed"); // the device goes to ERROR
}
```
For all codes, see [Transfer codes and errors](/reference/transfer-codes/).
## Set a timeout
A timeout is a value in ms:
- `-1` (default): wait until the transfer is possible, or until a transition interrupts the transfer.
- `0`: do not wait. If the transfer is not possible at once, return `TransferCode::timeout`. While
the transports are interrupted, return `TransferCode::interrupted`.
- A positive value: wait up to this time.
You can give the timeout for one call or for all calls on a channel.
### Timeout for one call
Give the timeout as the fourth argument of
[`Send()`](/api/fair/mq/Device/#Send-2) or [`Receive()`](/api/fair/mq/Device/#Receive-2). On a
[`Channel`](/api/fair/mq/Channel/), it is the second argument. The test device `TransferTimeout`
sends and receives on channels without a peer, with 200 ms and with 0 ms:
<Snippet file="test/helper/devices/TestTransferTimeout.h" start="auto Run() -> void override" />
### Timeout for a channel
The channel properties `sndTimeoutMs` and `rcvTimeoutMs` (default `-1`) set the timeout for all
calls without a timeout argument. Give them in the channel configuration:
```sh
./my-device --id device1 --channel-config name=data,type=pull,method=connect,address=tcp://localhost:5555,rcvTimeoutMs=1000
```
In a JSON file, use the same keys. See [Channel properties](/reference/channel-properties/).
[`Channel::UpdateSndTimeout()`](/api/fair/mq/Channel/#UpdateSndTimeout) and
[`UpdateRcvTimeout()`](/api/fair/mq/Channel/#UpdateRcvTimeout) change the values of a `Channel`
object.
:::caution[Known defect]
[`Device::AddChannel()`](/api/fair/mq/Device/#AddChannel) does not copy `sndTimeoutMs` and
`rcvTimeoutMs` into the configuration. A channel that you add in this way has the timeouts `-1`.
Give the timeout as an argument of each call instead.
:::
### Steps of 100 ms
The zeromq and shmem sockets wait in steps of 100 ms. After each step, the socket checks for an
interruption and for the end of the timeout. Thus:
- The real timeout is the value rounded up to a multiple of 100 ms. A timeout of 150 ms waits
200 ms.
- A transfer that waits returns `TransferCode::interrupted` not more than 100 ms after the
interruption.
## Handle interrupted transfers
When a controller or the device requests a transition, the device calls `Interrupt()` of all its
transports. From then on, a `Send()` or `Receive()` that must wait returns `TransferCode::interrupted`. A transfer
that is possible at once can still complete. When the next state starts, the device resumes the
transports.
Thus:
- Treat `interrupted` as a normal end of `RUNNING`. Return from `ConditionalRun()` with `false`, or
go back to the check of `NewStatePending()` in your `Run()` loop.
- In `PostRun()`, the transports are still interrupted. Do not wait for transfers there. See
[Wait in PostRun() or ResetTask()](/guides/end-of-run/#wait-in-postrun-or-resettask).
- With shmem, a `NewMessage()` that waits for free memory throws `MessageBadAlloc` after an
interruption (see below).
The test `InterruptTransfer.Receive` interrupts a transport while a `Receive()` waits.
`Factory.ResumeAfterInterrupt` shows that transfers work again after `Resume()`.
## Exceptions and the ERROR state
An exception in a hook or in a data callback moves the device to `ERROR`. With input channels on more
than one transport, an exception in a data callback ends the process with `std::terminate()`
instead. Your code can also request the transition `ErrorFound`. The test device `StateAction` does
both:
<Snippet file="test/helper/devices/TestStateAction.h" start="void ActIfRequested(std::string_view state)" />
After an exception, the device does these steps:
1. The state machine logs `Exception caught in ProcessWork(), going to Error state` (severity
`debug`), and changes to `ERROR`.
2. The device does not call the other hooks of the state. After an exception in `RUNNING`, it does
not call `PostRun()`.
3. [`RunStateMachine()`](/api/fair/mq/Device/#RunStateMachine) throws the exception again.
4. With `fairmq/runDevice.h`, `main()` logs `Uncaught exception reached the top of main:` and the
text of the exception. The exit code is 1.
After the transition `ErrorFound`, the current hook continues until it returns. In `RUNNING`, the
device also calls the remaining hooks, for example `PostRun()`. Then the state machine changes to
`ERROR`. `RunStateMachine()` throws `StateMachine::ErrorStateException` with the text
`Device transitioned to error state`, and the exit code is also 1.
The tests `Exceptions.Throw` and `ErrorState.ChangeState` check the exit code 1 for each hook, with
`--control static` and `interactive`.
### What the control plugin does in ERROR
In `ERROR`, the controller of the control plugin stops. It does not run the shutdown sequence. Thus
the device does not call `ResetTask()` and `Reset()` after an error. Free your resources also in the
destructor of your device, or use objects that free them automatically.
With `--catch-signals 1` (default), a signal is not an error. A `SIGINT` in any hook starts the
shutdown sequence, and the exit code is 0. The test `Signals.RaiseSIGINT` checks this for each hook.
## Error codes
[`ChangeStateOrThrow()`](/api/fair/mq/Device/#ChangeStateOrThrow) throws `std::system_error` when the
state machine refuses the transition. The code is
[`ErrorCode::DeviceChangeStateFailed`](/api/fair/mq/ErrorCode/#DeviceChangeStateFailed) (13) in the
category `fairmq`. Compare the value and the name of the category:
```cpp
try {
device.ChangeStateOrThrow(fair::mq::Transition::Run);
} catch (std::system_error const& e) {
if (e.code().value() == static_cast<int>(fair::mq::ErrorCode::DeviceChangeStateFailed)
&& std::string_view(e.code().category().name()) == "fairmq") {
LOG(error) << e.what(); // Invalid transition: RUN: failed to change state of a fairmq device
}
}
```
:::caution
Do not compare `e.code()` with [`fair::mq::MakeErrorCode()`](/api/fair/mq/#MakeErrorCode). `fairmq/Error.h` defines the category
object as `static`, so each translation unit has its own object. Then the comparison can return
`false` for the same error.
:::
The text of `what()` comes from the standard library. The example shows the text of libstdc++.
## Shared memory allocation
With shmem, `NewMessage(size)` allocates the message in the shared memory segment. If the segment
does not have enough free memory, the transport throws
[`MessageBadAlloc`](/api/fair/mq/MessageBadAlloc/). These options change the behavior:
| Option | Default | Effect |
| --- | --- | --- |
| `--shm-throw-bad-alloc` | `true` | With `false`, the transport tries again without a limit. `--bad-alloc-max-attempts` then has no effect. |
| `--bad-alloc-max-attempts` | Not set (1 attempt) | The number of attempts before the exception. `-1` means no limit. `0` has the same effect as `1`. |
| `--bad-alloc-attempt-interval` | `50` | The time between two attempts, in ms. |
| `--shm-segment-size` | `2147483648` (2 GiB) | A message larger than the segment always throws `MessageBadAlloc` at once. |
An attempt that waits ends with `MessageBadAlloc` when a transition interrupts the transport. The
test `ShmAllocation.MaxAttempts` fills a segment and expects the exception after four attempts:
<Snippet file="test/transport/_shm_allocation.cxx" start="TEST_P(ShmAllocation, MaxAttempts)" />
For the size of the segment, see [Tune shared memory](/shmem/tuning/).
## Connect timeout
In `CONNECTING`, the device tries to connect each channel with the method `connect`. If a connect
fails, the device waits 50 ms, reads the address property again and tries again. After
`--init-timeout` seconds (default 120), the device throws `std::runtime_error` and goes to `ERROR`:
```txt
could not connect all channels after 120 attempts
following channels are still invalid:
```
The number in the first line is the value of `init-timeout` in seconds, not the number of attempts.
A zeromq or shmem connect succeeds also when the peer does not exist yet. Thus the retries help
when the address is not valid yet, for example when a controller sets it later.
In `BINDING`, the device tries each channel once. With the channel property `autoBind` (default
`true`), a tcp channel that cannot bind to its port tries random ports. If a channel cannot bind,
the device throws an exception with the text
`… of the binding channels could not initialize. Initial configuration incomplete.`
## When a peer stops or restarts
FairMQ does not watch the peers of a channel. When a peer process ends, FairMQ does not report it
to your device. The zeromq and the shmem transport both send through ZeroMQ sockets, so this section
applies to both. A statement marked "ZeroMQ behavior" comes from the ZeroMQ documentation, not from
the code of FairMQ.
### A peer ends while the device sends or receives
`Send()` and `Receive()` return `TransferCode::error` when the ZeroMQ socket reports an error other
than `EAGAIN` or `EINTR`, for example after the end of its context
([zeromq/Common.h](/source/fairmq/zeromq/Common.h/#L79-L88)). A peer that ends does not cause such an
error (ZeroMQ behavior).
The socket waits in steps of 100 ms, and after each step it checks only for an interruption and for
the end of the timeout ([zeromq/Common.h](/source/fairmq/zeromq/Common.h/#L64-L77)). Thus a peer that
ends looks like a peer that is slow:
| Timeout | `Send()` | `Receive()` |
| --- | --- | --- |
| `-1` | Returns the size when ZeroMQ puts the message into a queue. If no queue has space, it waits until a queue has space or a transition interrupts it. | Waits until a message arrives, or until a transition interrupts it. |
| `0` or more | Returns `TransferCode::timeout` when no queue has space before the timeout ends. | Returns `TransferCode::timeout` when no message arrives before the timeout ends. |
The test device `TransferTimeout` (see [Timeout for one call](#timeout-for-one-call)) shows the
second row for channels without a peer.
A successful `Send()` does not tell you that the peer received the message. ZeroMQ put it into a
queue. These messages can be lost when a peer ends:
- The messages in the queues of the process that ends. The queues are in the memory of the process.
- The messages in the queue of a socket that binds, for the peer that disconnects. ZeroMQ removes
this queue (ZeroMQ behavior).
- The messages that a `pub` socket sends while no `sub` socket is connected. ZeroMQ drops them
(ZeroMQ behavior). Only the zeromq transport has `pub` and `sub`.
A socket that connects keeps its queue while the peer is away. It sends the messages when the
connection comes back (ZeroMQ behavior). A `push` socket that binds sends new messages only to the
peers that remain (ZeroMQ behavior). A `push` socket that connects to several peers continues to put messages into the
queue of the peer that ended, until this queue is full (ZeroMQ behavior). FairMQ does not set the
ZeroMQ option `ZMQ_IMMEDIATE`, which changes this.
With `req` and `rep` and the timeout `-1`, a request can wait forever. If the `rep` peer ends before it replies,
`Receive()` on the `req` channel waits or returns `TransferCode::timeout`. After that, ZeroMQ refuses
the next `Send()` on the `req` socket, because the socket waits for the reply (ZeroMQ behavior). This
`Send()` returns `TransferCode::error`, and the log shows `Failed transfer on socket …`. The device
makes its sockets only in `BINDING` and `CONNECTING`. Thus the controller must reset the device and
take it through `INITIALIZING DEVICE`, `BINDING` and `CONNECTING` again.
### Find out if a peer is connected
[`GetNumberOfConnectedPeers()`](/api/fair/mq/Channel/#GetNumberOfConnectedPeers) of a channel returns
the number of connections of its socket. The socket counts the ZeroMQ events "connected",
"accepted" and "disconnected" when you call the function
([zeromq/Common.h](/source/fairmq/zeromq/Common.h/#L238-L264)). The test `ConnectedPeers.Pair` shows
that the count goes back to 0 when the peer closes its channel:
<Snippet file="test/channel/_channel.cxx" start="auto testConnectedPeers(" />
Call the function in the thread that uses the channel. See
[What is thread-safe](/concepts/threads/#what-is-thread-safe).
### The peer starts again
- **Your device connects, and the peer binds.** ZeroMQ connects again by itself (ZeroMQ behavior).
Your device stays in its state. For a `tcp://` address, the device resolves the host name once, in
`CONNECTING`, and gives the IP address to ZeroMQ
([Device.cxx](/source/fairmq/Device.cxx/#L321-L331)). Thus the peer must start again on the same
host and port.
- **Your device binds, and the peer connects.** ZeroMQ accepts the new connection (ZeroMQ
behavior). Your device does nothing.
- **The peer binds to another port.** If the port is not free and `autoBind` is `true`, the peer
binds to a random port ([Channel.cxx](/source/fairmq/Channel.cxx/#L346-L386)). The connecting
device does not find it there. Set `autoBind=false` for a peer that can start again. Then its bind
fails, and it goes to `ERROR`.
- **The shmem transport.** The new peer must use the same `--session`. Then it opens the segments and
regions that exist. The transport does not check the session of a message. See
[Keep two topologies apart](/shmem/sessions/#keep-two-topologies-apart).
### The binding peer starts after the connecting device
The connecting device does not wait for the peer. In `CONNECTING`, a zeromq or shmem connect
succeeds also when no socket binds at the address (ZeroMQ behavior, see [Connect timeout](#connect-timeout)). The
device goes on to `RUNNING`. ZeroMQ connects when the peer binds (ZeroMQ behavior). Until then:
- `Send()` puts messages into the queue of the socket, up to the limit of `sndBufSize` (default
1000). Then it waits or returns `TransferCode::timeout` (ZeroMQ behavior).
- `Receive()` waits, or returns `TransferCode::timeout`.
Thus the start order of the processes does not matter, if the addresses are fixed. The test
`MultipleDevices.TwoInSameProcess` starts a connecting sender and a binding receiver at the same
time, in no fixed order. If the connecting device closes its socket before the peer binds, ZeroMQ
keeps the queued messages for the time of the channel property `linger` (default 500 ms) and then
drops them (ZeroMQ behavior). See [Stop a topology without losing messages](/guides/end-of-run/).
### Shared memory after a peer ends
With shmem, the data of a message is a block in a segment. After a successful `Send()`, the message
of the sender no longer owns the block. Its destructor does not free it
([shmem/Message.h](/source/fairmq/shmem/Message.h/#L372-L411)). The receiver frees the block when it
destroys or rebuilds the received message and the reference count was 1. Only the process that holds
the last message of a block frees the block. Thus:
| Case | What happens to the block |
| --- | --- |
| The receiver crashes while it holds the message. | The block stays allocated. |
| The receiver ends before it receives the message. | If the metadata message is lost with a queue (see above), the block stays allocated. If the connecting socket of the sender keeps the message, the next receiver gets it and frees the block. |
| The sender ends after `Send()`, and the receiver gets the message. | The data is valid. The segment does not belong to the sender. The receiver frees the block. |
| A process crashes while it holds one of several copies (`Copy()`). | The reference count does not get to 1. The block stays allocated after the other copies are destroyed. |
| A block of an unmanaged region stays allocated in one of these cases. | The creator of the region gets no callback for this block. |
A block that stays allocated stays until the segment is removed, or until
`fairmq-shmmonitor --reset-content` (experimental) resets the segment while no device uses it. If
peers crash often, the segment fills, and `NewMessage()` throws `MessageBadAlloc`. See
[Shared memory allocation](#shared-memory-allocation).
The segments belong to the session, not to the process that created them. Each shmem transport
increments the device counter in the management segment when it starts
([shmem/Manager.h](/source/fairmq/shmem/Manager.h/#L144-L153)). Its destructor decrements the
counter. When the counter is 0, this transport removes all objects of the session, unless
`--shm-no-cleanup` is `true` ([shmem/Manager.h](/source/fairmq/shmem/Manager.h/#L773-L798)). Thus:
- When the creator of a segment ends normally and other devices run, the segment stays. The other
devices continue.
- A process that ends without the destructor, for example after a crash or `kill -9`, does not
decrement the counter. The topology continues, but the last device does not remove the memory at
the end. See [The device counter and cleanup](/shmem/sessions/#the-device-counter-and-cleanup).
- A peer that starts again with the same session opens the segments and increments the counter
again.
### Rules for peers that can stop
<Steps>
1. Give a timeout to `Send()` and `Receive()` on a channel whose peer can stop. With `-1`, only a
transition ends the wait.
2. Check the return value of each transfer. Decide in your code when a peer is lost, for example
after a number of timeouts. FairMQ does not decide it.
3. Do not take a successful `Send()` as a delivery. If the data must arrive, let the receiver
confirm it, with `req`/`rep` or with an acknowledgement on a second channel. The example
[multiple-transports](/examples/multiple-transports/) sends acknowledgements on its channel `ack`.
4. Give fixed addresses to the peers that can start again.
5. With shmem, start the new process with the same `--session` as the other devices.
6. After a crash, start the peer again, or stop the topology. When all devices of the session have
stopped, look for the memory that stays and remove it. See [Monitor and clean up](/shmem/monitor/).
With `--shm-monitor true`, a daemon removes it when the heartbeats of the session stop.
</Steps>
## Problems that can occur
- **The device stops slowly after Ctrl-C:** a hook waits in `std::this_thread::sleep_for()` or in a
long computation. Use `WaitFor()` for pauses, and check `NewStatePending()` in long loops.
- **A timeout is longer than the value:** the sockets wait in steps of 100 ms. Use multiples of
100 ms.
- **The device goes to `ERROR` in `INITIALIZING TASK` with `Config has no key: …`:** the option does
not exist. `GetProperty<T>(key)` throws `PropertyNotFoundError`. Register the option in
`addCustomOptions()`, or use `GetProperty<T>(key, default)`.
- **`boost::bad_any_cast` in a hook:** the type in `GetProperty<T>()` is not the type of the option.
Use the type from the option definition.
- **The device ignores the timeout of a channel:** the channel came from `AddChannel()`. See the
caution above.
- **The device has no channels, and the log shows an error at the start of `INITIALIZING DEVICE`:**
the configuration parser failed. The config plugin logs the error and continues. Correct the file
of `--mq-config` or the values of `--channel-config`.
- **A device waits forever after its peer crashed:** the transfers use the timeout `-1`. Give a
timeout. See [When a peer stops or restarts](#when-a-peer-stops-or-restarts).
- **The free memory of the shmem segment gets smaller after each crash of a peer:** the blocks of
the crashed process stay allocated. Stop the topology, and remove the shared memory. See
[Shared memory after a peer ends](#shared-memory-after-a-peer-ends).
## Related pages
- [Transfer codes and errors](/reference/transfer-codes/): all codes and all exceptions of FairMQ.
- [Behavior of each socket type](/concepts/channels/#behavior-of-each-socket-type): full queues, `pub` drops and `req` errors.
- [Device states](/concepts/states/): `ERROR` and the transitions.
- [Receive data with callbacks or loops](/guides/receive-data/): the end of `RUNNING`.
- [Channel properties](/reference/channel-properties/): `sndTimeoutMs`, `rcvTimeoutMs` and the other
properties.
- [Tune shared memory](/shmem/tuning/): segment size and allocation.

View File

@@ -0,0 +1,207 @@
---
title: 'Check code with fairmq-tidy'
description: 'Find the deprecated FairMQ* type names in your project with fairmq-tidy, fix them, and run the check at each build and in CI.'
sidebar:
order: 11
code: [fairmq/tidy/ModernizeNonNamespacedTypes.h, fairmq/tidy/Tool.h]
---
import { Steps } from '@astrojs/starlight/components';
This guide runs `fairmq-tidy` on a CMake project that uses FairMQ. The result is a list of all places that use a deprecated `FairMQ*` type name. A CMake target then checks the code at each build. The reference of the tool is on [fairmq-tidy](/tools/fairmq-tidy/).
## Before you start
- You need a FairMQ installation with the tool. Build FairMQ with `-DBUILD_TIDY_TOOL=ON`, see [Build fairmq-tidy](/tools/fairmq-tidy/#build-fairmq-tidy).
- Your project must use the Makefile or the Ninja generator of CMake. The other generators do not write a compilation database.
Make sure that the tool runs:
```sh
fairmq-tidy --help
```
## Make a compilation database
The tool reads the compile command of each file, with the include paths and flags, from the file `compile_commands.json`.
<Steps>
1. Configure your project with `CMAKE_EXPORT_COMPILE_COMMANDS`:
```sh
cmake -S . -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
```
2. Make sure that the file `build/compile_commands.json` exists.
</Steps>
The database has an entry for each source file. A header file has no entry. The tool checks a header when it checks a source file that includes the header.
## Run the check
<Steps>
1. Go to the source directory of your project. The tool finds a relative file name from the current directory.
2. Check one file:
```sh
fairmq-tidy -p build src/mydevice.cxx
```
3. Check all source files. Give several file names:
```sh
fairmq-tidy -p build src/*.cxx
```
With more than one file, the tool prints a line before each file. An example is `[1/3] Processing file /home/me/myproject/src/mydevice.cxx.`
4. Write the output to a file. The tool writes to the standard error stream:
```sh
fairmq-tidy -p build src/*.cxx 2> tidy.log
```
</Steps>
## Read the output
Each finding has a warning line, the source line with a marker under the old name, and a fix-it hint with the new name:
```txt
/home/me/myproject/src/mydevice.cxx:3:25: warning: Modernize non-namespaced type 'FairMQDevice' with 'fair::mq::Device'. [fairmq-modernize-nonnamespaced-types]
3 | class MyDevice : public FairMQDevice
| ^~~~~~~~~~~~
| fair::mq::Device
/home/me/myproject/src/mydevice.cxx:5:21: warning: Modernize non-namespaced type 'FairMQMessagePtr' with 'fair::mq::MessagePtr' (aka 'unique_ptr<Message>'). [fairmq-modernize-nonnamespaced-types]
5 | bool HandleData(FairMQMessagePtr& msg, int);
| ^~~~~~~~~~~~~~~~
| fair::mq::MessagePtr
```
- `/home/me/myproject/src/mydevice.cxx:3:25` is the file, the line and the column of the old name. The file name is the name in the compilation database. CMake writes absolute paths.
- `'FairMQDevice'` is the old name. `'fair::mq::Device'` is the new name. For some names, `(aka …)` shows the full type.
- `[fairmq-modernize-nonnamespaced-types]` is the name of the check. Use it to search the log.
- With Clang 18, most findings appear two times at the same location. The example shows one copy. Fix each finding one time.
- After each file, the tool prints the number of warnings, for example `4 warnings generated.` This number includes the second copies.
- A finding in a header appears for each source file that includes the header.
A finding in `runFairMQDevice.h` of FairMQ means that your code includes this old header. Do not change the FairMQ header. Move your code to `runDevice.h`, see [Replace runFairMQDevice.h](/guides/migrate-names/#replace-runfairmqdeviceh).
The tool does not find all old names. For example, it does not find `fairmq_free_fn`, `InputMsgCallback` and the old headers. See [Names that the check does not find](/tools/fairmq-tidy/#names-that-the-check-does-not-find).
## Apply the fixes
`fairmq-tidy` does not change your files. Do these steps for each finding:
<Steps>
1. Open the file at the line and the column of the warning.
2. Replace the old name with the text of the fix-it hint, for example `FairMQDevice` with `fair::mq::Device`.
3. Replace the old `#include` lines. Use the table [Headers](/guides/migrate-names/#headers).
4. Run `fairmq-tidy` again. Continue until it prints no warning.
5. Build your project with `-Werror=deprecated-declarations`. The compiler then stops at the old names that the tool does not find.
</Steps>
To get a list of all fixes, add the Clang option `-fdiagnostics-parseable-fixits`:
```sh
fairmq-tidy -p build --extra-arg=-fdiagnostics-parseable-fixits src/*.cxx 2>&1 | grep '^fix-it:' | sort -u
```
```txt
fix-it:"/home/me/myproject/src/mydevice.cxx":{3:25-3:37}:"fair::mq::Device"
fix-it:"/home/me/myproject/src/mydevice.cxx":{5:21-5:37}:"fair::mq::MessagePtr"
```
Each line gives the file, the range of the old name (`line:column-line:column`) and the new text. `sort -u` removes the second copy of each finding.
## Check the code at each build
The CMake module `FairMQTidy.cmake` adds the check to a target. The build then runs the tool after it builds the target. The check includes only the source files of the target that end in `.cpp` or `.cxx`.
<Steps>
1. Find FairMQ with the component `tidy_tool`. CMake stops if FairMQ has no `fairmq-tidy`:
```cmake
find_package(FairMQ REQUIRED COMPONENTS tidy_tool)
```
2. Turn on the compilation database. Do this before you add the targets:
```cmake
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
```
3. Include the module and call `fairmq_target_tidy()` for each target:
```cmake
include(FairMQTidy)
add_executable(mydevice src/mydevice.cxx)
target_link_libraries(mydevice PRIVATE FairMQ::FairMQ)
fairmq_target_tidy(TARGET mydevice)
```
4. Build the project:
```sh
cmake --build build
```
</Steps>
For each source file, the build prints a line like this one and then the findings:
```txt
fairmq-tidy: Analyzing source file 'src/mydevice.cxx' of target 'mydevice'
```
To build one target and run its check, build the target `fairmq-tidy-<target>`:
```sh
cmake --build build --target fairmq-tidy-mydevice
```
The build runs the check again each time the target changes. Findings do not stop the build. If the tool fails on a file, the build fails.
## Fail a CI job on findings
The exit code of `fairmq-tidy` is `0` also when it finds old names. To fail a CI job on findings, search the build log for the name of the check:
```sh
set -eo pipefail
cmake --build build 2>&1 | tee build.log
if grep -q "fairmq-modernize-nonnamespaced-types" build.log; then
echo "fairmq-tidy found deprecated FairMQ names"
exit 1
fi
```
`set -eo pipefail` stops the script with the exit code of `cmake --build`, so that a failed build also fails the job.
## Problems that can occur
| Message | Cause | Solution |
| --- | --- | --- |
| `CMAKE_EXPORT_COMPILE_COMMANDS is not enabled. Skipping.` | The variable is off when `fairmq_target_tidy()` runs. | Set `CMAKE_EXPORT_COMPILE_COMMANDS` to `ON` before the call. |
| `Skipping <file>. Compile command not found.` (exit code 2) | The file has no entry in the compilation database. | Check the `-p` directory. Give source files of the project, not headers. |
| `error: no such file or directory: '-Wno-everything'` | The compilation database has no entry for the file, for example a header. Clang 18 takes the compile command of a similar file. The tool checks the file, but it also shows the compiler warnings. | Give the source files that the database lists. |
| `fatal error: '<header>' file not found`, then `Error while processing <file>.` (exit code 1) | Clang does not find a header. | Add the include path with `--extra-arg=-I<dir>`. For the headers of Clang itself, add `--extra-arg-before=-I$(clang -print-resource-dir)/include`. |
| `Error while trying to load a compilation database` and `Running without flags.` | The tool did not find `compile_commands.json`. | Give the build directory with `-p`. |
| `no such file or directory: '…$<1:…'` in the CMake build | `fairmq_target_tidy()` breaks the command line when its list of extra arguments has two or more items. With GCC, the function always adds one item. | Do not use `EXTRA_ARGS` with GCC. With other compilers, give at most one argument. See [The CMake function](/tools/fairmq-tidy/#the-cmake-function-fairmq_target_tidy). |
## Related pages
- [fairmq-tidy](/tools/fairmq-tidy/): the check, the command line, the exit codes and the CMake function.
- [Move from the FairMQ* names](/guides/migrate-names/): all old names and their replacements.
- [Use FairMQ in a CMake project](/start/cmake/): `find_package(FairMQ)` and the targets.

View File

@@ -0,0 +1,195 @@
---
title: 'Move from the FairMQ* names'
description: 'Replace the deprecated FairMQ* headers, type names and members with the fair::mq names. The complete list of old names and their replacements.'
sidebar:
order: 12
code: [fairmq/FwdDecls.h, fairmq/Device.h, fairmq/Message.h, fairmq/UnmanagedRegion.h, fairmq/runFairMQDevice.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps, Tabs, TabItem } from '@astrojs/starlight/components';
The API of FairMQ is in the namespace `fair::mq`, and its headers are in the directory `fairmq/`. The old global names like `FairMQDevice` and the old headers like `<FairMQDevice.h>` still compile, but the compiler warns. This guide moves your code to the new names and lists each old name with its replacement.
## Before and after
```cpp title="mydevice.cxx (old)"
#include <FairMQDevice.h>
class MyDevice : public FairMQDevice
{
bool HandleData(FairMQMessagePtr& msg, int);
};
```
```cpp title="mydevice.cxx (new)"
#include <fairmq/Device.h>
class MyDevice : public fair::mq::Device
{
bool HandleData(fair::mq::MessagePtr& msg, int);
};
```
## Move your code
<Steps>
1. Replace the old `#include` lines. Use the table [Headers](#headers).
2. Replace the old type names. Use the table [Type names](#type-names). [fairmq-tidy](/guides/fairmq-tidy/) finds most of them for you.
3. If your `main()` comes from `runFairMQDevice.h`, move to `runDevice.h`. See [Replace runFairMQDevice.h](#replace-runfairmqdeviceh).
4. Replace the deprecated functions and members. Use the table [Functions and members](#functions-and-members).
5. Build with `-Werror=deprecated-declarations`. The compiler then stops at each remaining use of a deprecated name:
```sh
cmake -S . -B build -DCMAKE_CXX_FLAGS="-Werror=deprecated-declarations"
cmake --build build
```
</Steps>
## How the compiler warns
An old header contains a `#pragma GCC warning`. An old type name or member has the attribute `[[deprecated("…")]]`, and the compiler prints the text of the attribute. For the old code above, GCC and Clang print these warnings (the paths are shorter here):
<Tabs>
<TabItem label="GCC">
```txt
FairMQDevice.h:13:21: warning: Deprecated header: Use <fairmq/Device.h> instead
mydevice.cxx:5:47: warning: 'using FairMQMessagePtr = using fair::mq::MessagePtr = class std::unique_ptr<fair::mq::Message>' is deprecated: Use fair::mq::MessagePtr [-Wdeprecated-declarations]
```
</TabItem>
<TabItem label="Clang">
```txt
FairMQDevice.h:13:13: warning: Deprecated header: Use <fairmq/Device.h> instead [-W#pragma-messages]
mydevice.cxx:3:25: warning: 'FairMQDevice' is deprecated: Use fair::mq::Device [-Wdeprecated-declarations]
mydevice.cxx:5:21: warning: 'FairMQMessagePtr' is deprecated: Use fair::mq::MessagePtr [-Wdeprecated-declarations]
```
</TabItem>
</Tabs>
The compiler does not show all uses:
- GCC 13 does not warn for a deprecated alias in a list of base classes, for example `class MyDevice : public FairMQDevice`. Clang and fairmq-tidy find it.
- [`<fairmq/FwdDecls.h>`](/source/fairmq/FwdDecls.h/#L29-L43) declares twelve of the old names again, without the attribute. A file that includes only this header gets no warning for these names.
- An old header warns only if the file did not include the new header before. `FairMQLogger.h` always warns. `runFairMQDevice.h` does not warn.
- `FairMQDevicePtr` of `runFairMQDevice.h` has no attribute.
## Headers
Each old header includes the new header, so the old `#include` lines still work. The include directories of an installed `FairMQ::FairMQ` are `include` and `include/fairmq`, so the old headers also work with the prefix `fairmq/`, for example `<fairmq/FairMQDevice.h>`.
| Old header | New header | Warning |
| --- | --- | --- |
| [`<FairMQChannel.h>`](/source/fairmq/FairMQChannel.h/) | `<fairmq/Channel.h>` | yes |
| [`<FairMQDevice.h>`](/source/fairmq/FairMQDevice.h/) | `<fairmq/Device.h>` | yes |
| [`<FairMQLogger.h>`](/source/fairmq/FairMQLogger.h/) | `<fairlogger/Logger.h>` (FairLogger) | yes, always |
| [`<FairMQMessage.h>`](/source/fairmq/FairMQMessage.h/) | `<fairmq/Message.h>` | yes |
| [`<FairMQParts.h>`](/source/fairmq/FairMQParts.h/) | `<fairmq/Parts.h>` | yes |
| [`<FairMQPoller.h>`](/source/fairmq/FairMQPoller.h/) | `<fairmq/Poller.h>` | yes |
| [`<FairMQSocket.h>`](/source/fairmq/FairMQSocket.h/) | `<fairmq/Socket.h>` | yes |
| [`<FairMQTransportFactory.h>`](/source/fairmq/FairMQTransportFactory.h/) | `<fairmq/TransportFactory.h>` | yes |
| [`<FairMQUnmanagedRegion.h>`](/source/fairmq/FairMQUnmanagedRegion.h/) | `<fairmq/UnmanagedRegion.h>` | yes |
| [`<options/FairMQProgOptions.h>`](/source/fairmq/options/FairMQProgOptions.h/) | `<fairmq/ProgOptions.h>` | yes |
| [`<runFairMQDevice.h>`](/source/fairmq/runFairMQDevice.h/) | `<fairmq/runDevice.h>` | no |
## Type names
The table is in the order of the headers that declare the deprecated alias. The column fairmq-tidy shows if [the check](/tools/fairmq-tidy/#names-that-the-check-finds) finds the name (with Clang 18).
| Old name | New name | Declared in | fairmq-tidy |
| --- | --- | --- | --- |
| `FairMQChannel` | [`fair::mq::Channel`](/api/fair/mq/Channel/) | `Channel.h` | yes |
| `FairMQChannelMap` | [`fair::mq::ChannelMap`](/api/fair/mq/#ChannelMap) | `Device.h` | yes |
| `InputMsgCallback` | [`fair::mq::InputMsgCallback`](/api/fair/mq/#InputMsgCallback) | `Device.h` | no |
| `InputMultipartCallback` | [`fair::mq::InputMultipartCallback`](/api/fair/mq/#InputMultipartCallback) | `Device.h` | no |
| `FairMQDevice` | [`fair::mq::Device`](/api/fair/mq/Device/) | `Device.h` | yes |
| `fair::mq::FairMQMemoryResource` | [`fair::mq::MemoryResource`](/api/fair/mq/MemoryResource/) | `MemoryResources.h` | no |
| `fairmq_free_fn` | [`fair::mq::FreeFn`](/api/fair/mq/#FreeFn) | `Message.h` | no |
| `FairMQMessage` | [`fair::mq::Message`](/api/fair/mq/Message/) | `Message.h` | yes |
| `FairMQMessagePtr` | [`fair::mq::MessagePtr`](/api/fair/mq/#MessagePtr) | `Message.h` | yes |
| `FairMQParts` | [`fair::mq::Parts`](/api/fair/mq/Parts/) | `Parts.h` | yes |
| `FairMQPoller` | [`fair::mq::Poller`](/api/fair/mq/Poller/) | `Poller.h` | yes |
| `FairMQPollerPtr` | [`fair::mq::PollerPtr`](/api/fair/mq/#PollerPtr) | `Poller.h` | yes |
| `FairMQProgOptions` | [`fair::mq::ProgOptions`](/api/fair/mq/ProgOptions/) | `ProgOptionsFwd.h` | yes |
| `FairMQSocket` | [`fair::mq::Socket`](/api/fair/mq/Socket/) | `Socket.h` | yes |
| `FairMQSocketPtr` | [`fair::mq::SocketPtr`](/api/fair/mq/#SocketPtr) | `Socket.h` | yes |
| `FairMQTransportFactory` | [`fair::mq::TransportFactory`](/api/fair/mq/TransportFactory/) | `TransportFactory.h` | yes |
| `FairMQTransportFactoryError` | [`fair::mq::TransportFactoryError`](/api/fair/mq/TransportFactoryError/) | `TransportFactory.h` | yes |
| `FairMQRegionEvent` | [`fair::mq::RegionEvent`](/api/fair/mq/RegionEvent/) | `UnmanagedRegion.h` | yes |
| `FairMQRegionInfo` | [`fair::mq::RegionInfo`](/api/fair/mq/RegionInfo/) | `UnmanagedRegion.h` | yes |
| `FairMQRegionBlock` | [`fair::mq::RegionBlock`](/api/fair/mq/RegionBlock/) | `UnmanagedRegion.h` | yes |
| `FairMQRegionCallback` | [`fair::mq::RegionCallback`](/api/fair/mq/#RegionCallback) | `UnmanagedRegion.h` | yes |
| `FairMQRegionBulkCallback` | [`fair::mq::RegionBulkCallback`](/api/fair/mq/#RegionBulkCallback) | `UnmanagedRegion.h` | yes |
| `FairMQRegionEventCallback` | [`fair::mq::RegionEventCallback`](/api/fair/mq/#RegionEventCallback) | `UnmanagedRegion.h` | yes |
| `FairMQUnmanagedRegion` | [`fair::mq::UnmanagedRegion`](/api/fair/mq/UnmanagedRegion/) | `UnmanagedRegion.h` | yes |
| `FairMQUnmanagedRegionPtr` | [`fair::mq::UnmanagedRegionPtr`](/api/fair/mq/#UnmanagedRegionPtr) | `UnmanagedRegion.h` | yes |
| `FairMQRegionConfig` | [`fair::mq::RegionConfig`](/api/fair/mq/RegionConfig/) | `UnmanagedRegion.h` | yes |
| `FairMQDevicePtr` | `std::unique_ptr<fair::mq::Device>` as the return type of `getDevice()` | `runFairMQDevice.h` | yes, as `fair::mq::Device *` |
All old names are global, except `fair::mq::FairMQMemoryResource`. All names in the table except `FairMQDevicePtr` have the attribute `[[deprecated]]`.
## Replace runFairMQDevice.h
[`runFairMQDevice.h`](/source/fairmq/runFairMQDevice.h/) and [`runDevice.h`](/source/fairmq/runDevice.h/) both contain a `main()` function. Your code gives the two functions `getDevice()` and `addCustomOptions()`. The signature of `getDevice()` is different:
| Header | Declaration of `getDevice()` |
| --- | --- |
| `runFairMQDevice.h` | `FairMQDevicePtr getDevice(const fair::mq::ProgOptions& config);` with `FairMQDevicePtr` = `fair::mq::Device*` |
| `runDevice.h` | `std::unique_ptr<fair::mq::Device> getDevice(fair::mq::ProgOptions& config);` |
`addCustomOptions(boost::program_options::options_description&)` is the same in both headers.
```cpp title="Old code"
#include <runFairMQDevice.h>
FairMQDevicePtr getDevice(const fair::mq::ProgOptions& /*config*/)
{
return new MyDevice();
}
```
The new code returns a `std::unique_ptr`, and the parameter is not `const`. The example 1-1 uses the new header:
<Snippet file="examples/1-1/sampler.cxx" start="#include <fairmq/Device.h>" end="#include <fairmq/runDevice.h>" />
<Snippet file="examples/1-1/sampler.cxx" start="std::unique_ptr<fair::mq::Device> getDevice" />
## Functions and members
The compiler warns for these members too. The column "Declared in" names the header in `fairmq/`.
| Old | New | Declared in |
| --- | --- | --- |
| [`Device::fChannels`](/api/fair/mq/Device/#fChannels) | [`GetChannels()`](/api/fair/mq/Device/#GetChannels) | `Device.h` |
| [`Device::GetStateName(state)`](/api/fair/mq/Device/#GetStateName) | [`fair::mq::GetStateName(state)`](/api/fair/mq/#GetStateName) of `<fairmq/States.h>` | `Device.h` |
| [`Device::GetTransitionName(transition)`](/api/fair/mq/Device/#GetTransitionName) | [`fair::mq::GetTransitionName(transition)`](/api/fair/mq/#GetTransitionName) of `<fairmq/States.h>` | `Device.h` |
| [`Device::Serialize<S>(msg, data, args...)`](/api/fair/mq/Device/#Serialize) | `S().Serialize(msg, data, args...)` | `Device.h` |
| [`Device::Deserialize<D>(msg, data, args...)`](/api/fair/mq/Device/#Deserialize) | `D().Deserialize(msg, data, args...)` | `Device.h` |
| [`Parts::AddPart(Message* msg)`](/api/fair/mq/Parts/#AddPart) | [`Parts::AddPart(MessagePtr msg)`](/api/fair/mq/Parts/#AddPart-2) | `Parts.h` |
| [`Parts::AtRef(index)`](/api/fair/mq/Parts/#AtRef) | `*(parts.At(index))` with [`At()`](/api/fair/mq/Parts/#At) | `Parts.h` |
| [`Socket::Close()`](/api/fair/mq/Socket/#Close) | Destroy the socket. Its destructor closes it. | `Socket.h` |
| [`shmem::Socket::GetConstant()`](/api/fair/mq/shmem/Socket/#GetConstant) and `zmq::Socket::GetConstant()` | `fair::mq::zmq::getConstant()` of `<fairmq/zeromq/Common.h>` | `shmem/Socket.h`, `zeromq/Socket.h` |
## CMake names
The CMake package is `FairMQ`. Link your targets with `FairMQ::FairMQ`. The executables of FairMQ are imported targets with the same prefix, for example `FairMQ::fairmq-bsampler`. See [Use FairMQ in a CMake project](/start/cmake/).
## Automate the search with fairmq-tidy
`fairmq-tidy` finds the uses of most old type names and shows the new name for each one. It does not look at the `#include` lines and the members, and it does not change your files. See [Check code with fairmq-tidy](/guides/fairmq-tidy/).
## Related pages
- [Check code with fairmq-tidy](/guides/fairmq-tidy/): find the old type names in a project.
- [fairmq-tidy](/tools/fairmq-tidy/): the check, the command line and the CMake function.
- [Your first device](/start/first-device/): a device with the current API.
- [Use FairMQ in a CMake project](/start/cmake/): the package and its targets.

View File

@@ -0,0 +1,173 @@
---
title: 'Use std::pmr memory resources'
description: 'Fill a container in the message memory of a transport with a std::pmr allocator, and send it as a message without a copy.'
sidebar:
order: 5
code: [fairmq/MemoryResources.h, fairmq/MemoryResources.cxx, fairmq/MemoryResourceTools.h, fairmq/TransportFactory.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
Each transport factory has a memory resource of the C++17 type `std::pmr::memory_resource`. A
container that allocates from this resource keeps its data in a message buffer of the transport.
[`fair::mq::getMessage()`](/api/fair/mq/#getMessage) then makes a message from the container
without a copy, and you send it as a normal message.
## The names in FairMQ
[`MemoryResources.h`](/source/fairmq/MemoryResources.h/) declares `namespace pmr = std::pmr;` in
`fair::mq`. Thus `fair::mq::pmr::polymorphic_allocator<T>` is `std::pmr::polymorphic_allocator<T>`,
and `fair::mq::pmr::vector<T>` is `std::pmr::vector<T>`. Before v1.10.0, `fair::mq::pmr` was
`boost::container::pmr`. Code that uses `boost::container::pmr` types with the FairMQ resources does
not compile with v1.10.0 and later. Use the `std::pmr` types.
| Name | Header | What it is |
| --- | --- | --- |
| [`fair::mq::MemoryResource`](/api/fair/mq/MemoryResource/) | `MemoryResources.h` | Interface. A `pmr::memory_resource` that can give the message of a buffer. |
| [`fair::mq::ChannelResource`](/api/fair/mq/ChannelResource/) | `MemoryResources.h` | The memory resource of a transport factory. Each allocation is one message of this transport. |
| [`FairMQMemoryResource`](/api/fair/mq/#FairMQMemoryResource) | `MemoryResources.h` | Deprecated name of `fair::mq::MemoryResource`. |
| [`fair::mq::BytePmrAllocator`](/api/fair/mq/#BytePmrAllocator) | `MemoryResourceTools.h` | `pmr::polymorphic_allocator<fair::mq::byte>`, where [`fair::mq::byte`](/api/fair/mq/#byte) is `unsigned char`. |
| [`fair::mq::getMessage()`](/api/fair/mq/#getMessage) | `MemoryResourceTools.h` | Makes a message from a container. |
`TransportFactory.h` includes `MemoryResources.h`. For `getMessage()` and `BytePmrAllocator`,
include `<fairmq/MemoryResourceTools.h>`. For the deprecated names, see
[Move from the FairMQ\* names](/guides/migrate-names/).
## The memory resource of a transport
[`TransportFactory::GetMemoryResource()`](/api/fair/mq/TransportFactory/#GetMemoryResource) returns
a pointer to the `ChannelResource` of the factory. Each factory has its own resource, and each call
returns the same pointer. The test `MemoryResources.transportAllocatorMap` checks this:
<Snippet file="test/memory_resources/_memory_resources.cxx" start="auto allocZMQ = factoryZMQ->GetMemoryResource();" end="EXPECT_EQ(_tmp, allocZMQ);" />
The [conversion operator](/api/fair/mq/TransportFactory/#operator-ChannelResource2a) of the factory
gives the same pointer. Thus a factory reference can replace the pointer, for example in
`getMessage(std::move(v), *factory)`.
In a device, `Transport()->GetMemoryResource()` returns the resource of the default transport. For
the transport of one channel, use `GetChannel("data").Transport()->GetMemoryResource()`.
The `ChannelResource` gives each allocation to the transport
([MemoryResources.cxx](/source/fairmq/MemoryResources.cxx/#L18-L21)):
- An allocation of `n` bytes makes a message of `n` bytes with the requested alignment. The
resource keeps the message, with the address of its data as the key.
- A deallocation destroys the message of this address.
- Two resources are equal only if they are the same object.
- [`getNumberOfMessages()`](/api/fair/mq/ChannelResource/#getNumberOfMessages) returns the number of
messages that the resource keeps.
## Send a container without a copy
<Steps>
1. Include `<fairmq/MemoryResourceTools.h>`.
2. Get the memory resource of the transport of the channel that sends the data. With the resource
of another transport, `Send()` converts the message. See
[Send a message of another transport](/guides/several-transports/#send-a-message-of-another-transport).
3. Make a container with a pmr allocator on this resource, for example a `fair::mq::pmr::vector`.
4. Reserve the full size with `reserve()` before you add the elements.
5. Add the elements.
6. Call `getMessage(std::move(container))`. Do not use the container after this call.
7. Send the message.
</Steps>
The test `PmrMessage.FromContainerWithoutCopy` does these steps for each transport. Then it sends
the message on a channel and receives it:
<Snippet file="test/memory_resources/_memory_resources.cxx" start="TEST_P(PmrMessage, FromContainerWithoutCopy)" />
After `getMessage()`, the message has the address of the container data. For one exception of the
shmem transport, see the unused capacity in [Limits](#limits). The size of the message is `size()`
multiplied by the size of one element, and the resource keeps no message.
In a device, the same steps look like this:
```cpp
#include <fairmq/Device.h>
#include <fairmq/MemoryResourceTools.h>
#include <utility>
#include <vector>
struct Sampler : fair::mq::Device
{
bool ConditionalRun() override
{
auto* resource = GetChannel("data").Transport()->GetMemoryResource();
fair::mq::pmr::vector<float> values(resource);
values.reserve(1000);
for (int i = 0; i < 1000; ++i) {
values.push_back(0.5f * i);
}
fair::mq::MessagePtr msg(fair::mq::getMessage(std::move(values)));
return Send(msg, "data") >= 0;
}
};
```
## What `getMessage()` does
`getMessage(container, target)` moves the container into the function, and finds the resource of
its allocator ([MemoryResourceTools.h](/source/fairmq/MemoryResourceTools.h/#L25-L63)). Give the
container as an rvalue, for example `std::move(v)`. A call with an lvalue does not compile, because
the function uses `ContainerT::value_type` and `ContainerT` is then a reference type. The
optional `target` is a `fair::mq::MemoryResource*`. The result depends on the two resources:
| Resource of the container | `target` | Result |
| --- | --- | --- |
| A FairMQ resource | none, or the same resource | No copy. The message of the container buffer, with the size of the elements in the container. |
| A FairMQ resource | another FairMQ resource | A new message of the target transport with a copy of the data. The container frees its buffer. |
| Another `std::pmr` resource | a FairMQ resource | A new message of the target transport with a copy of the data. |
| Another `std::pmr` resource | none | Throws `std::runtime_error` with `Neither the container or target resource specified`. |
If the resource has no message for the container data, `getMessage()` copies the data into a new
message. This occurs for a container without a buffer. Examples are an empty vector without `reserve()`, and
a short `std::pmr::string` that keeps its characters in the string object.
The test `MemoryResources.getMessage` shows both results. The first message has the address of the
vector data. The second message, with the shmem factory as target, has a new address:
<Snippet file="test/memory_resources/_memory_resources.cxx" start="// test message creation on the same channel it was allocated with" end="EXPECT_EQ(messageArray[2], 6);" />
## Limits
- **Allocator.** The container must use a `pmr::polymorphic_allocator`, because `getMessage()`
calls `get_allocator().resource()`.
- **Contiguous data.** `getMessage()` uses `data()` and `size()` of the container. The buffer must
start at `data()`, as in `std::vector`.
- **Element type.** Use types that you can copy as bytes, for example numbers and structs of
numbers. `getMessage()` destroys the container, and with it the elements. The message keeps their
bytes. A receiver in another process also gets only the bytes.
- **Growth.** Each allocation makes a message. If the vector grows past its capacity, it allocates
a new message, copies the elements, and destroys the old message. Use `reserve()`.
- **Unused capacity.** `getMessage()` makes the message smaller with
[`SetUsedSize()`](/api/fair/mq/Message/#SetUsedSize). The zeromq transport keeps the unused memory
until it destroys the message. The shmem transport tries to give the unused memory back to the
segment. If this fails, it keeps the memory, or it copies the data into a new buffer if 1000000
bytes or more are unused.
- **Threads.** `ChannelResource` has no lock. All channels of one transport in a device share one
resource. Allocate and call `getMessage()` from one thread at a time.
- **Lifetime.** The resource is a member of the transport factory. Destroy the containers before the
factory. A device destroys its factories in the state `RESETTING DEVICE`.
- **Receive.** `getMessage()` is for the sender only. A received message is a normal message: read
it with `GetData()` and `GetSize()`.
## Related pages
- [Messages and multipart](/concepts/messages/): how to make, send and receive messages.
- [Transports](/concepts/transports/): the transport factories that own the memory resources.
- [How shared memory works](/shmem/how-it-works/): where the shmem transport keeps the message data.
- [Use channels without a device](/guides/channels-without-device/): the channels of the tests in this guide.
- [Send your own data types](/guides/send-data-types/): structs, arrays and serialized objects in messages.

View File

@@ -0,0 +1,187 @@
---
title: 'Poll several channels'
description: 'Wait with a poller until one of several channels can receive or send a message, and then serve the channels that are ready.'
sidebar:
order: 4
code: [fairmq/Poller.h, fairmq/Device.h, fairmq/TransportFactory.h, fairmq/zeromq/Poller.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
A poller waits until at least one of several channels can receive or send a message. With a poller,
one thread of your device serves several channels in `Run()`. It receives where a message waits,
and it sends where a peer can take a message.
If your device only receives, register data callbacks with [`OnData()`](/api/fair/mq/Device/#OnData)
instead. Then the device polls the channels itself. See
[Receive data with callbacks or loops](/guides/receive-data/).
## Poll channels in `Run()`
<Steps>
1. In `Run()`, make the poller with [`NewPoller()`](/api/fair/mq/Device/#NewPoller) and the names
of the channels. Make it once, before the loop.
2. In a loop, call [`Poll(timeout)`](/api/fair/mq/Poller/#Poll). The timeout is in milliseconds, for
example 100 ms.
3. After each `Poll()`, call [`CheckInput()`](/api/fair/mq/Poller/#CheckInput-2) for each channel
that receives. Call [`CheckOutput()`](/api/fair/mq/Poller/#CheckOutput-2) for each channel that
sends.
4. If a check returns `true`, call `Receive()` or `Send()` on this sub-channel.
5. Stop the loop when [`NewStatePending()`](/api/fair/mq/Device/#NewStatePending) returns `true`.
</Steps>
The sampler of the [multiple-channels example](/examples/multiple-channels/) sends on the channel
`data` and receives on the channel `broadcast` in one loop:
<Snippet file="examples/multiple-channels/sampler.cxx" start="void Run() override" />
`data` is a `push` socket, and `broadcast` is a `sub` socket. The start script gives the sampler
these channels:
<Snippet file="examples/multiple-channels/fairmq-start-ex-multiple-channels.sh.in" start='SAMPLER="fairmq' end="name=broadcast,type=sub" />
The example uses the zeromq transport only, because shmem has no `pub` and `sub` sockets. The
sampler logs `Received broadcast: "OK"` for each message of the broadcaster, and `Sent "Hello"` for
each message on `data`.
## Make a poller
The device has two functions. Both return a [`fair::mq::PollerPtr`](/api/fair/mq/#PollerPtr), which
is a `std::unique_ptr<fair::mq::Poller>`.
| Function | The poller polls | Check a channel with |
| --- | --- | --- |
| [`NewPoller("data", "broadcast")`](/api/fair/mq/Device/#NewPoller) | All sub-channels of the named channels. | `CheckInput("data", index)`, with the sub-channel index. |
| [`NewPoller(channels)`](/api/fair/mq/Device/#NewPoller-2), with a `std::vector<fair::mq::Channel*>` | The sub-channels in the vector. | `CheckInput(i)`, with the position `i` in the vector. |
`CheckOutput()` takes the same arguments as `CheckInput()`. The poller of `NewPoller(channels)` has
no channel names. On this poller, `CheckInput("data", 0)` throws
[`fair::mq::PollerError`](/api/fair/mq/PollerError/).
The poller of `NewPoller("data", "broadcast")` also accepts a position. It keeps the sub-channels in
the order of the names, and in each channel in the order of the index. With one
sub-channel in each channel, `CheckInput(0)` checks `data[0]` and `CheckInput(1)` checks
`broadcast[0]`.
The built-in merger device polls all sub-channels of its input channel with a vector:
<Snippet file="fairmq/devices/Merger.h" start="int numInputs = GetNumSubChannels(fInChannelName);" end="PollerPtr poller(NewPoller(chans));" />
`NewPoller(fInChannelName)` polls the same sub-channels. Then check them with
`CheckInput(fInChannelName, i)`.
Make the poller in `InitTask()`, `PreRun()` or `Run()`. Before the states `BINDING` and
`CONNECTING`, the channels have no sockets. The poller keeps the zeromq sockets of the channels. If
you keep the poller as a member of your device, destroy it in `ResetTask()`.
### The functions of the transport factory
`NewPoller()` calls a function of the [transport factory](/api/fair/mq/TransportFactory/) of the
channels. You can call these functions directly, for example
[without a device](/guides/channels-without-device/):
| Function | The poller polls | Check a channel with |
| --- | --- | --- |
| [`CreatePoller(subChannels)`](/api/fair/mq/TransportFactory/#CreatePoller), with a `std::vector<fair::mq::Channel>` | The sub-channels of one channel, for example `GetChannels().at("data")`. | `CheckInput(index)`, with the sub-channel index. |
| [`CreatePoller(channels)`](/api/fair/mq/TransportFactory/#CreatePoller-2), with a `std::vector<fair::mq::Channel*>` | The sub-channels in the vector. | `CheckInput(i)`, with the position `i`. |
| [`CreatePoller(channelMap, names)`](/api/fair/mq/TransportFactory/#CreatePoller-3) | All sub-channels of the named channels in the map. | `CheckInput(name, index)` or `CheckInput(i)`. |
An unknown name in `CreatePoller(channelMap, names)` throws `PollerError`. These functions do not
compare the transports of the channels. Give them only channels of the transport of this factory.
## What the poller checks
The socket type of each sub-channel selects the events that the poller waits for
([zeromq/Poller.h](/source/fairmq/zeromq/Poller.h/#L111-L123)):
| Socket type | The poller waits until | `CheckInput()` | `CheckOutput()` |
| --- | --- | --- | --- |
| `pull`, `sub`, `xsub` | a message arrived | `true` or `false` | always `false` |
| `push`, `pub`, `xpub` | the socket can send | always `false` | `true` or `false` |
| `req`, `rep`, `pair`, `dealer`, `router` | a message arrived, or the socket can send | `true` or `false` | `true` or `false` |
`CheckInput()` returns `true` if `zmq_poll()` set the event `ZMQ_POLLIN` for the socket, and
`CheckOutput()` returns `true` for `ZMQ_POLLOUT`. In ZeroMQ, `ZMQ_POLLIN` means that at least one
message waits, and `ZMQ_POLLOUT` means that the socket can take at least one message without a wait.
Both functions give the result of the last `Poll()`. The shmem transport polls the sockets that carry the metadata of its messages,
with the same rules.
:::caution[Sockets in both directions]
For the types `req`, `rep`, `pair`, `dealer` and `router`, the poller also waits for output.
ZeroMQ sets `ZMQ_POLLOUT` while one of these sockets can send. Then `Poll()` returns at once, also if
no message arrived. A loop
that does not send on such a socket then does not wait in `Poll()`, and it uses the CPU all the
time.
:::
The poller does not check the index. For a position outside the poller, or for a sub-channel index
that the channel does not have, `CheckInput()` and `CheckOutput()` read the item of another
sub-channel or memory outside the poller. The result is undefined.
## Select the timeout
`Poll(timeout)` waits until a socket is ready or the timeout ends. The poller gives the timeout in
milliseconds to `zmq_poll()` without a change. In ZeroMQ, the values have this effect:
- `0` returns at once.
- `-1` waits until a socket is ready.
- A positive value waits for this number of milliseconds at most.
`Poll()` returns no value. Check the channels after each call.
A transition request does not stop `Poll()`. On a request, the device calls `Interrupt()` on its
transports, and this stops only `Send()` and `Receive()`. Thus use a timeout of about 100 ms, and
check `NewStatePending()` after each `Poll()`. The device uses 200 ms for its own poller of the data
callbacks, and 500 ms if the callbacks use several transports.
`Poll()` tries again if a signal interrupts the system call. It returns when the zeromq context
ends. For all other errors, it logs `polling failed, reason: <error>` and throws `PollerError`.
## Use one transport for each poller
All channels of one poller must use the same transport. Both `NewPoller()` functions compare the
transports before they make the poller ([Device.h](/source/fairmq/Device.h/#L218-L257)). For the
channel names, they compare the sub-channel 0 of each channel. If the transports are different,
they log an error and throw `std::runtime_error`. If your `Run()` does not catch the exception, the
device goes to the state `ERROR`.
For channels of two transports, use one thread and one poller for each transport. Or register data
callbacks with `OnData()`: then the device makes one thread for each transport. See
[Receive from channels of different transports](/guides/several-transports/#receive-from-channels-of-different-transports).
## Check the result
The poller tests in [`test/poller/_poller.cxx`](https://github.com/FairRootGroup/FairMQ/blob/dev/test/poller/_poller.cxx)
run two devices for each transport. One device sends one message on each of `data1` and `data2`.
The other device polls the two channels until a message arrived on each. It uses `NewPoller()` with
a vector or with the names:
<Snippet file="test/helper/devices/TestPollIn.h" start="auto Run() -> void override" />
To test your own loop, send messages on one channel only, and make sure that the device receives
them. Then request the transition `STOP`, and make sure that the device leaves the state `RUNNING`
within your timeout.
## Problems that can occur
| Problem | Cause | Fix |
| --- | --- | --- |
| `GetChannel(): '<name>[0]' does not exist.`, then `std::out_of_range` | `NewPoller()` got the name of a channel that the device does not have. | Use the names of the channel configuration. |
| `invalid channel key: '<name>'`, then `PollerError` | `CheckInput(name, index)` on a poller from a vector, or a name that the poller does not have. | Check with the position, or make the poller with the names. |
| `poller failed: different transports within same poller are not yet supported` | The channels of one poller use different transports. | Make one poller for each transport. |
| The device does not stop. | `Poll(-1)`, or a long timeout, waits for a message. | Use a timeout of about 100 ms. Check `NewStatePending()` after each `Poll()`. |
| The loop uses the CPU all the time. | A `req`, `rep`, `pair`, `dealer` or `router` socket can send, and the loop does not send on it. | Poll these sockets only in a loop that also sends on them. To only receive, call `Receive()` with a timeout. |
## Related pages
- [Receive data with callbacks or loops](/guides/receive-data/): `OnData()`, `ConditionalRun()` and `Run()`.
- [Channels and sockets](/concepts/channels/): the socket types and their patterns.
- [Use several transports](/guides/several-transports/): channels of zeromq and shmem in one device.
- [Example: multiple channels](/examples/multiple-channels/): the example of this guide, step by step.

View File

@@ -0,0 +1,235 @@
---
title: 'Receive data with callbacks or loops'
description: 'Process messages in RUNNING with OnData() callbacks, with ConditionalRun() and the option --rate, or with your own Run() loop.'
sidebar:
order: 1
code: [fairmq/Device.h, fairmq/Device.cxx, fairmq/tools/RateLimit.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
This guide shows the three ways to do the work of a device in the state `RUNNING`: data callbacks,
`ConditionalRun()` and `Run()`. When you complete it, your device processes messages and leaves
`RUNNING` when its work ends or when a controller requests `Stop`.
## Choose a way
| | `OnData()` callbacks | `ConditionalRun()` | `Run()` |
| --- | --- | --- | --- |
| Who receives the messages | The device | Your code | Your code |
| How often the device calls your code | Once for each message | Again and again | Once |
| How your code ends `RUNNING` | The callback returns `false` | The function returns `false` | The function returns |
| What happens on `Stop` | The device does not call the callbacks again | The device does not call the function again | Your loop must check `NewStatePending()` |
| Rate limit | No | The option `--rate` | Your code |
| Typical device | Sink, processor | Sampler, client of a request and reply | Device with a poller or with its own order of transfers |
Use `OnData()` when your device reacts to messages. Use `ConditionalRun()` when your device creates
data or does a sequence of transfers. Use `Run()` only when you need full control of the loop.
## Receive with OnData()
<Steps>
1. In the constructor of your device, call [`OnData()`](/api/fair/mq/Device/#OnData) with the name
of the input channel and your callback.
2. Write the callback. It receives the message and the index of the sub-channel.
3. Return `true` from the callback to receive the next message. Return `false` to end `RUNNING`.
</Steps>
The processor of the example [1-n-1](/examples/1-n-1/) receives a message on the channel `data1` and
sends a new message on the channel `data2`:
<Snippet file="examples/1-n-1/processor.cxx" start="struct Processor : fair::mq::Device" />
The message belongs to the callback. You can change it, send it, or keep it.
### Callback forms
`OnData()` has four overloads. Two take a member function, and two take a `std::function`:
| Overload | Signature of the callback | Receives |
| --- | --- | --- |
| [`OnData(name, &T::f)`](/api/fair/mq/Device/#OnData) | `bool f(fair::mq::MessagePtr& msg, int index)` | One message |
| [`OnData(name, callback)`](/api/fair/mq/Device/#OnData-2) | [`InputMsgCallback`](/api/fair/mq/#InputMsgCallback) | One message |
| [`OnData(name, &T::f)`](/api/fair/mq/Device/#OnData-3) | `bool f(fair::mq::Parts& parts, int index)` | One multipart message |
| [`OnData(name, callback)`](/api/fair/mq/Device/#OnData-4) | [`InputMultipartCallback`](/api/fair/mq/#InputMultipartCallback) | One multipart message |
A multipart callback receives all parts of a message that the sender sent as `Parts`. This is the
start of the callback of the sink in the example [multipart](/examples/multipart/). It checks the
number of parts and reads the header from the first part:
<Snippet file="examples/multipart/sink.cxx" start="bool HandleData(fair::mq::Parts& parts, int)" end="Received part 1 (header)" />
A lambda is also a callback. The device of the example [qc](/examples/qc/) leaves `RUNNING` after the
first message:
<Snippet file="examples/qc/qCTask.cxx" start="QCTask()" />
### Several input channels
Call `OnData()` once for each input channel. The sink of the example
[multiple-channels](/examples/multiple-channels/) has two callbacks:
<Snippet file="examples/multiple-channels/sink.cxx" start=" Sink()" />
The device selects the method from the input channels:
- **One channel with one sub-channel:** the device calls `Receive()` in a loop, without a poller.
- **More channels or sub-channels, one transport:** the device polls all input channels with a
timeout of 200 ms. Then it calls the callbacks of the channels with data, in the order of the
`OnData()` calls.
- **More than one transport:** the device polls each transport in
[its own thread](/concepts/threads/#the-threads-of-a-device-process), with a timeout of 500 ms. A
mutex makes sure that only one callback runs at a time.
The index argument tells the callback which sub-channel received the message.
### Rules for callbacks
- Register the callbacks before `RUNNING` starts, for example in the constructor.
- Register one callback for each channel. A second `OnData()` of the same form for the same channel
has no effect.
- With callbacks, the device does not call `ConditionalRun()` and `Run()`. It calls `PreRun()` and
`PostRun()`.
- The device checks for a pending transition between two callbacks. A callback that does not return
delays the transition.
- If `Receive()` returns a negative [transfer code](/reference/transfer-codes/), the device does not
call the callback and ends `RUNNING`.
## Use ConditionalRun()
<Steps>
1. Override [`ConditionalRun()`](/api/fair/mq/Device/#ConditionalRun). Do one step of the work in
each call.
2. Check the return value of each `Send()` and `Receive()`. Return `false` when it is negative.
3. Return `true` to get the next call. Return `false` to end `RUNNING`.
4. To limit the number of calls per second, start the device with the option `--rate`.
</Steps>
The client of the example [req-rep](/examples/req-rep/) sends a request and waits for the reply in
each call:
<Snippet file="examples/req-rep/client.cxx" start="bool ConditionalRun()" />
The device calls `ConditionalRun()` while it returns `true` and no transition is pending. After the
last call, the device calls `Run()` once.
The option `--rate` gives the maximum rate of the calls in Hz. The default is 0, which means no
limit. The device reads the value in `INITIALIZING DEVICE`. A
[`tools::RateLimiter`](/api/fair/mq/tools/RateLimiter/) measures the time between the calls
and sleeps when the calls come too fast. Values of 0.001 or less give no limit. To limit a loop of
your own, see [RateLimit.h](/reference/tools/#ratelimith).
```sh
fairmq-ex-1-1-sampler --id sampler1 --rate 10 --channel-config name=data,type=push,method=bind,address=tcp://*:5555
```
## Write a Run() loop
<Steps>
1. Override [`Run()`](/api/fair/mq/Device/#Run).
2. Write a loop that continues while [`NewStatePending()`](/api/fair/mq/Device/#NewStatePending)
returns `false`.
3. In the loop, check the return value of each `Send()` and `Receive()`.
4. For a pause, call [`WaitFor()`](/api/fair/mq/Device/#WaitFor) and not `std::this_thread::sleep_for()`.
A pending transition ends `WaitFor()` at once.
5. Return from `Run()` to end `RUNNING`.
</Steps>
The sender of the example [n-m](/examples/n-m/) receives an id on the channel `sync` and sends a
multipart message to one of the receivers:
<Snippet file="examples/n-m/sender.cxx" start="void Run() override" />
When a controller requests `Stop`, the device interrupts its transports. The waiting `Receive()`
returns `TransferCode::interrupted`. The loop continues, and `NewStatePending()` ends it.
For a loop that also waits for output channels, see [Poll several channels](/guides/poll-channels/).
## What the tests show
The tests in `test/device/_data_callbacks.cxx` check these properties. The `DataCallbacks` tests run
for each transport:
| Test | Result |
| --- | --- |
| `DataCallbacks.SingleMessage` | The callback receives three messages with the index 0. It returns `false` after the third, and the device goes to `READY`. |
| `DataCallbacks.Multipart` | The multipart callback receives the parts `a` and `bc` in one call. |
| `DataCallbacks.TwoChannels` | A message callback and a multipart callback on two channels receive their messages. |
| `MultipleTransports.OneInputEach` | A zeromq channel and a shmem channel in one device receive their messages. |
| `ConditionalRun.EndsRunWhenItReturnsFalse` | `ConditionalRun()` returns `false` in the fifth call. The device makes no more calls and goes to `READY`. |
| `ConditionalRun.Rate` | With `rate` 100, the 21 calls take 140 ms or more. |
## Check the result
Start the sampler and the sink of the example [1-1](/examples/1-1/) in two terminals:
```sh
fairmq-ex-1-1-sampler --id sampler1 --rate 1 --max-iterations 3 --control static --channel-config name=data,type=push,method=bind,address=tcp://*:5555,rateLogging=0
```
```sh
fairmq-ex-1-1-sink --id sink1 --max-iterations 3 --control static --channel-config name=data,type=pull,method=connect,address=tcp://localhost:5555,rateLogging=0
```
The log of the sink shows these lines (without the prefix of the logger):
```txt
READY ---> RUNNING
fair::mq::Device running...
Received: "Hello"
Received: "Hello"
Received: "Hello"
Configured maximum number of iterations reached. Leaving RUNNING state.
RUNNING ---> READY
```
The line `RUNNING ---> READY` tells you that the device left `RUNNING`. With `--control static`, the
device then resets and exits.
## Problems that can occur
- **The device goes to `ERROR` at the start of `RUNNING`:** the channel name in `OnData()` does not
exist. The device throws `std::out_of_range`. Make sure that the name is the same as in the
channel configuration.
- **`RUNNING` ends without a reason in the log:** a `Receive()` for a callback returned a negative
value. For example, the input channel has the property `rcvTimeoutMs`, and no message arrived in
time. Remove the timeout, or use a `Run()` loop.
- **The device does not leave `RUNNING`:** your `Run()` loop does not check `NewStatePending()`, or a
callback does not return. Add the check, and return from the callbacks. A second Ctrl-C aborts a
device that does not stop.
- **`ConditionalRun()` is not called:** the device has data callbacks. Remove the `OnData()` calls, or
move the work into the callbacks.
- **A multipart callback receives wrong parts:** the sender sends single messages. With shmem, a
multipart `Receive()` of a single message reads wrong metadata. See the disabled test
`PartsTransfer.SingleSendMultipartReceive`. Use the same form on both sides.
:::caution[Known defect]
With input channels on more than one transport, the device calls the callbacks in
[other threads](/concepts/threads/#which-thread-runs-your-code). If
a callback throws an exception there, the process ends with `std::terminate()`. The device does not
go to `ERROR`.
:::
## Related pages
- [Device states](/concepts/states/): what happens in `RUNNING`, and what ends it.
- [Devices](/concepts/devices/): the hooks and the helper functions of a device.
- [Handle errors and timeouts](/guides/errors-timeouts/): transfer codes, timeouts and exceptions.
- [Poll several channels](/guides/poll-channels/): a `Run()` loop with a poller.
- [Messages and parts](/concepts/messages/): `MessagePtr` and `Parts`.

View File

@@ -0,0 +1,357 @@
---
title: Send your own data types
description: Put structs, arrays and serialized objects into messages, keep the data valid until the transport is done, and read it safely in the receiver.
sidebar:
order: 1.5
code: [fairmq/TransportFactory.h, fairmq/Message.h, fairmq/Device.h, fairmq/Parts.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
A message holds bytes. FairMQ copies and sends these bytes, but it does not serialize your objects
and it does not check their type. This guide shows how to put structs, arrays and serialized objects
into messages. It also shows how long your data must stay valid, and how a receiver reads the
bytes safely.
[Messages and multipart](/concepts/messages/) explains the message functions. This page uses them
for your own data types.
## Choose a way
| Your data | Make the message with | Copies that FairMQ makes |
| --- | --- | --- |
| A small trivially copyable struct or number | [`NewSimpleMessage(value)`](/api/fair/mq/Device/#NewSimpleMessage) | One copy on the heap. The shmem transport copies it again into the segment. |
| An array or a struct that you can write in place | [`NewMessage(size, alignment)`](/api/fair/mq/Device/#NewMessage), then write into [`GetData()`](/api/fair/mq/Message/#GetData) | None. |
| Data in a buffer of your own, for example a `std::vector` | `NewMessage(data, size, ffn, hint)` | zeromq: none. shmem: one copy into the segment. |
| A serialized object | Your serializer, then `NewMessage(size)` or a buffer of your own | See [Serialized objects](#serialized-objects). |
| A `std::pmr` container | [`fair::mq::getMessage()`](/api/fair/mq/#getMessage) | None, if the container uses the memory resource of the transport. Otherwise one copy ([MemoryResourceTools.h](/source/fairmq/MemoryResourceTools.h/#L42-L62)). See [Use std::pmr memory resources](/guides/pmr/). |
| A header and a payload | [`fair::mq::Parts`](/api/fair/mq/Parts/) with one part for each | The same as for each part. See [A header and a payload](#a-header-and-a-payload). |
The data types on this page are examples. This struct is the type of one element. The samples are
member functions of a device class, and they also need the headers `<cstring>`, `<stdexcept>`,
`<string>` and `<vector>`.
```cpp
#include <cstdint>
#include <type_traits>
struct Hit
{
float x;
float y;
float energy;
std::uint32_t detectorId;
};
// FairMQ does not check this. Check it yourself.
static_assert(std::is_trivially_copyable_v<Hit>, "Hit must be trivially copyable");
```
## Plain structs with NewSimpleMessage()
`NewSimpleMessage(value)` copies `value` into a new heap object with `new T(value)`. Then it makes a
message of `sizeof(T)` bytes for this object, with a deleter that deletes it
([TransportFactory.h](/source/fairmq/TransportFactory.h/#L195-L203)). You can change or destroy
`value` at once after the call.
```cpp
bool ConditionalRun() override
{
Hit const hit{1.5f, 2.5f, 0.3f, 7};
fair::mq::MessagePtr msg(NewSimpleMessage(hit));
return Send(msg, "data") >= 0;
}
```
The [copypush example](/examples/copypush/) sends a `uint64_t` counter in the same way, and the
sampler of the [multipart example](/examples/multipart/) sends its header struct.
### Limits of NewSimpleMessage()
The type must be trivially copyable, because the receiver gets only the bytes of the object. The
check for this is a comment in the code
([TransportFactory.h](/source/fairmq/TransportFactory.h/#L198-L200)). Thus a wrong type compiles and
sends wrong bytes:
| Argument | What the message contains |
| --- | --- |
| A trivially copyable struct, a number, `std::array<float, 16>` | The bytes of the object. This is correct. |
| A `std::vector<Hit>`, or a struct with a `std::string` member or a pointer member | The bytes of the object itself: sizes and addresses in the memory of the sender. The receiver cannot use them. |
| A pointer, for example a `const char*` variable | The bytes of the pointer itself, not the data that it points to. |
| A `char` array or a string literal | The characters up to the first zero byte, without the zero byte (overload for `const char (&)[N]`). Binary data in a `char` array is cut. For a `char` array without a zero byte, the copy reads past the end of the array. |
| A `std::string` | The characters of the string, without the terminating zero. |
| A C array of another element type, for example `float values[16]` | Does not compile, because `new T(value)` cannot copy an array. Use `std::array`. |
More rules:
- The receiver must use the same definition of the struct. FairMQ copies the bytes and does not
convert them, for example for another byte order or another padding.
- Use `NewSimpleMessage()` for small data only, because of the additional copy. The comment in the
multipart sampler says the same. With shmem, the data is copied two times.
- `NewSimpleMessage()` uses the default transport of the device. For a channel with another
transport, use `NewSimpleMessageFor(channel, index, value)`.
## Write in place with NewMessage(size)
`NewMessage(size)` allocates a buffer of `size` bytes in the transport. The zeromq transport
allocates it in the memory of the process. The shmem transport allocates it in the managed segment,
and the receiver reads this block without a copy. Write your data into the buffer before you send
the message.
<Steps>
1. Calculate the size in bytes, for example `numHits * sizeof(Hit)`.
2. Call `NewMessage(size, fair::mq::Alignment{alignof(Hit)})`. The alignment makes sure that the
pointer to the buffer is correct for the type.
3. Cast [`GetData()`](/api/fair/mq/Message/#GetData) to a pointer to your type and write the
elements.
4. If you wrote fewer bytes than you allocated, call
[`SetUsedSize(bytes)`](/api/fair/mq/Message/#SetUsedSize).
5. Send the message. After a successful `Send()`, do not read or write the buffer.
</Steps>
```cpp
bool ConditionalRun() override
{
std::size_t const numHits = 1000;
fair::mq::MessagePtr msg(NewMessage(numHits * sizeof(Hit), fair::mq::Alignment{alignof(Hit)}));
auto* hits = static_cast<Hit*>(msg->GetData());
for (std::size_t i = 0; i < numHits; ++i) {
hits[i] = Hit{0.1f * i, 0.2f * i, 1.0f, static_cast<std::uint32_t>(i)};
}
return Send(msg, "data") >= 0;
}
```
[`fair::mq::Alignment`](/api/fair/mq/Alignment/) has one `size_t` member. The test
`Messages.Alignment` makes messages with an alignment of 64 bytes and checks the addresses for both
transports. Without an alignment, the zeromq transport uses the buffer of `zmq_msg_init_size()`,
and FairMQ does not check its alignment.
[Change the size](/concepts/messages/#change-the-size) explains `SetUsedSize()`. By default, a full
shmem segment makes `NewMessage()` throw `MessageBadAlloc`, see
[Shared memory allocation](/guides/errors-timeouts/#shared-memory-allocation).
## Send a buffer of your own
`NewMessage(data, size, ffn, hint)` makes a message for a buffer that you allocated. `ffn` is a
function of the type [`fair::mq::FreeFn`](/api/fair/mq/#FreeFn), `void(void* data, void* hint)`.
The transport calls `ffn(data, hint)` when it does not need the buffer any more. The `hint` can
point to the object that owns the buffer. The [1-1 example](/examples/1-1/) sends a `std::string`
this way. A `std::vector` works in the same way:
```cpp
bool ConditionalRun() override
{
auto* hits = new std::vector<Hit>(1000);
// Write the elements of *hits here.
fair::mq::MessagePtr msg(NewMessage(hits->data(),
hits->size() * sizeof(Hit),
[](void* /*data*/, void* hint) { delete static_cast<std::vector<Hit>*>(hint); },
hits));
return Send(msg, "data") >= 0;
}
```
- The zeromq transport sends your buffer without a copy. ZeroMQ calls `ffn` after the transfer,
and it can call it from one of its own threads (ZeroMQ behavior).
- The shmem transport copies the buffer into the segment when it makes the message. Then it calls
`ffn` at once ([shmem/Message.h](/source/fairmq/shmem/Message.h/#L64-L78)).
- For the size 0, the shmem transport does not call `ffn`. The object of the `hint` then stays
allocated. Send an empty message with `NewMessage()` instead.
- If the shmem transport cannot allocate the block, `NewMessage()` throws before it calls `ffn`.
Then you must free the buffer yourself.
Write data that you send with shmem directly into a message from `NewMessage(size)`. Then the
transport does not copy it.
## Serialized objects
FairMQ has no serializer. Use the library of your choice, for example to serialize an object into a
`std::string` or a `std::vector<char>`. Then put the bytes into a message in one of these ways:
- **The serializer gives a buffer.** Move the buffer to the heap. Give it to
`NewMessage(data, size, ffn, hint)`, as in [Send a buffer of your own](#send-a-buffer-of-your-own).
- **You know the size before you serialize.** Make the message with `NewMessage(maxSize)`, and let
the serializer write into `GetData()`. Then call `SetUsedSize()` with the real size. The zeromq
transport does not copy the data. The shmem transport shrinks the block in place. Only if this
fails and at least 1000000 bytes are unused, it copies the data into a new block
([shmem/Message.h](/source/fairmq/shmem/Message.h/#L208-L235)).
- **The serializer writes into a container with an allocator.** Use a `std::pmr` container on the
memory resource of the transport. See [Use std::pmr memory resources](/guides/pmr/).
In this sample, `MySerialize()` stands for the function of your library:
```cpp
bool ConditionalRun() override
{
auto* buffer = new std::string(MySerialize(fEvent));
fair::mq::MessagePtr msg(NewMessage(buffer->data(),
buffer->size(),
[](void* /*data*/, void* hint) { delete static_cast<std::string*>(hint); },
buffer));
return Send(msg, "data") >= 0;
}
```
The receiver gives `GetData()` and `GetSize()` to the deserializer. The deserializer must not read
more than `GetSize()` bytes.
### The deprecated Serialize() and Deserialize()
[`Device::Serialize<Serializer>(msg, data, args…)`](/api/fair/mq/Device/#Serialize) and
[`Device::Deserialize<Deserializer>(msg, data, args…)`](/api/fair/mq/Device/#Deserialize) are
deprecated ([Device.h](/source/fairmq/Device.h/#L78-L88)). They make a temporary `Serializer` or
`Deserializer` object and call its member function `Serialize(msg, data, args…)` or
`Deserialize(msg, data, args…)`. They add nothing else. Call your class directly instead:
```cpp
// Old, gives a deprecation warning:
Serialize<MySerializer>(*msg, fEvent);
// New:
MySerializer().Serialize(*msg, fEvent);
```
## A header and a payload
Put the header and the payload into two parts of one multipart message. Each part keeps its own
buffer, so FairMQ does not copy the payload to join it with the header. The receiver gets all parts
in one call. The [multipart example](/examples/multipart/) uses this header:
<Snippet file="examples/multipart/Header.h" start="struct Header" />
The sampler copies the header with `NewSimpleMessage()` into part 0, and allocates the payload
with `NewMessage(1000)` as part 1:
<Snippet file="examples/multipart/sampler.cxx" start="example_multipart::Header header;" end="parts.AddPart(NewMessage(1000));" />
The sink reads the header from part 0:
<Snippet file="examples/multipart/sink.cxx" start="if (parts.Size() != 7)" end="header.stopFlag = (static_cast" />
The sink checks the number of parts, but not the size of part 0. A receiver must also check the
size before it reads the header. See [Read the data safely](#read-the-data-safely). For the rules of
multipart messages, see [Multipart messages](/concepts/messages/#multipart-messages).
## How long the data must stay valid
The rules depend on the function that makes the message and on the transport. The default
transport of a device comes from `--transport`, and each channel can have its own transport. To
support both transports, follow the stricter rule of the two columns.
| Message from | zeromq | shmem |
| --- | --- | --- |
| `NewSimpleMessage()` | The message owns a copy. You can change your object at once. | The same. |
| `NewMessage(size)` | The transport owns the buffer. Write it before `Send()`. After a successful `Send()`, do not use it. | The same. The receiver reads the same block in shared memory. |
| `NewMessage(data, size, ffn, hint)` | Your buffer must stay valid and unchanged until ZeroMQ calls `ffn`. | The transport copies the buffer and calls `ffn` before `NewMessage()` returns. |
| [`NewStaticMessage(str)`](/api/fair/mq/Device/#NewStaticMessage), or a buffer with [`NoCleanup`](/api/fair/mq/TransportFactory/#NoCleanup) | The transport tells you nothing when the transfer ends. Use only data that does not change and that lives longer than the transport, for example the member `fText` of the [1-n-1 sampler](/examples/1-n-1/#the-code). | The transport copies the data when it makes the message. |
| [`Copy()`](/api/fair/mq/Message/#Copy) of a message | Do not change the buffer after `Copy()`. Both messages can use the same buffer ([Message.h](/source/fairmq/Message.h/#L55-L59)). | The same. |
| A block of an unmanaged region | See [Unmanaged regions](/shmem/regions/). | See [Unmanaged regions](/shmem/regions/). |
If `Send()` returns a negative value, the message keeps its buffer. You can send it again or
destroy it.
A received message owns its buffer. The data is valid while the message exists. Do not keep the
pointer from `GetData()` after you destroy or rebuild the message. To keep the data longer, keep the
`MessagePtr`. The receiver of the [n-m example](/examples/n-m/#receiver-collect-the-parts) moves
a part out of the `Parts` object and stores it, with
`fBuffer[h.id].parts.AddPart(std::move(parts.At(1)))`. With shmem, destroy all messages before the
device destroys its transports, see
[Rules for your code](/shmem/how-it-works/#rules-for-your-code).
## Read the data safely
A message can have another size than you expect, for example from a sender with another version of
your struct. A read past `GetSize()` reads memory that does not belong to the message.
<Steps>
1. For a multipart message, check the number of parts with `parts.Size()`.
2. Check `GetSize()` of each part before you read it. A struct needs `GetSize() == sizeof(T)`. An
array needs `GetSize() % sizeof(T) == 0`.
3. Copy a struct out of the buffer with `std::memcpy()`. Then the alignment of the buffer has no
effect.
4. Read an array in place only from a message that you received with an alignment.
</Steps>
The test `Factory.SimpleAndStaticMessages` checks the size and copies a number out of the buffer:
<Snippet file="test/transport/_factory.cxx" start="uint64_t const value = 0x0123456789abcdef;" end="EXPECT_EQ(received, value);" />
A data callback of [`OnData()`](/api/fair/mq/Device/#OnData) gets a message that the device made
without an alignment ([Device.cxx](/source/fairmq/Device.cxx/#L564-L584)). This multipart callback
uses the `Header` of the multipart example. It checks the sizes and copies each element:
```cpp
bool HandleData(fair::mq::Parts& parts, int /*index*/)
{
if (parts.Size() != 2 || parts[0].GetSize() != sizeof(example_multipart::Header)) {
throw std::runtime_error("unexpected message format");
}
example_multipart::Header header;
std::memcpy(&header, parts[0].GetData(), sizeof(header));
auto const& payload = parts[1];
if (payload.GetSize() % sizeof(Hit) != 0) {
throw std::runtime_error("payload size is not a multiple of sizeof(Hit)");
}
auto const* bytes = static_cast<char const*>(payload.GetData());
std::size_t const numHits = payload.GetSize() / sizeof(Hit);
for (std::size_t i = 0; i < numHits; ++i) {
Hit hit;
std::memcpy(&hit, bytes + i * sizeof(Hit), sizeof(hit));
fSumEnergy += hit.energy;
}
return header.stopFlag == 0;
}
```
An exception in the callback moves the device to `ERROR`. To continue instead, log the error and
return `true`. See [Handle errors and timeouts](/guides/errors-timeouts/#exceptions-and-the-error-state).
To read an array in place, receive the message yourself, for example in `ConditionalRun()`. Make
the empty message with `NewMessage(fair::mq::Alignment{alignof(Hit)})`. If the received buffer of
the zeromq transport is not aligned, the transport copies it into an aligned buffer
([zeromq/Message.h](/source/fairmq/zeromq/Message.h/#L241-L256)). The shmem transport ignores this
alignment, because the receiver gets the block of the sender. The shmem transport aligns each block
of the managed segment to at least `alignof(std::max_align_t)`
([shmem/Manager.h](/source/fairmq/shmem/Manager.h/#L694-L696)).
## Problems that can occur
- **The receiver gets a few bytes instead of the data:** you gave a `std::vector` to
`NewSimpleMessage()`. The message has `sizeof(std::vector<Hit>)` bytes, for example 24. Use
`NewMessage(data, size, ffn, hint)` or `NewMessage(size)`.
- **A binary `char` array arrives shorter:** `NewSimpleMessage()` treats a `char` array as a C
string. Use `NewMessage(size)` and `std::memcpy()`.
- **The receiver reads wrong values after an update of the sender:** the two devices use different
definitions of the struct. Put a version number into the header, and check the size.
- **The data of a zeromq message changes during the transfer:** your code changed the buffer too
early. With `NewStaticMessage()` or `NewMessage(data, size, ffn, hint)`, ZeroMQ uses your buffer
until the transfer ends (ZeroMQ behavior).
- **The shared memory segment becomes full:** the receiver keeps the messages, or the sender sends
faster than the receiver reads. See [Tune and debug](/shmem/tuning/).
## Related pages
- [Messages and multipart](/concepts/messages/): the functions that make, send and receive messages.
- [Use std::pmr memory resources](/guides/pmr/): fill a container in message memory and send it
without a copy.
- [multipart: several parts in one message](/examples/multipart/): the header and payload example.
- [How shared memory works](/shmem/how-it-works/): where the shmem transport keeps the data.
- [Unmanaged regions](/shmem/regions/): messages for blocks of your own shared memory.

View File

@@ -0,0 +1,199 @@
---
title: 'Use several transports'
description: 'Give each channel of one device its own transport, make messages for the right transport, and receive from channels of different transports.'
sidebar:
order: 3
code: [fairmq/Device.h, fairmq/Device.cxx, fairmq/Channel.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
One device can use the shmem transport for some channels and the zeromq transport for others. For
example, it uses shmem to a process on the same host and zeromq to another host. This guide shows
how to configure the transport of each channel and how to make messages without a conversion. It
also shows how to receive from channels of different transports.
The device makes one transport factory for each transport that its channels use. For the rules, see
[How a device selects the transport](/concepts/transports/#how-a-device-selects-the-transport).
## Configure the channels
<Steps>
1. Select the default transport of the device with `--transport`. The value is `zeromq` (default) or
`shmem`. All channels without a transport property use it.
2. Add the [channel property](/reference/channel-properties/) `transport` to each channel that uses
the other transport. In `--channel-config`, add `transport=zeromq` or `transport=shmem`.
3. Give the peer channel in the other device the same transport.
4. For each shmem channel, run both devices on the same host with the same `--session`. Do not use
the socket types `pub` and `sub`.
</Steps>
The [multiple-transports example](/examples/multiple-transports/) starts `sampler1` with `shmem` as
the default transport. Its channel `ack` is a `sub` socket, thus it uses `zeromq`:
<Snippet file="examples/multiple-transports/fairmq-start-ex-multiple-transports.sh.in" start='SAMPLER1="fairmq' end="name=ack,type=sub" />
The example has no JSON file. In a [JSON file](/reference/json/) for `--mq-config`, set `transport`
for the channel or for one socket of the channel. A socket without `transport` uses the value of its channel. This file
gives `sampler1` the same channels:
```json
{
"fairMQOptions": {
"devices": [
{
"id": "sampler1",
"channels": [
{
"name": "data1",
"sockets": [
{ "type": "push", "method": "bind", "address": "tcp://127.0.0.1:5555" }
]
},
{
"name": "ack",
"transport": "zeromq",
"sockets": [
{ "type": "sub", "method": "bind", "address": "tcp://127.0.0.1:5557" }
]
}
]
}
]
}
}
```
Give all sub-channels of one channel the same transport. The pollers and the data callbacks of the
device use the transport of the sub-channel 0 for all sub-channels.
## Make messages for the right transport
[`NewMessage()`](/api/fair/mq/Device/#NewMessage) uses the default transport of the device. To make
a message with the transport of a channel, use
[`NewMessageFor(channel, index, args…)`](/api/fair/mq/Device/#NewMessageFor). It takes the same
arguments as `NewMessage()` after the channel name and the sub-channel index. `sampler1` makes its
data messages with the transport of `data1`:
<Snippet file="examples/multiple-transports/sampler1.cxx" start="bool ConditionalRun() override" />
The device has more functions of this kind:
[`NewSimpleMessageFor()`](/api/fair/mq/Device/#NewSimpleMessageFor),
[`NewStaticMessageFor()`](/api/fair/mq/Device/#NewStaticMessageFor) and
[`NewUnmanagedRegionFor()`](/api/fair/mq/Device/#NewUnmanagedRegionFor). If you have a reference to
the channel, call [`NewMessage()`](/api/fair/mq/Channel/#NewMessage) on the channel.
[`AddTransport(Transport::SHM)`](/api/fair/mq/Device/#AddTransport) returns the factory of a
transport, and makes it if the device has none.
## Send a message of another transport
You can send a message on a channel of another transport. `Channel::Send()` then converts the
message ([Channel.h](/source/fairmq/Channel.h/#L421-L480)):
| Message | Channel | What the channel does |
| --- | --- | --- |
| `shmem` | `zeromq` | Makes a zeromq message that points to the shared memory buffer. No copy. The shared memory buffer stays allocated until zeromq releases the message. |
| `zeromq` | `shmem` | Copies the data into the shared memory segment, and destroys the zeromq message. |
| empty | either | Replaces the message with an empty message of the channel transport. |
After the call, your `MessagePtr` points to the new message. `Receive()` replaces a message object of
another transport with an empty message of the channel transport. The sender of the
[readout example](/examples/readout/) receives shmem messages and sends them on its zeromq channel
`sr`:
<Snippet file="examples/readout/sender.cxx" start="bool HandleData(fair::mq::MessagePtr& msg, int /*index*/)" />
The copy from zeromq to shmem costs time and memory for large messages. Use `NewMessageFor()` to
prevent it.
## Receive from channels of different transports
If you register data callbacks with [`OnData()`](/api/fair/mq/Device/#OnData) on channels of
different transports, the device polls each transport in its own thread. The callbacks run in
[these threads](/concepts/threads/#which-thread-runs-your-code). A mutex lets only one callback run at a time
([Device.cxx](/source/fairmq/Device.cxx/#L509-L562)). The sink of the example registers callbacks
for `data1` and `data2`:
<Snippet file="examples/multiple-transports/sink.cxx" start="Sink()" />
:::caution[Exceptions in the threads of the transports]
In this mode, an exception in a poll thread, for example in a data callback, does not move the
device to the state `ERROR`.
The device logs `fair::mq::Device::PollForTransport() failed: <error>, going to ERROR state.` and
throws again ([Device.cxx](/source/fairmq/Device.cxx/#L558-L561)). The exception leaves the thread,
and C++ calls `std::terminate()`. Catch the exceptions in your callbacks.
:::
The start script gives `data1` and `data2` of the sink the same transport, `shmem`. The test script
of the example gives `data2` the transport `zeromq`. Then the sink polls `shmem` and `zeromq` in two
threads:
<Snippet file="examples/multiple-transports/test-ex-multiple-transports.sh.in" start='SINK+=" --transport shmem"' end="name=$ackChan" />
One [poller](/guides/poll-channels/) can poll channels of one transport only.
[`NewPoller()`](/api/fair/mq/Device/#NewPoller) throws `std::runtime_error` for channels of
different transports. Use one thread for each transport, with its own poller or a blocking
`Receive()`. `sampler1` receives the acknowledgements with a blocking `Receive()` in a second
thread:
<Snippet file="examples/multiple-transports/sampler1.cxx" start="void ListenForAcks()" />
## Check the result
<Steps>
1. Start the devices with `--severity debug`.
2. Find the line `Initializing transport for channel <name>[<index>]: <transport>` for each
sub-channel. The value `default` means the default transport of the device.
3. Find the line `Adding '<transport>' transport` once for each transport of the device.
</Steps>
In the code, [`GetChannel(name, index).GetTransportName()`](/api/fair/mq/Channel/#GetTransportName)
returns the transport of a sub-channel, and [`msg->GetType()`](/api/fair/mq/Message/#GetType)
returns the transport of a message.
To run the example, start `fairmq-start-ex-multiple-transports.sh` in the directory
`examples/multiple-transports` of the build directory. The script opens one `xterm` window for each
device. When `sampler1` leaves the state `RUNNING`, it logs `Acknowledged <n> messages`.
## Problems that can occur
| Message in the log | Cause | Fix |
| --- | --- | --- |
| `Received message is not a valid FairMQ shared memory message` | A shmem channel received a message from a zeromq peer. | Give both ends of the channel the same transport. |
| `poller failed: different transports within same poller are not yet supported` | `NewPoller()` got channels of different transports. | Make one poller for each transport. |
| `PUB/SUB socket type is not supported for shared memory transport` | A shmem channel has the type `pub` or `sub`. | Add `transport=zeromq` to the channel. |
| `Unknown transport provided: <name>` | A channel property `transport` has an unknown value. | Use `default`, `zeromq` or `shmem`. |
| `invalid transport type provided: <name>` | `--transport` has an unknown value. | Use `zeromq` or `shmem`. |
A shmem receiver detects a zeromq message only if the message is smaller than the shmem metadata. A
larger zeromq message goes into the receiver as shmem metadata. A zeromq receiver gets the shmem
metadata as data and reports no error. Thus a wrong transport on one end of a channel does not
always cause an error message.
## Checklist
- The default transport of the device is the transport of most channels.
- Each other channel has the property `transport`.
- Both ends of each channel use the same transport.
- All sub-channels of one channel use the same transport.
- Each shmem channel connects devices on one host with the same `--session`, and is not `pub` or `sub`.
- The device makes messages with `NewMessageFor()`, or with `NewMessage()` of the channel.
- Each poller polls channels of one transport only.
## Related pages
- [Transports](/concepts/transports/): the two transports and how a device selects them.
- [Messages and multipart](/concepts/messages/): what `Send()` does with a message.
- [Poll several channels](/guides/poll-channels/): wait for messages on several channels.
- [Example: multiple transports](/examples/multiple-transports/): the example of this guide, step by step.
- [Design a topology](/guides/design-topology/#select-the-transport-of-each-link): select the transport of each link.

View File

@@ -0,0 +1,415 @@
---
title: Test your devices
description: 'Run a topology as CTest tests: a script with a unique session, the static controller, ipc addresses and the cleanup of shared memory, for each transport.'
sidebar:
order: 9.7
code: [fairmq/tools/runUuidGenerator.cxx, fairmq/plugins/control/Control.cxx, fairmq/shmem/Manager.cxx, fairmq/shmem/runMonitor.cxx, fairmq/TransportFactory.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
This guide makes CTest tests for your devices. A shell script starts the devices of the topology,
waits until they stop, and removes what they leave behind. CMake adds the script once for each
transport. For code that does not need a device, a GoogleTest program in one process is enough.
The examples of FairMQ use the same method. See [Test the example](/examples/1-1/#test-the-example)
on the page of the 1-1 example.
## What a test needs
| Need | How | Why |
| --- | --- | --- |
| A new session for each run | `--session` with the output of `fairmq-uuid-gen -h` | Tests that run at the same time do not share shared memory. See [Keep two topologies apart](/shmem/sessions/#keep-two-topologies-apart). |
| Devices that stop by themselves | `--control static`, and an end condition in the devices | With `static`, the process ends when the device leaves `RUNNING`. The default `dynamic` waits for the key `q`. See [Control modes](/concepts/plugins/#control-modes). |
| Unique addresses | `ipc:///tmp/fmq_<session>_<channel>_<transport>` | No port collisions, and no connections to the devices of another test. |
| A small segment | `--shm-segment-size 100000000` | The default is 2 GiB. The tests of FairMQ use 100000000 bytes (100 MB). |
| Cleanup after a crash | `--shm-monitor true` and `FAIRMQ_PATH` | When all devices of the session stopped, also after a crash, a daemon removes the shared memory. See [Automatic cleanup](/shmem/monitor/#automatic-cleanup-with---shm-monitor). |
| Cleanup after a failure | A trap in the script | The script stops the other devices and removes the shared memory and the socket files. |
| A limit for the time | The test property `TIMEOUT` | CTest stops a test that hangs, and the test fails (CMake behavior). |
`--max-iterations` is not an option of every device. Many example devices add it with
`addCustomOptions()` and return `false` from `ConditionalRun()` or from their data callback after
this number of messages. The built-in devices `fairmq-bsampler` and `fairmq-sink` also have it.
See [The sampler](/examples/1-1/#the-sampler) and
[Stop a topology without losing messages](/guides/end-of-run/). Give your
devices an end condition of this type, or stop them with a signal.
## Write the test script
<Steps>
1. Read the transport from the first argument.
2. Make a new session name with `fairmq-uuid-gen -h`. Write it to the output.
3. Make an `ipc://` address for each channel from the session, the channel name and the transport.
4. Set a trap for `EXIT` that stops the remaining devices and removes the shared memory and the
socket files.
5. Start each device in the background with the same session and `--control static`.
6. Wait for the devices with an end condition.
7. Stop the other devices with `SIGTERM` or `SIGINT`, and wait for them.
</Steps>
This script tests a topology `my-sampler` → `my-processor` → `my-sink`. The sampler and the sink have
an option `--max-iterations` like the examples. The processor has no end condition:
```sh title="test-topology.sh"
#!/bin/bash
# Usage: test-topology.sh <transport> <directory of the devices>
# FAIRMQ_PATH must be the directory of fairmq-uuid-gen and fairmq-shmmonitor.
set -eu
transport="$1"
bin="$2"
session="$("$FAIRMQ_PATH/fairmq-uuid-gen" -h)"
echo "session: $session"
dataAddr="/tmp/fmq_${session}_data_${transport}"
resultAddr="/tmp/fmq_${session}_result_${transport}"
cleanup() {
set +e
local running
running="$(jobs -p)"
if [[ -n $running ]]; then
kill -TERM $running
wait
fi
"$FAIRMQ_PATH/fairmq-shmmonitor" --cleanup --session "$session"
rm -f "$dataAddr" "$resultAddr"
}
trap cleanup EXIT
trap 'exit 1' TERM INT
common=(--transport "$transport" --session "$session" --control static --color false
--shm-segment-size 100000000 --shm-monitor true)
"$bin/my-sampler" --id sampler1 "${common[@]}" --max-iterations 10 \
--channel-config "name=data,type=push,method=bind,address=ipc://$dataAddr,rateLogging=0" &
samplerPid=$!
"$bin/my-processor" --id processor1 "${common[@]}" \
--channel-config "name=data,type=pull,method=connect,address=ipc://$dataAddr,rateLogging=0" \
"name=result,type=push,method=connect,address=ipc://$resultAddr,rateLogging=0" &
processorPid=$!
"$bin/my-sink" --id sink1 "${common[@]}" --max-iterations 10 \
--channel-config "name=result,type=pull,method=bind,address=ipc://$resultAddr,rateLogging=0" &
sinkPid=$!
wait "$samplerPid"
wait "$sinkPid"
kill -TERM "$processorPid"
wait "$processorPid"
```
How the script works:
- `set -e` ends the script when a command fails. `wait "$pid"` returns the exit code of the device,
so a device that stops with an error ends the script with this code. The test then fails.
- The script waits for the devices in a fixed order. If the sink fails before the sampler stops,
the script finds the error when the sampler stops.
- `set -u` stops the script at a variable that has no value, for example a misspelled name.
- The trap for `EXIT` runs at each end of the script: after success, after a failed device, and
after `SIGTERM` or `SIGINT`. `jobs -p` lists the devices that still run. The trap stops them,
waits for them, and removes the shared memory of the session and the socket files.
- The exit code of the script does not change in the trap. After a signal, `trap 'exit 1' TERM INT`
ends the script with the code 1.
- After a signal, the control plugin of each device runs the shutdown sequence, and the device
exits with the code 0. See [Signals](/concepts/plugins/#signals).
- A device that goes to the state `ERROR` exits with the code 1. See
[When the device goes to ERROR](/concepts/plugins/#when-the-device-goes-to-error).
- The script writes the session name. If the test fails, the output of CTest shows it, and you can
remove the shared memory of this session.
The test script of the 1-1 example starts the sampler in the same way:
<Snippet file="examples/1-1/test-ex-1-1.sh.in" start='SAMPLER="fairmq-ex-1-1-sampler"' end="SAMPLER_PID=$!" />
The script of the [1-n-1 example](/examples/1-n-1/) stops its two processors with `SIGINT` after
the sampler and the sink stop.
:::caution[Errors in the example scripts]
Do not copy the example scripts without changes:
- Their traps run only on `TERM`. If a device fails, `set -e` ends the script, and the other
devices continue to run.
- Their traps end with `exit 0`.
- In `test-ex-multiple-transports.sh.in` and `test-ex-region.sh.in`, the trap calls
`fairmq-shmmonitor --cleanup --session $SESSION`. The variable of the script is `session`, so the
option `--session` gets no value. `set -u` finds this type of error.
- `test-ex-builtin-devices.sh.in` gives each device `--session $SESSION`, with the same error.
:::
## Add one CTest test for each transport
Register the script once for each transport. This `CMakeLists.txt` uses the package variable
`FairMQ_BINDIR`, the directory of `fairmq-uuid-gen` and `fairmq-shmmonitor` (see
[Package variables](/start/cmake/#package-variables)):
```cmake title="CMakeLists.txt"
enable_testing() # in the top-level CMakeLists.txt
foreach(transport IN ITEMS zeromq shmem)
set(test "MyTopology.${transport}")
add_test(NAME ${test}
COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/test-topology.sh
${transport} $<TARGET_FILE_DIR:my-sampler>)
set_tests_properties(${test} PROPERTIES
TIMEOUT 30
ENVIRONMENT "FAIRMQ_PATH=${FairMQ_BINDIR}")
endforeach()
```
- `FAIRMQ_PATH` has two uses. The script finds the two tools there, and the shmem transport looks
there first for `fairmq-shmmonitor`, then in `PATH`
([Manager.cxx](/source/fairmq/shmem/Manager.cxx/#L26-L53)).
- `$<TARGET_FILE_DIR:my-sampler>` gives the directory of your devices. The script expects all three
devices in this directory.
- `TIMEOUT 30` is the timeout of the example tests. Give your test enough time for a slow machine,
for example a build with sanitizers.
On a timeout, CTest stops the test process (CMake behavior). The trap of the script does not run
then. With CMake 3.27 or later, the test properties `TIMEOUT_SIGNAL_NAME` and
`TIMEOUT_SIGNAL_GRACE_PERIOD` make CTest send a signal first and wait before it stops the process
(CMake behavior, see the
[CMake documentation](https://cmake.org/cmake/help/latest/prop_test/TIMEOUT_SIGNAL_NAME.html)).
Then the trap can stop the devices:
```cmake
if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.27)
set_tests_properties(${test} PROPERTIES
TIMEOUT_SIGNAL_NAME SIGTERM
TIMEOUT_SIGNAL_GRACE_PERIOD 10)
endif()
```
Put this block in the loop, after `set_tests_properties()`.
### How the examples register their tests
The function `add_example()` in
[`examples/CMakeLists.txt`](https://github.com/FairRootGroup/FairMQ/blob/dev/examples/CMakeLists.txt)
copies `test-ex-<name>.sh.in` with `configure_file()` into the build directory. Then it adds the test
`Example.<name>.<transport>` (or `Example.<name>.<variant>.<transport>`) for each transport, with a
timeout of 30 s. `env_mods` holds the changes of the environment for the leak sanitizer and for
`FAIRMQ_TEST_LD_LIBRARY_PATH`:
<Snippet file="examples/CMakeLists.txt" start=' set(test "${testsuite}.${name}.${transport}")' end="endif()" />
`configure_file()` replaces `@CMAKE_BINARY_DIR@`, `@CMAKE_CURRENT_BINARY_DIR@` and `@FAIRMQ_BIN_DIR@`
in the script with the paths of the build tree. Thus the example scripts find `fairmq-uuid-gen` in
`<build>/fairmq`.
:::caution[`${…}` in a configured script]
`add_example()` calls `configure_file()` for the test scripts without the option `@ONLY`. Then CMake
also replaces each `${variable}` in the script with the value of a CMake variable, which is often
empty (CMake behavior). The example scripts use only the form `$variable`. If you configure your
script, use `@ONLY`, or do not use `${…}` in it.
:::
## Test without a device
To test the code that sends and receives, and not the state machine, make the transport factory
and the channels in the test program. See
[Use channels without a device](/guides/channels-without-device/). The tests of FairMQ in
[`test/transport/`](https://github.com/FairRootGroup/FairMQ/tree/dev/test/transport) and
[`test/channel/`](https://github.com/FairRootGroup/FairMQ/tree/dev/test/channel) do this. Many of
these tests run once for each transport.
This GoogleTest program sends one message from a `push` channel to a `pull` channel:
```cpp title="test_channels.cxx"
#include <fairmq/Channel.h>
#include <fairmq/ProgOptions.h>
#include <fairmq/TransportFactory.h>
#include <fairmq/tools/Unique.h>
#include <gtest/gtest.h>
#include <cstddef>
#include <string>
namespace
{
class PushPull : public testing::TestWithParam<std::string>
{};
TEST_P(PushPull, OneMessage)
{
fair::mq::ProgOptions config;
config.SetProperty<std::string>("session", fair::mq::tools::Uuid());
config.SetProperty<std::size_t>("shm-segment-size", 100000000);
config.SetProperty<bool>("shm-monitor", true);
auto factory = fair::mq::TransportFactory::CreateTransportFactory(GetParam(), "", &config);
fair::mq::Channel pull("data-in", "pull", factory);
fair::mq::Channel push("data-out", "push", factory);
ASSERT_TRUE(pull.Bind("inproc://data"));
ASSERT_TRUE(push.Connect("inproc://data"));
auto out(push.NewSimpleMessage("hello"));
ASSERT_EQ(push.Send(out, 1000), 5);
auto in(pull.NewMessage());
ASSERT_EQ(pull.Receive(in, 1000), 5);
EXPECT_EQ(std::string(static_cast<char*>(in->GetData()), in->GetSize()), "hello");
}
INSTANTIATE_TEST_SUITE_P(, PushPull, testing::Values("zeromq", "shmem"),
[](testing::TestParamInfo<std::string> const& info) { return info.param; });
} // namespace
```
- [`tools::Uuid()`](/api/fair/mq/tools/#Uuid) gives each test its own session. Without the property
`session`, all tests use the session `default` and share its shared memory.
- An `inproc://` address connects only channels of the same factory: each factory has its own
ZeroMQ context (ZeroMQ behavior). Thus the tests of two processes cannot connect to each other.
For channels of different factories, use an `ipc://` address with a unique path.
- The name generator puts the transport at the end of the test name. With the CMake file below,
the CTest names are `MyProject.PushPull.OneMessage/zeromq` and
`MyProject.PushPull.OneMessage/shmem`.
Register the tests with the module `GoogleTest` of CMake. FairMQ does the same in
`add_testsuite()` of `cmake/GTestHelper.cmake`:
```cmake title="CMakeLists.txt"
find_package(GTest REQUIRED)
include(GoogleTest)
add_executable(test-channels test_channels.cxx)
target_link_libraries(test-channels PRIVATE FairMQ::FairMQ GTest::gtest_main)
gtest_discover_tests(test-channels
TEST_PREFIX MyProject.
NO_PRETTY_VALUES
PROPERTIES TIMEOUT 20 ENVIRONMENT "FAIRMQ_PATH=${FairMQ_BINDIR}")
```
Without `NO_PRETTY_VALUES`, `gtest_discover_tests()` adds the parameter value to each CTest name,
for example `MyProject.PushPull.OneMessage/zeromq # GetParam() = "zeromq"` (CMake behavior, seen
with CMake 3.28).
The test helpers of FairMQ in `test/` are not installed. An installed FairMQ does not contain them,
so your project cannot include them from there. Copy them into your project if they help:
- `Configure()` in [`test/helper/Transport.h`](https://github.com/FairRootGroup/FairMQ/blob/dev/test/helper/Transport.h)
sets the session, the segment size and the monitor. See
[Make the transport factory](/guides/channels-without-device/#make-the-transport-factory).
- `IpcAddress` makes a unique `ipc://` address and removes the socket file in its destructor:
<Snippet file="test/helper/Transport.h" start="class IpcAddress" />
- `TransportParam`, `AllTransports()` and the name generator `TransportParamName` in
[`test/helper/TransportParam.h`](https://github.com/FairRootGroup/FairMQ/blob/dev/test/helper/TransportParam.h)
run a test for `zeromq`, `shmem`, and `shmem` with expanded metadata. `BasicTransports()` and
`ShmTransports()` select fewer transports.
- The `main()` of the test suites sets `FAIRMQ_PATH` if the environment does not have it
([`test/runner.cxx.in`](https://github.com/FairRootGroup/FairMQ/blob/dev/test/runner.cxx.in)).
The value is the directory `fairmq` of the build tree (`FAIRMQ_TEST_ENVIRONMENT` in
`test/TestEnvironment.h.in`).
To test a device class in the test process, run its state machine in a thread. See
[Run the device in a thread](/guides/control-from-code/#run-the-device-in-a-thread).
To start device processes from C++, use [`tools::execute()`](/reference/tools/#processh). The helper
`RunDevices()` in [`test/helper/Devices.h`](https://github.com/FairRootGroup/FairMQ/blob/dev/test/helper/Devices.h)
starts the test program `testhelper_runTestDevice` of the FairMQ build tree, once for each device.
It calls `execute()` for each device in its own thread, with a default timeout of 15 s. Thus you
cannot copy this helper without the test devices of FairMQ. The session is a new `UuidHash()` as a decimal
number, like the output of `fairmq-uuid-gen -h`. Each device gets the same options as in the script above:
<Snippet file="test/helper/Devices.h" start="cmd << runTestDevice" end='<< " --color false";' />
## Clean up shared memory after a failed test
A device that crashes or that CTest stops does not remove its shared memory. Three things remove
it:
1. **The monitor daemon.** With `--shm-monitor true`, a shmem device starts `fairmq-shmmonitor` as
a daemon if no monitor runs for the session. The daemon removes the memory of the session
2000 ms after the last heartbeat of the devices. The daemon forks and calls `setsid()`, so it
continues after the devices stop. If the transport cannot find
`fairmq-shmmonitor`, it logs `could not find fairmq-shmmonitor in "$FAIRMQ_PATH:$PATH"` and runs
without a daemon.
2. **The trap of the script.** `fairmq-shmmonitor --cleanup --session <session>` removes the
segments, the regions and the monitor mutex of the session. For a session without shared memory,
for example with `zeromq`, it writes a message and removes nothing. Also then, its exit code
is 0.
3. **You.** Find the sessions with `fairmq-shmmonitor --list-all`. Remove one session with its
name from the test output:
```sh
fairmq-shmmonitor --list-all
fairmq-shmmonitor --cleanup --session 1234567890
```
The files are in `/dev/shm`. All names start with `fmq_` or `sem.fmq_`:
```sh
ls -l /dev/shm/ | grep fmq_
```
See [Monitor and clean up](/shmem/monitor/) and [fairmq-shmmonitor](/tools/shmmonitor/) for the
details. A file-backed region keeps its file. Remove it at its path.
## Run the tests
```sh
ctest --test-dir build -R '^MyTopology\.' --output-on-failure
ctest --test-dir build -R '^MyTopology\.' --parallel 4
```
The second command runs the tests at the same time. This is a good check for collisions: each test
must use its own session and its own addresses. After the tests, `ls /dev/shm/ | grep fmq_` must
show no file of your sessions.
You can also run the script directly. Set `FAIRMQ_PATH` first:
```sh
FAIRMQ_PATH=<prefix>/bin bash test-topology.sh shmem build/bin
```
## Problems that can occur
- **A test fails only when tests run in parallel.** Two tests use the same TCP port, the same
`ipc://` path or the same session. With a fixed port in use, `autoBind` binds to a random port,
and the peers do not find the device (see [Automatic ports](/concepts/channels/#automatic-ports)).
They can also connect to the device of the other test. Put the session and the transport in each
`ipc://` path, as above.
- **A test hangs until the timeout.** A device has no end condition, or it does not use
`--control static`. Or a device failed, and its peer waits for messages. Use `set -e` and a trap
for `EXIT`, so that the script stops the others when `wait` returns the error. Set
`TIMEOUT_SIGNAL_NAME`, so that the trap also runs on a timeout. Stop the devices without an end
condition with a signal.
- **A device stops slowly after the signal.** A hook waits in `std::this_thread::sleep_for()` or in
a long loop. See [Handle errors and timeouts](/guides/errors-timeouts/#problems-that-can-occur).
- **The log shows `could not find fairmq-shmmonitor`.** `FAIRMQ_PATH` is not set, and
`fairmq-shmmonitor` is not in `PATH`. Set the environment of the test.
- **`/dev/shm` fills up.** Earlier tests crashed without `--shm-monitor true`. Remove their sessions
with `fairmq-shmmonitor --cleanup`.
- **The test passes, but a device failed.** The script does not wait for each device, or the trap
ends with `exit 0`. Wait for each device, and let a signal end the script with a code other than 0.
## Related pages
- [1-1: sampler and sink](/examples/1-1/#test-the-example): the test script of the simplest example.
- [Use channels without a device](/guides/channels-without-device/): factories and channels in one process.
- [Monitor and clean up](/shmem/monitor/): when shared memory stays and how to remove it.
- [Helpers in fair::mq::tools](/reference/tools/#fairmq-uuid-gen): `fairmq-uuid-gen` and `execute()`.
- [Contributing](/project/contributing/#build-and-test): build and run the tests of FairMQ, and
[Tests with device processes](/project/contributing/#tests-with-device-processes) in FairMQ itself.
- [A CTest cleanup test](/shmem/monitor/#a-ctest-cleanup-test): remove the shared memory after the other tests.
- [When a peer stops or restarts](/guides/errors-timeouts/#when-a-peer-stops-or-restarts): what a test of a restart can check.
- [Parse options without DeviceRunner](/guides/control-from-code/#parse-options-without-devicerunner): configure a device in a test program.

View File

@@ -0,0 +1,226 @@
---
title: 'Write a plugin'
description: 'Write a plugin with its own options, build it as a shared library, load it into a device with -P, and use the plugin API in it.'
sidebar:
order: 7
code: [fairmq/Plugin.h, fairmq/PluginManager.cxx, fairmq/PluginServices.h]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
This guide shows how to write a plugin, build it as a shared library and load it into a device with `-P`. The result
is a device that loads your plugin at startup and accepts the options of the plugin on its command line.
## Before you start
- Install FairMQ. See [Install](/start/install/).
- Have a device that starts with `runDevice.h`, for example `fairmq-sink` or a device of the examples.
- Read [Plugins and control](/concepts/plugins/) for the plugin system and the controller role.
A plugin has four parts:
1. A class that derives from [`fair::mq::Plugin`](/api/fair/mq/Plugin/).
2. A function that declares the options of the plugin. This part is optional.
3. The macro `REGISTER_FAIRMQ_PLUGIN`. It exports the plugin from the library.
4. A shared library with the name `libfairmq-plugin-<name>.so`.
A plugin can also be part of the executable. See
[Put the controller in your program](/guides/control-from-code/#put-the-controller-in-your-program).
The code samples on this page come from the test plugin `test_dummy` (`test/helper/plugins/dummy.h.in`) and from the
built-in control plugin.
## Write the plugin class
<Steps>
1. Include `<fairmq/Plugin.h>`. Derive your class from `fair::mq::Plugin`.
2. Give the class a constructor with the five parameters of the
[`Plugin` constructor](/api/fair/mq/Plugin/#Plugin-2). These are the name, the version, the maintainer, the
homepage and a pointer to `PluginServices`. Pass them to the base class. The macro `REGISTER_FAIRMQ_PLUGIN` calls
this constructor.
3. In the constructor, read your options. Then subscribe to the events that you need, for example to the state
changes.
4. Remove your subscriptions before the plugin goes away. `DeviceRunner` destroys the plugins before the device. The
test plugin unsubscribes in the state `EXITING`. The built-in plugins unsubscribe in their destructors.
</Steps>
<Snippet file="test/helper/plugins/dummy.h.in" start="class DummyPlugin" lang="cpp" />
The base class gives the plugin API: the state, the controller role, the properties and the log settings. The list is
in [What a plugin can do](/concepts/plugins/#what-a-plugin-can-do).
## Add options
<Steps>
1. Write a function without parameters that returns `fair::mq::Plugin::ProgOptions`. This type is
`boost::optional<boost::program_options::options_description>`.
2. Fill an `options_description` with your options and return it. The caption of the description is the heading of
the group in the output of `--help`.
3. For a plugin without options, use `fair::mq::Plugin::NoProgramOptions` in the macro.
</Steps>
<Snippet file="test/helper/plugins/dummy.h.in" start="auto DummyPluginProgramOptions" lang="cpp" />
The device adds these options to its command line. After the parsing, each option is a property with the same name.
Read it in the constructor of the plugin:
```cpp
// An option without a default value is a property only if the command line gives it.
auto const value = GetProperty<std::string>("custom-dummy-option", "nothing");
```
[`GetProperty<T>(key)`](/api/fair/mq/Plugin/#GetProperty) without a fallback value throws
`fair::mq::PropertyNotFoundError` when the property does not exist. The type `T` must be the type of the option, for
example `float` for `--rate`.
## Register the plugin
Write the macro `REGISTER_FAIRMQ_PLUGIN` once, at namespace scope. The built-in control plugin registers itself so:
<Snippet file="fairmq/plugins/control/Control.h" start="REGISTER_FAIRMQ_PLUGIN(" end="^\)" />
| Argument | Meaning |
| --- | --- |
| `KLASS` | The plugin class. |
| `NAME` | The name of the plugin, without quotes. Give this name to `-P`. The file name of the library ends with it: `libfairmq-plugin-NAME.so`. The macro makes function names from it, so use lower-case letters and `_`, for example `test_dummy`. |
| `VERSION` | A [`fair::mq::tools::Version`](/api/fair/mq/tools/Version/) with the major, minor and patch number. Put it in parentheses, `(fair::mq::Plugin::Version{1, 0, 0})`: the commas in the braces otherwise separate macro arguments. See [Version.h](/reference/tools/#versionh). |
| `MAINTAINER` | A string, for example a name and an e-mail address. |
| `HOMEPAGE` | A string with a URL. |
| `PROGOPTIONS` | The function that declares the options, or `fair::mq::Plugin::NoProgramOptions`. |
The macro defines a factory function and exports two symbols: `make_NAME_plugin` and `get_NAME_plugin_progoptions`.
The plugin manager looks for these symbols when it loads the plugin
([Plugin.h](/source/fairmq/Plugin.h/#L145-L151)).
## Build the plugin
Build the plugin as a shared library. The name of the CMake target is `fairmq-plugin-` and the plugin name. CMake
then makes the file `libfairmq-plugin-<name>.so`.
```cmake title="CMakeLists.txt"
cmake_minimum_required(VERSION 3.15)
project(MyPlugin CXX)
find_package(FairMQ REQUIRED)
# FairMQConfig.cmake does not find the dependencies of FairMQ. Find them here.
foreach(dep IN LISTS FairMQ_PACKAGE_DEPENDENCIES)
find_package(${dep} ${FairMQ_${dep}_VERSION} REQUIRED COMPONENTS ${FairMQ_${dep}_COMPONENTS})
endforeach()
add_library(fairmq-plugin-myplugin SHARED myplugin.cxx)
target_link_libraries(fairmq-plugin-myplugin PRIVATE FairMQ::FairMQ)
```
In this sample, `myplugin.cxx` contains the class, the options function and the macro with the name `myplugin`. The
target `FairMQ::FairMQ` gives the include paths, the dependencies and C++17. Without the loop over
`FairMQ_PACKAGE_DEPENDENCIES`, CMake does not find the targets of the dependencies. The prefix `FairMQPlugin_` also works:
the tests of FairMQ build `FairMQPlugin_test_dummy` and `fairmq-plugin-test_dummy2`. See
[Use FairMQ in a CMake project](/start/cmake/) for `find_package()`.
```sh
cmake -S . -B build
cmake --build build
```
## Load the plugin
<Steps>
1. Give the name of the plugin to `-P`. Give `-P` once for each plugin.
2. Give the directory of the library to `-S`, or put it in `LD_LIBRARY_PATH`.
3. Start the device. This command uses the built-in device `fairmq-sink`:
```sh
fairmq-sink --id sink1 \
--channel-config name=data,type=pull,method=bind,address=tcp://*:5555 \
--control static --severity debug \
-P myplugin -S ./build
```
4. Stop the device with Ctrl-C.
</Steps>
To load a plugin from your own `main()`, call `LoadPlugin()` in the runner hook `hooks::LoadPlugins`. The
[custom-controller](/examples/custom-controller/) example does this for a plugin that the executable contains.
To load plugins without `DeviceRunner`, see
[Load plugins without DeviceRunner](/guides/control-from-code/#load-plugins-without-devicerunner).
## Check the result
- `--help` with `-P myplugin -S ./build` prints the options of the plugin, under the caption of its options group.
The device does not start with `--help`.
- With `--severity debug`, the device logs a line for each plugin that it creates, and a line when it destroys the
plugin:
```txt
Loaded plugin: 'myplugin', version '1.0.0', maintainer 'Jane Doe <jane.doe@example.org>', homepage 'https://example.org/myplugin'
```
- With `--severity debug`, the table `Configuration:` lists the options of the plugin that have a value.
## Use the plugin API
### Read and change properties
- [`SetProperty<T>()`](/api/fair/mq/Plugin/#SetProperty) adds or changes a property. It notifies all subscribers.
- [`UpdateProperty<T>()`](/api/fair/mq/Plugin/#UpdateProperty) changes only a property that exists. It returns
`false` otherwise.
- Give the type for text values: `SetProperty<std::string>("key", "value")`. Without it, the property gets the type
`const char*`, and `GetProperty<std::string>()` throws an exception.
The time when a change has an effect depends on the property. See
[Control a device from code](/guides/control-from-code/#read-and-change-properties-at-run-time).
### Follow the state of the device
[`SubscribeToDeviceStateChange()`](/api/fair/mq/Plugin/#SubscribeToDeviceStateChange) calls your function at the
start of each new state, in the thread of the state machine. The device waits until your function returns. For long
work, start a thread in the plugin and stop it in the destructor. The control plugin runs its controller in this way.
:::caution
An exception that leaves a state callback moves the device to `ERROR`. Catch the exceptions in the callback.
:::
### Control the device
A plugin that calls [`TakeDeviceControl()`](/api/fair/mq/Plugin/#TakeDeviceControl) in its constructor gets the
controller role before the control plugin. The plugins of `-P` are created first. See
[Control a device from code](/guides/control-from-code/#control-the-device-from-a-plugin).
### Change the log settings
[`CycleLogConsoleSeverityUp()`](/api/fair/mq/Plugin/#CycleLogConsoleSeverityUp) and the other `CycleLog` functions
change the console severity and the verbosity in steps. To set a value, change the property, for example
`SetProperty<std::string>("severity", "debug")`. See [Logging](/tools/logging/).
## Problems
| Problem | Cause and solution |
| --- | --- |
| `Could not load dynamic plugin myplugin from configured search paths (-S) nor with system lookup …` | The plugin manager found no file, or the file does not load. Check the file name `libfairmq-plugin-myplugin.so`, the directory in `-S` or `LD_LIBRARY_PATH`, and the name in `REGISTER_FAIRMQ_PLUGIN`. |
| `… is not a directory.` | A path of `-S` is a file. Give the directory. |
| `An error occurred while instantiating plugin myplugin: …` | The constructor of the plugin throws, for example `Config has no key: …` from `GetProperty<T>()`. Give a fallback value, or check with `PropertyExists()` first. |
| `Plugin 'myplugin' is not allowed to change device states. Currently, plugin 'control' has taken control.` | The control plugin has the controller role. Take the role in the constructor, or start the device with `--control none`. |
| The device does not end after `EXITING`. | The plugin has the controller role. Call `ReleaseDeviceControl()` in `EXITING`. |
| The options of the plugin do nothing. | The device ignores unknown options. With `--severity debug`, it logs `detected unregistered option: …`. Check that the plugin loads. |
| An unsubscribe function throws `std::out_of_range`. | `UnsubscribeFromPropertyChange<T>()` and `UnsubscribeFromPropertyChangeAsString()` need an existing subscription. Call them only after the subscription. |
## Related pages
- [Plugins and control](/concepts/plugins/): how plugins load, and the controller role.
- [Control a device from code](/guides/control-from-code/): a controller plugin step by step.
- [custom-controller](/examples/custom-controller/): a complete controller plugin.
- [Configuration and properties](/concepts/configuration/): the properties that a plugin reads and sets.

View File

@@ -0,0 +1,24 @@
---
title: FairMQ
description: FairMQ is a C++17 message queuing library and framework for large-scale data processing. It connects processes through channels and moves data without a copy on one host.
template: splash
editUrl: false
lastUpdated: false
hero:
title: Message queuing for large-scale data processing
tagline: FairMQ connects processes through channels. Each process is a device with a state machine. On one host, the shared memory transport moves data without a copy.
actions:
- text: Get started
link: /FairMQ/start/first-device/
variant: primary
- text: Read the concepts
link: /FairMQ/concepts/devices/
variant: secondary
---
import HomePaths from '../../components/home/HomePaths.astro';
import HomeCode from '../../components/home/HomeCode.astro';
<HomePaths />
<HomeCode />

View File

@@ -0,0 +1,407 @@
---
title: 'Contributing'
description: 'Get the code, build and test FairMQ, follow the code style and the commit rules, send a pull request, and work on this documentation.'
sidebar:
order: 1
---
import { Steps, FileTree } from '@astrojs/starlight/components';
import Snippet from '../../../components/Snippet.astro';
FairMQ is developed on GitHub. This page tells you how to get the code, how to build and test it, and which rules your changes must follow. It also tells you how to report a problem and how to work on this documentation.
## Repository and branches
The repository is [FairRootGroup/FairMQ](https://github.com/FairRootGroup/FairMQ) on GitHub.
| Branch or tag | Content |
| --- | --- |
| `dev` | The development branch. Send your pull requests to `dev`. |
| `master` | The latest release. It is the default branch on GitHub. |
| `v1.11.0`, `v1.10.1`, … | The releases. The release tags are on commits of `dev`. |
The [release notes](/project/release-notes/) list the changes of each release and the changes on `dev` that are not released yet.
## Get the code
```sh
git clone -b dev https://github.com/FairRootGroup/FairMQ fairmq_source
```
Do not make a shallow clone. The build reads the version of FairMQ from the Git tags (see [Version](/reference/cmake/#version)).
The bundled packages GoogleTest, PicoSHA2 and FairCMakeModules are Git submodules in `extern/`. The configure step gets the submodules that it needs with `git submodule update --init`.
## Build and test
<Steps>
1. Install the dependencies. See [Install](/start/install/). To install them with Spack, use the file `spack.yaml` of the repository:
```sh
spack --env fairmq_source install
spack env activate fairmq_source
```
2. Configure a debug build with the tests:
```sh
cmake -S fairmq_source -B fairmq_build -G Ninja -DCMAKE_BUILD_TYPE=Debug -DBUILD_TESTING=ON
```
3. Build:
```sh
cmake --build fairmq_build
```
4. Run all tests:
```sh
ctest --test-dir fairmq_build --output-on-failure --parallel "$(nproc)"
```
</Steps>
The debug build compiles with `-Wshadow -Wall -Wextra -Wpedantic`. Your change must compile without warnings, because the CI job `static-analysis` fails on each warning.
### Select tests
The test suites are GoogleTest programs in `test/`: `Channel`, `Device`, `EventManager`, `MemoryResources`, `Message`, `Parts`, `Plugins`, `PluginServices`, `PluginsPrelinked`, `Poller`, `Properties`, `Protocols`, `Region`, `StateMachine`, `Tools` and `Transport`. CTest gives each test the name `<suite>.<test>`, for example `Channel.ConnectedPeers.Pair/zeromq`. Many tests run once for each transport and have the transport in the name. The suite `Tools` tests the [helpers in fair::mq::tools](/reference/tools/). To test your own devices in your project, see [Test your devices](/guides/test-devices/).
The examples add tests with names like `Example.1-1.zeromq` and `Example.builtin-devices.multipart.shmem`.
The tests have no CTest labels. Select tests with a regular expression on the name:
```sh
ctest --test-dir fairmq_build -R '^Channel\.'
ctest --test-dir fairmq_build -R 'shmem'
ctest --test-dir fairmq_build -R '^Example\.'
```
The first command runs the suite `Channel`. The second command runs all tests with `shmem` in the name. The third command runs the tests of the examples.
Each suite is a program `test/testsuite_<suite>` in the build directory. CTest runs it in the build directory. To run some tests of a suite without CTest, give a GoogleTest filter:
```sh
cd fairmq_build
test/testsuite_Channel --gtest_filter='ConnectedPeers.*'
```
CTest stops a test after its timeout: 20 s for most suites, 5 s for `Tools`, and 30 s for the tests of the examples.
:::caution[Locked memory]
Some shared memory tests lock memory in RAM. For example, `Region.PreallocateInsideSession.shmem` locks two segments and two regions, 60 MB in total. If the limit for locked memory is lower, the test fails with `Could not lock the managed segment memory`. Show the limit with `ulimit -l`. The CI sets the limit to `unlimited` before it runs the tests.
:::
### Sanitizers and static analysis
The CI also builds FairMQ with sanitizers and with static analysis. Use the same settings to find problems before you send a change:
- Address, leak and undefined behavior sanitizers, as the CI job `asan+lsan+ubsan`:
```sh
cmake -S fairmq_source -B build_asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DBUILD_TESTING=ON \
-DENABLE_SANITIZER_ADDRESS=ON -DENABLE_SANITIZER_LEAK=ON \
-DENABLE_SANITIZER_UNDEFINED_BEHAVIOR=ON -DFAIRMQ_DEBUG_MODE=ON \
-DCMAKE_CXX_FLAGS="-O1 -fno-omit-frame-pointer"
```
- Static analysis, as the CI job `static-analysis`. The build runs `clang-tidy` and `cpplint` on each file that it compiles, if CMake finds these programs.
```sh
cmake -S fairmq_source -B build_tidy -G Ninja -DCMAKE_BUILD_TYPE=Debug -DBUILD_TESTING=ON \
-DRUN_STATIC_ANALYSIS=ON
```
[CMake options and variables](/reference/cmake/) describes all sanitizer options and the static analysis options.
## Add a test
The tests are GoogleTest programs. `test/CMakeLists.txt` makes one program for each suite with the function `add_testsuite()` of [`cmake/GTestHelper.cmake`](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/GTestHelper.cmake).
<Steps>
1. Write the tests in a source file in the folder of the suite, for example `test/poller/_poller.cxx`. Start the file with the license header.
2. Add the file to the `SOURCES` of the suite in `test/CMakeLists.txt`. For a new suite, make a new folder and add a call of `add_testsuite()`.
3. Configure with `-DBUILD_TESTING=ON`, and build. After the build, CMake runs the suite program and registers each of its tests in CTest (`gtest_discover_tests()`).
4. Run the new tests with `ctest -R`. See [Run the new test](#run-the-new-test).
</Steps>
This is the suite `Poller` in `test/CMakeLists.txt`:
<Snippet file="test/CMakeLists.txt" start="add_testsuite(Poller" end="^\)" />
`${definitions}` and `${environment}` add the compile definitions and the test environment that `test/CMakeLists.txt` sets at the top of the file.
### The arguments of add_testsuite()
| Argument | What it does |
| --- | --- |
| `<name>` | The name of the suite. The program is `test/testsuite_<name>` in the build directory. CTest puts `<name>.` in front of each test name. |
| `SOURCES <file>…` | The source files. Add `${CMAKE_CURRENT_BINARY_DIR}/runner.cxx`. It contains the `main()` of the suite. |
| `LINKS <lib>…` | The libraries. The function adds `GTest::GTest`. The suites link `FairMQ`, the library target of the build. |
| `DEPENDS <target>…` | Targets that CMake must build before the suite, for example `testhelper_runTestDevice`. |
| `INCLUDES <dir>…` | The include directories. The suites need `${CMAKE_CURRENT_SOURCE_DIR}` for `runner.h` and the headers in `test/helper/`, and `${CMAKE_CURRENT_BINARY_DIR}` for the generated `TestEnvironment.h`. |
| `DEFINITIONS <def>…` | Compile definitions. |
| `ENVIRONMENT <var>=<op>:<value>…` | Changes to the environment of each test, in the format of the CTest property `ENVIRONMENT_MODIFICATION`. CMake older than 3.22 ignores this argument. |
| `TIMEOUT <seconds>` | The CTest timeout of each test. The default is 10 s. Most suites set 20 s. |
| `RUN_SERIAL <ON/OFF>` | `ON`: CTest runs no other test at the same time as a test of this suite. The default is `OFF`. No suite sets it at the moment. |
`add_testhelper(<name> …)` makes the program `testhelper_<name>`, which is not a test. It takes `SOURCES`, `LINKS`, `DEPENDS`, `INCLUDES` and `DEFINITIONS`. `add_testlib(<name> …)` makes a shared library. It takes the same arguments, and also `HIDDEN` (hidden symbol visibility) and `VERSION`. The suite `Plugins` uses two of these libraries as plugins.
### Run a test for each transport
The header `test/helper/TransportParam.h` makes a GoogleTest test run once for each transport. Write the test with `TEST_P()` for the fixture `TransportTest`. Then give the transports to `INSTANTIATE_TEST_SUITE_P()`:
<Snippet file="test/poller/_poller.cxx" start="auto RunPoller" end="INSTANTIATE_TEST_SUITE_P" />
| Values | Transports | Test name suffix |
| --- | --- | --- |
| `AllTransports()` | `zeromq`, `shmem`, and `shmem` with `--shm-metadata-msg-size 2048` | `/zeromq`, `/shmem`, `/shmem_expanded_metadata` |
| `BasicTransports()` | `zeromq` and `shmem` | `/zeromq`, `/shmem` |
| `ShmTransports()` | `shmem`, and `shmem` with `--shm-metadata-msg-size 2048` | `/shmem`, `/shmem_expanded_metadata` |
| `testing::Values(TransportParam("zeromq"))` | `zeromq` only | `/zeromq` |
`TransportParamName()` gives the suffix. `GetParam().transport` is the name of the transport. `GetParam().DeviceArgs()` gives the extra command-line options of a device process for this parameter. For example, the suite `Poller` has the tests `Poller.Poller.Subchannel/zeromq` and `Poller.Poller.Channel/shmem_expanded_metadata`.
### Tests with device processes
`RunDevices()` of `test/helper/Devices.h` starts one process of `testhelper_runTestDevice` for each `DeviceSpec`. All processes get the same new session and the transport of `RunOptions`. The default control mode is `static`. The function waits for all processes. It kills a process that runs longer than `RunOptions::timeout`, by default 15 s.
The prefix of the device ID selects the device class, in `getDevice()` of `test/helper/runTestDevice.cxx`. For example, `push_zeromq` starts the class `Push`. A test device derives from `TestDevice` (`test/helper/devices/TestDevice.h`). At the end of its test, it calls `Succeed()`, which logs `test device succeeded, transport: ` and the transport name. `Succeeded()` checks the exit code 0 and this log line.
To add a test device:
<Steps>
1. Write a header `test/helper/devices/Test<Name>.h` with a class that derives from `TestDevice`.
2. Include the header in `test/helper/runTestDevice.cxx`. In `getDevice()`, return your class for a new ID prefix.
3. Add the header to the `SOURCES` of `add_testhelper(runTestDevice …)` in `test/CMakeLists.txt`.
4. Give your suite the argument `DEPENDS testhelper_runTestDevice`.
</Steps>
### Run the new test
Build, and run the suite with CTest:
```sh
cmake --build fairmq_build
ctest --test-dir fairmq_build -R '^Poller\.' --output-on-failure
```
To see the test names without running the tests, add `-N`. To run the tests of one transport, select the suffix, for example `-R '^Poller\..*/shmem$'`. To run the program directly, see [Select tests](#select-tests).
## Add an example
Each example is a folder in `examples/`. Most examples use the function `add_example()` of [`examples/CMakeLists.txt`](https://github.com/FairRootGroup/FairMQ/blob/dev/examples/CMakeLists.txt). It builds the devices, writes the scripts, registers the tests, and installs the programs and the start scripts. The examples `custom-controller`, `dds`, `n-m` and `qc` have their own CMake code.
Example 1-1 has these files:
<FileTree>
- examples/
- CMakeLists.txt calls add_subdirectory(1-1)
- 1-1/
- CMakeLists.txt
- sampler.cxx
- sink.cxx
- fairmq-start-ex-1-1.sh.in the start script
- test-ex-1-1.sh.in the test script
- README.md
</FileTree>
<Steps>
1. Make a folder `examples/<name>/`.
2. Write a file `<device>.cxx` for each device, with `fairmq/runDevice.h`. See `examples/1-1/sampler.cxx`. The test script needs devices that stop by themselves. The devices of example 1-1 have the option `--max-iterations` for this.
3. Write `examples/<name>/CMakeLists.txt` with a call of `add_example()`. Example 1-1 has this call:
<Snippet file="examples/1-1/CMakeLists.txt" lines="9-9" />
4. Write the start script `fairmq-start-ex-<name>.sh.in` and the test script `test-ex-<name>.sh.in`. See [The scripts](#the-scripts).
5. Add `add_subdirectory(<name>)` to `examples/CMakeLists.txt`.
6. Configure with `-DBUILD_TESTING=ON`. `BUILD_EXAMPLES` is `ON` by default. Build, and run the tests of the example:
```sh
ctest --test-dir fairmq_build -R '^Example\.<name>\.' --output-on-failure
```
</Steps>
### The arguments of add_example()
| Argument | What it does |
| --- | --- |
| `NAME <name>` | Required. The name of the example. Without it, CMake stops with `NAME arg is required`. |
| `DEVICE <device>…` | For each device, the program `fairmq-ex-<name>-<device>` from the file `<device>.cxx`, linked to `FairMQ`. |
| `SCRIPT <script>…` | The start scripts `fairmq-start-ex-<script>.sh.in`. The default is one script with the name of the example. |
| `CONFIG` | Copies `ex-<name>.json` to the build directory of the example, and installs it into `share/fairmq/`. The scripts get `@EX_CONF_DIR@`. |
| `TRANSPORT <transport>…` | The transports of the tests. The default is `zeromq` and `shmem`. |
| `VARIANT <variant>…` | One test for each variant and transport, `Example.<name>.<variant>.<transport>`. The test script gets the variant as its second argument. |
| `NO_TRANSPORT` | One test, without the transport argument. Known defect: the test name is `Example.<name>.`, with a dot at the end. |
| `NO_TEST` | No test script and no test. |
Other arguments stop CMake with `Unexpected unparsed arguments`. Without `VARIANT` and `NO_TRANSPORT`, the tests are `Example.<name>.<transport>`, for example `Example.1-1.zeromq` and `Example.1-1.shmem`.
### The scripts
CMake writes two copies of each start script. The copy in the build directory of the example has the name `fairmq-start-ex-<script>.sh`. The copy `fairmq-start-ex-<script>.sh_install` has the paths of the installation, and the install step copies it to `bin/` as `fairmq-start-ex-<script>.sh`. CMake replaces these variables:
| Variable | Build directory | Installation |
| --- | --- | --- |
| `@EX_BIN_DIR@` | The build directory of the example | `<prefix>/bin` |
| `@FAIRMQ_BIN_DIR@` | `<build>/fairmq` | `<prefix>/bin/fairmq` |
| `@EX_CONF_DIR@` (with `CONFIG`) | The build directory of the example | `<prefix>/share/fairmq` |
:::caution[Known defect]
The installed programs of FairMQ are in `<prefix>/bin`, not in `<prefix>/bin/fairmq`. An installed start script that runs a built-in device from `@FAIRMQ_BIN_DIR@` does not find it.
:::
CTest runs `test-ex-<name>.sh <transport>`, or `test-ex-<name>.sh <transport> <variant>`, with a timeout of 30 s. The test passes if the script exits with 0. The install step does not install the test script. This is the test script of example 1-1:
<Snippet file="examples/1-1/test-ex-1-1.sh.in" />
The script starts both devices with `--control static`, `--max-iterations 1` and a new session from `fairmq-uuid-gen`. The `ipc` address contains the session and the transport, so that tests that run at the same time do not use the same address. With `set -e`, a device that fails also fails the test.
:::caution[Variables in the test script]
CMake writes the test script with `configure_file()` without `@ONLY`. Thus CMake replaces `${VAR}` in the script, and also `@VAR@`. Write the shell variables of the test script as `$var`, without braces.
:::
## Code style
- **Format**: [`.clang-format`](https://github.com/FairRootGroup/FairMQ/blob/dev/.clang-format) in the repository root sets the format. It is based on the Mozilla style, with an indent of 4 spaces, no tabs and a column limit of 100. The pointer alignment follows the most frequent style in the file, with left alignment (`int* p`) as the fallback. The existing code does not follow this file everywhere. Format only the lines that you change, for example with `git clang-format`.
- **Checks**: [`.clang-tidy`](https://github.com/FairRootGroup/FairMQ/blob/dev/.clang-tidy) enables a selected set of `misc`, `modernize`, `performance` and `readability` checks. With `RUN_STATIC_ANALYSIS=ON`, the build runs them if CMake finds `clang-tidy`. The CI job `static-analysis` uses this option.
- **Language**: C++17. Put new code in the namespace `fair::mq`. Do not use the deprecated `FairMQ*` names in new code. See [Move from the FairMQ* names](/guides/migrate-names/).
- **License header**: each source file starts with the license header of FairMQ. Copy the header from a file in the same directory. See [License and citation](/project/license/).
The repository has no `.editorconfig` file.
## Commit messages
The commit titles use the Conventional Commits format `type(scope): summary`. The file [`.gitlint`](https://github.com/FairRootGroup/FairMQ/blob/dev/.gitlint) configures the tool gitlint with these rules:
- The type is one of `fix`, `feat`, `build`, `ci`, `docs`, `style`, `refactor`, `perf` and `test`.
- The title has a maximum of 75 characters.
- A body is optional.
The scope is optional. It names the part of FairMQ, for example `shmem`, `zeromq`, `tools` or `test`. Titles from the history:
```txt
fix(shmem): lock the region mutexes in one order
feat(tools): add an execute() overload with a deadline
test(channel): add tcp tests with and without auto-bind
ci: run the tests in parallel
```
Write the summary in the imperative mood. Use the body to tell what changed and why. The history marks a breaking change with `!` after the type or the scope, for example `feat!:` or `feat(ofi)!:`. Most of these commits also have a paragraph `BREAKING CHANGE` in the body. The pull request template also links [the seven rules of a great commit message](https://chris.beams.io/posts/git-commit/#seven-rules).
To check the message of your last commit, install gitlint and run `gitlint` in the repository.
## Pull requests
<Steps>
1. Fork the repository on GitHub and make a branch from `dev`.
2. Make your change, with tests for new behavior.
3. Add your name to `CONTRIBUTORS`. See [Authors and contributors](#authors-and-contributors).
4. Rebase your branch on the latest `dev`.
5. Open a pull request to `dev`. Describe your change, and name the issues that it is related to. The template asks you to confirm three items: the rebase on `dev`, your name in `CONTRIBUTORS` or `AUTHORS`, and the rules for commit messages.
</Steps>
### CI
The workflows are in [`.github/workflows/`](https://github.com/FairRootGroup/FairMQ/tree/dev/.github/workflows).
| Workflow | When it runs | What it does |
| --- | --- | --- |
| `CI` | Each pull request, each push to `master` and `dev` | The job `build` builds FairMQ with GCC 12, 13, 14 and 15 and the Spack environment `test/ci/spack-latest.yaml`, and with GCC 15 and `test/ci/spack-boost187.yaml` (Boost 1.87). It runs the tests and the install step. The job `sanitizers` runs the tests with the address, leak and undefined behavior sanitizers (GCC 14), and with the thread sanitizer (GCC 15). The job `static-analysis` builds with `RUN_STATIC_ANALYSIS=ON` and fails on each warning. |
| `Docs` | Each pull request, each push to `dev`, and a manual start | Builds this site and checks its links. A push to `dev` also publishes the site on GitHub Pages. |
| `Check AUTHORS and CONTRIBUTORS in metadata` | Changes to `AUTHORS`, `CONTRIBUTORS`, `codemeta.json` or `.zenodo.json` | Runs `meta_update.py` and fails if the metadata files change. |
| `validate codemeta` | Changes to `codemeta.json` | Validates `codemeta.json`. |
| `fair-software` | Each push | Measures the compliance with the recommendations of fair-software.eu. |
| `Spack Buildcache` | Each week, a manual start, and a push to `dev` or `master` that changes the Spack files of the CI | Builds the dependencies of the CI and stores them in a Spack build cache. |
The CI gets its dependencies from the Spack environments in `test/ci/`. Dependabot updates the GitHub Actions, the Git submodules and the npm packages of the documentation each month, with pull requests to `dev`.
## Report a problem
Report bugs and ask for features in the [GitHub issues](https://github.com/FairRootGroup/FairMQ/issues/new/choose). The issue templates are `Bug report`, `Feature request` and `Question / Support`.
For a bug report, give the information that the template asks for:
- The steps to reproduce the problem: your environment, the CMake options and the commands.
- The expected behavior.
- The logs.
- The operating system, the compiler and the environment, for example the FairSoft version.
## Authors and contributors
The file [`AUTHORS`](https://github.com/FairRootGroup/FairMQ/blob/dev/AUTHORS) lists the authors of FairMQ. The file [`CONTRIBUTORS`](https://github.com/FairRootGroup/FairMQ/blob/dev/CONTRIBUTORS) lists the other people who contributed. Each line has this format, with an optional e-mail address and an optional ORCID:
```txt
Family name, Given name <e-mail> [https://orcid.org/0000-0000-0000-0000]
```
The files `codemeta.json` and `.zenodo.json` contain the same names. After you change `AUTHORS` or `CONTRIBUTORS`, update them with the script in the repository root:
```sh
python3 meta_update.py
```
Commit the changed metadata files together with your change. The CI workflow `Check AUTHORS and CONTRIBUTORS in metadata` fails if they do not agree. [License and citation](/project/license/) tells how the project uses these names.
## Work on the documentation
This site is in the directory `docs/` of the repository. It uses [Astro](https://astro.build/) and [Starlight](https://starlight.astro.build/).
You need these programs:
- Node.js 22.23.4 or later. `engines` in `docs/package.json` sets this version. The CI uses Node.js 24.
- Doxygen, for the API pages and the source pages. The CI installs the Doxygen package of Ubuntu 24.04.
Run these commands in `docs/`:
| Command | What it does |
| --- | --- |
| `npm ci` | Installs the packages of `package-lock.json`. |
| `npm run dev` | Starts a live preview at `http://localhost:4321/FairMQ/`. |
| `npm run build` | Builds the site in `dist/`. |
| `npm run preview` | Shows the built site from `dist/`. |
| `npm run check` | Checks all internal links and anchors in the built site. Run it after `npm run build`. |
| `node scripts/check-pages.mjs` | Checks the pages without a build: the frontmatter, the MDX syntax, the imports, the links and anchors, and the code snippets. Give page files to check only these pages. |
| `node scripts/print-api.mjs <name> --members` | Lists the API pages with `<name>` in the name, and the anchors of their members. It reads the Doxygen XML. |
`npm run dev` and `npm run build` run Doxygen first if necessary. This occurs if the XML in `docs/build/doxygen/xml/` is missing or older than a `.h` or `.cxx` file in `fairmq/`. If Doxygen is not installed, they stop with an error.
The pages are MDX files in `docs/src/content/docs/<section>/<page>.mdx`. The site makes some content from the code:
- The API pages (`/api/`) and the source pages (`/source/`) come from the headers and sources in `fairmq/`, through the XML output of Doxygen.
- The names, the types and the defaults in the tables of command-line options come from the option definitions in the code. The descriptions are in `src/data/option-texts.mjs`.
- Code samples come from files of the repository, through the component `Snippet`. The build fails if the selected lines do not exist. Use the examples and the tests for samples, because the CI compiles them.
The pages use Simplified Technical English (ASD-STE100): short sentences, the active voice, and one word for one concept. Links to other pages are root-relative, without the base `/FairMQ`, and end with `/`, for example `/concepts/states/`. Each page has the link **Edit page** at the bottom. It opens the file of the page on GitHub.
## Related pages
- [CMake options and variables](/reference/cmake/): all options of the build.
- [Release notes](/project/release-notes/): the changes in each release.
- [License and citation](/project/license/): the license, the copyright holders and how to cite FairMQ.

View File

@@ -0,0 +1,120 @@
---
title: 'License and citation'
description: 'FairMQ is free software under the GNU LGPL version 3 only. This page gives the copyright holders, the bundled code and how to cite FairMQ.'
sidebar:
order: 3
---
FairMQ is free software. You can use it, change it and distribute it under the terms of the GNU Lesser General Public License, version 3 only. This page tells you where the license terms are, who holds the copyright, and how to cite FairMQ in a publication.
## The license
| Item | Value |
| --- | --- |
| License | GNU Lesser General Public License, version 3 only (SPDX identifier `LGPL-3.0-only`) |
| License text | [`LICENSE`](https://github.com/FairRootGroup/FairMQ/blob/dev/LICENSE) in the repository, also at [gnu.org](https://www.gnu.org/licenses/lgpl-3.0.html) |
| Base license | The LGPL version 3 adds permissions to the [GNU General Public License, version 3](https://www.gnu.org/licenses/gpl-3.0.html) (GPL). Read the two documents together. |
| Copyright and license of each file | [`COPYRIGHT`](https://github.com/FairRootGroup/FairMQ/blob/dev/COPYRIGHT), in the Debian machine-readable copyright format |
Each source file of FairMQ starts with this header. The years and the copyright holders change from file to file.
```txt
/********************************************************************************
* Copyright (C) 2021-2023 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH *
* *
* This software is distributed under the terms of the *
* GNU Lesser General Public Licence (LGPL) version 3, *
* copied verbatim in the file "LICENSE" *
********************************************************************************/
```
The source files have no `SPDX-License-Identifier` lines. The header names version 3 and no later version, and `COPYRIGHT` gives `LGPL-3.0-only`. Section 6 of the LGPL lets you use a later version only if the library says "or any later version". FairMQ does not say this.
## What the license means in practice
:::note
This section is a short summary to help you find the related parts of the license. It is not legal advice. Only the text in `LICENSE` and the GPL version 3 are binding. For a legal question, ask a lawyer.
:::
The license uses these terms. FairMQ is the "Library". Your device or program that uses the interfaces of FairMQ is an "Application". An Application that is linked with FairMQ is a "Combined Work".
- **Use without distribution**: section 2 of the GPL lets you make, run and propagate copies without conditions, if you do not convey them.
- **Changed copies of FairMQ**: section 2 of the LGPL and section 5 of the GPL apply when you convey a changed copy of FairMQ.
- **Code from the headers**: the headers of FairMQ contain templates and inline functions, and `runDevice.h` defines `main()`. Section 3 of the LGPL tells what you must do when your object code contains material from these headers.
- **Programs that link FairMQ**: section 4 of the LGPL tells the conditions for a Combined Work. Examples are a notice that the program uses FairMQ, and copies of the GPL and the LGPL. Also, the user must be able to use the program with a changed FairMQ. Section 4 d) 1) names a suitable shared library mechanism as one way. The default build of FairMQ makes the shared library `libfairmq.so`.
## Copyright
`COPYRIGHT` gives these copyright holders for all files of FairMQ:
- GSI Helmholtzzentrum fuer Schwerionenforschung GmbH
- the authors in [`AUTHORS`](https://github.com/FairRootGroup/FairMQ/blob/dev/AUTHORS)
- the contributors in [`CONTRIBUTORS`](https://github.com/FairRootGroup/FairMQ/blob/dev/CONTRIBUTORS)
The Git history shows the copyright of each contributor. The files [`MemoryResources.h`](/source/fairmq/MemoryResources.h/), [`MemoryResources.cxx`](/source/fairmq/MemoryResources.cxx/) and [`MemoryResourceTools.h`](/source/fairmq/MemoryResourceTools.h/) have a second copyright holder: CERN and the copyright holders of ALICE O2.
The upstream contact in `COPYRIGHT` is Mohammad Al-Turany. The maintainer in `codemeta.json` is the [GSI Helmholtz Centre for Heavy Ion Research](https://ror.org/02k8cbn47).
## Bundled code
The repository contains other projects as Git submodules in `extern/`. They have their own licenses.
| Submodule | Copyright | License | Use in FairMQ |
| --- | --- | --- | --- |
| [GoogleTest](https://github.com/google/googletest) | Google Inc. | BSD-style, 3 clauses (text in `COPYRIGHT`) | The tests. It is not in the installed library. |
| [PicoSHA2](https://github.com/okdshin/PicoSHA2) | okdshin | MIT (text in `COPYRIGHT`) | The shmem transport makes the shared memory ID of a session with its SHA-256 function. This ID is in the names of the shared memory objects. PicoSHA2 is compiled into `libfairmq`. |
| [FairCMakeModules](https://github.com/FairRootGroup/FairCMakeModules) | GSI | GNU LGPL version 3 (`LICENSE` of the submodule) | CMake modules for the build, if CMake does not find an installed FairCMakeModules. |
The dependencies outside of the repository, for example Boost, FairLogger and ZeroMQ, have their own licenses. See [Install](/start/install/#requirements) for the list.
## Cite FairMQ
FairMQ has a DOI on Zenodo: [10.5281/zenodo.1689985](https://doi.org/10.5281/zenodo.1689985). The README and `codemeta.json` give this DOI.
When you cite FairMQ, give the version that you used. The text below cites v1.11.0. Change the version and the year for a different release. The [release notes](/project/release-notes/) give the date of each release.
```txt
Al-Turany, M., Klein, D., Kollegger, T., Rybalchenko, A., & Winckler, N. (2026).
FairMQ: C++ Message Queuing Library and Framework (Version 1.11.0) [Computer software].
Zenodo. https://doi.org/10.5281/zenodo.1689985
```
```txt title="fairmq.bib"
@software{fairmq,
author = {Al-Turany, Mohammad and Klein, Dennis and Kollegger, Thorsten and
Rybalchenko, Alexey and Winckler, Nicolas},
title = {{FairMQ}: {C++} Message Queuing Library and Framework},
version = {1.11.0},
year = {2026},
publisher = {Zenodo},
doi = {10.5281/zenodo.1689985},
url = {https://doi.org/10.5281/zenodo.1689985}
}
```
The entry type `@software` needs biblatex. For BibTeX styles without it, use `@misc`.
The names, the title and the description come from the metadata files of the repository:
- [`codemeta.json`](https://github.com/FairRootGroup/FairMQ/blob/dev/codemeta.json): the name, the description `C++ Message Queuing Library and Framework`, the DOI, the authors, the contributors and the maintainer.
- [`.zenodo.json`](https://github.com/FairRootGroup/FairMQ/blob/dev/.zenodo.json): the creators and the contributors of the Zenodo record.
## Authors and contributors
The authors of FairMQ are in `AUTHORS`:
| Author | ORCID |
| --- | --- |
| Mohammad Al-Turany | [0000-0002-8071-4497](https://orcid.org/0000-0002-8071-4497) |
| Dennis Klein | [0000-0003-3787-1910](https://orcid.org/0000-0003-3787-1910) |
| Thorsten Kollegger | — |
| Alexey Rybalchenko | [0000-0002-6249-155X](https://orcid.org/0000-0002-6249-155X) |
| Nicolas Winckler | — |
[`CONTRIBUTORS`](https://github.com/FairRootGroup/FairMQ/blob/dev/CONTRIBUTORS) lists the other people who contributed code. The script `meta_update.py` copies the two lists into `codemeta.json` and `.zenodo.json`. Thus the citation metadata agrees with the files. To add your name, see [Authors and contributors](/project/contributing/#authors-and-contributors).
## Related pages
- [Contributing](/project/contributing/): add your name and send a change.
- [Release notes](/project/release-notes/): the versions and their dates.
- [Install](/start/install/): the dependencies and their versions.

View File

@@ -0,0 +1,181 @@
---
title: 'Release notes'
description: 'The changes in each FairMQ release from v1.5.0 to v1.11.0, the breaking changes, and the changes on dev that are not released yet.'
sidebar:
order: 2
---
import { Badge } from '@astrojs/starlight/components';
This page lists the changes in each release of FairMQ, the newest release first. The source of each section is the GitHub release and the Git history. <Badge text="Breaking" variant="danger" /> marks a change that can stop your code or your build, or that stops devices of the new and of an older version from working together in one shared memory session. Read these items before you update.
FairMQ does not keep ABI compatibility between releases. After each update, build your devices again. See [Install layout](/reference/cmake/#install-layout).
## Mixed versions
With the `shmem` transport, use the same FairMQ version for all devices of a session. With the `zeromq` transport, the FairMQ version does not change the bytes on the connection.
**zeromq.** The transport sends a message as one ZeroMQ frame that contains only your data. It sends a multipart message as a ZeroMQ multipart message with one frame for each part (`fairmq/zeromq/Socket.h`). FairMQ adds no header and no version number. The compatibility of different ZeroMQ versions is ZeroMQ behavior.
**shmem.** The transport keeps the data in shared memory and sends only metadata through ZeroMQ. The receiver copies the bytes of the metadata into its own [`MetaHeader`](/api/fair/mq/shmem/MetaHeader/) (`fairmq/shmem/Socket.h`). All devices of a session also use the same management segment, managed segments and regions. The metadata and the structures in shared memory contain no version number, and the transport does not compare the versions of the devices. These releases changed the data that the devices of a session share:
| Release | Change |
| --- | --- |
| v1.6.0 | The metadata message of a multipart message starts with the number of parts, a `size_t`. Before, the receiver calculated the number from the message size. Since v1.6.0, the sender pads each metadata message to `--shm-metadata-msg-size` (default 0: no padding). A receiver of v1.5.x accepts a single-part metadata message only with the exact size of one `MetaHeader`, and a multipart metadata message only with a multiple of this size. A receiver of v1.6.0 or later reads the first `size_t` of a multipart metadata message of v1.5.x as the number of parts. |
| v1.8.1 | The entry of a region in the management segment ([`RegionInfo`](/api/fair/mq/shmem/RegionInfo/)) has the new field `fRCSegmentSize`. The reference count of a copied region message is in the reference count segment of the region. Before, it was in a managed segment. |
| v1.9.0 | The pool of the reference counts in the reference count segment of a region has a different type of Boost.Interprocess: `node_allocator` instead of `adaptive_pool`. |
The fields of `MetaHeader` are the same from v1.5.0 to `dev`. The changes on `dev` after v1.11.0 do not change the metadata or the structures in shared memory.
The segments and the regions are objects of Boost.Interprocess. Their layout in memory is Boost behavior, and FairMQ does not check the Boost version of the other devices. To see the versions of a device, read its log. At start, a device program with `fairmq/runDevice.h` logs a logo with `version` and the Git version of FairMQ (severity `info`). The shmem transport logs `Transport: Using ZeroMQ (…) & boost::interprocess (…)` with the two versions (severity `debug`).
## Unreleased on dev
These changes are on the branch `dev` after v1.11.0. They are not in a release yet. [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.11.0...dev).
- **New**: `fair::mq::tools::execute()` has an overload with a timeout of type `std::chrono::milliseconds`. It stops the child process with `SIGKILL` after the timeout. The old overload has no limit. See [`execute()`](/api/fair/mq/tools/#execute-2) and [Process.h](/reference/tools/#processh).
- **Fixed**: shmem: a message that received a block of a region, was rebuilt, and then received a block of a second region released this block to the first region. Now each block goes back to its own region.
- **Fixed**: shmem: a thread that creates a region and a thread that opens a region in the same session can no longer deadlock.
- **Fixed**: shmem: a region callback that calls the transport while the region is removed no longer blocks. Before, this blocked all processes of the session.
- **Fixed**: shmem: the removal of a region took a minimum of 500 ms. Now the thread that sends the acknowledgements stops without this wait.
- **Fixed**: zeromq and shmem: a socket stops its socket monitor before it closes. This removes a memory leak of monitor events ([#463](https://github.com/FairRootGroup/FairMQ/issues/463)).
- **Tests**: many new tests for the state machine, the device, the channels, the properties, the tools and the shmem monitor. Many tests run once for each transport, and the test name ends with the transport. Multi-process tests use one test harness. See [Contributing](/project/contributing/#select-tests) and [Add a test](/project/contributing/#add-a-test).
- **CI**: the tests run in parallel. The job `asan+lsan+ubsan` builds with `FAIRMQ_DEBUG_MODE=ON`.
- **Docs**: this documentation site is new.
- <Badge text="Breaking" variant="danger" /> **Build**: the CMake option `BUILD_DOCS` and the package component `docs` are removed. `find_package(FairMQ COMPONENTS docs)` fails.
- **Build**: the bundled GoogleTest is updated to commit `a8380b0`.
## v1.11.0
Released 2026-06-10 · [GitHub release](https://github.com/FairRootGroup/FairMQ/releases/tag/v1.11.0) · [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.10.1...v1.11.0)
- **New**: shmem: the side-channel metadata API. A device can send the metadata of a shmem message in its own format. A device of the same session then reads the data in place ([#555](https://github.com/FairRootGroup/FairMQ/pull/555)). See [Out-of-band buffers](/shmem/side-channel/).
- **Fixed**: shmem: a failed region lookup stayed in the region cache, so all later lookups of this region failed also. Now a later lookup tries again.
- **Fixed**: `fair::mq::tools::execute()`: calls from several threads write the captured output one line at a time. Before, this was a data race.
- **Changed**: a channel compiles the regular expression for the validation of its name only once.
- **Build**: `.clang-tidy` enables only a selected set of checks, and the code has no warnings for these checks. See [Code style](/project/contributing/#code-style).
- **Build**: the new CMake variable `FAIRMQ_TEST_LD_LIBRARY_PATH` adds a directory to `LD_LIBRARY_PATH` of each test. See [Other variables](/reference/cmake/#other-variables).
- **Build**: linker flags from the CMake command line no longer break the link command.
- **CI**: the job `tsan` uses GCC with an instrumented `libzmq` and `libstdc++`. The job `static-analysis` fails on each warning. The jobs use ccache and a higher limit for locked memory.
- **Build**: the bundled GoogleTest is updated to commit `9156d4c`.
## v1.10.1
Released 2026-01-05 · [GitHub release](https://github.com/FairRootGroup/FairMQ/releases/tag/v1.10.1) · [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.10.0...v1.10.1)
- **Fixed**: FairMQ builds with Boost 1.89 and later. It uses the Boost.Process v1 API from `boost/process/v1.hpp` ([#538](https://github.com/FairRootGroup/FairMQ/pull/538)).
- **Build**: CMake stops with an error for Boost 1.88. This Boost version has no Boost.Process v1 API. Use Boost 1.87 or earlier, or 1.89 or later.
- **CI**: the CI moves from Jenkins to GitHub Actions. Spack installs the dependencies. The jobs build with GCC 12 to 15 and with Boost 1.87, and run the sanitizers and the static analysis.
## v1.10.0
Released 2025-06-13 · [GitHub release](https://github.com/FairRootGroup/FairMQ/releases/tag/v1.10.0) · [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.9.2...v1.10.0)
- <Badge text="Breaking" variant="danger" /> **Changed**: `fair::mq::pmr` is now an alias of `std::pmr`. Before, it was an alias of `boost::container::pmr` ([#532](https://github.com/FairRootGroup/FairMQ/pull/532)). Code that uses Boost memory resources with FairMQ must change to `std::pmr`. See [Use std::pmr memory resources](/guides/pmr/).
## v1.9.2
Released 2025-03-17 · [GitHub release](https://github.com/FairRootGroup/FairMQ/releases/tag/v1.9.2) · [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.9.1...v1.9.2)
- **Changed**: `cmake --install` also installs the shmem headers `Manager.h`, `Message.h`, `Poller.h`, `Socket.h`, `TransportFactory.h` and `UnmanagedRegionImpl.h` in `include/fairmq/shmem/`.
## v1.9.1
Released 2025-01-23 · [GitHub release](https://github.com/FairRootGroup/FairMQ/releases/tag/v1.9.1) · [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.9.0...v1.9.1)
- **Changed**: some methods of `EventManager` are compiled in the library and not in the header.
## v1.9.0
Released 2025-01-09 · [GitHub release](https://github.com/FairRootGroup/FairMQ/releases/tag/v1.9.0) · [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.8.4...v1.9.0)
- <Badge text="Breaking" variant="danger" /> **Changed**: the headers `Device.h`, `Channel.h`, `Message.h`, `TransportFactory.h` and `UnmanagedRegion.h` include `fairmq/TransportEnum.h` and no longer `fairmq/Transports.h` ([#519](https://github.com/FairRootGroup/FairMQ/pull/519)). If your code uses `TransportName()`, `TransportType()`, `TransportError` or `operator<<` for `Transport`, include `fairmq/Transports.h`.
- **New**: the control mode `--control none`. The control plugin does not take the controller role, so another plugin or your code must change the states ([#503](https://github.com/FairRootGroup/FairMQ/pull/503)). See [Control modes](/concepts/plugins/#control-modes).
- **Fixed**: shmem: the reference count segment of the regions had a low performance ([#501](https://github.com/FairRootGroup/FairMQ/pull/501)).
- <Badge text="Breaking" variant="danger" /> **Changed**: shmem: the reference counts of copied region messages use the pool type `node_allocator` instead of `adaptive_pool` (commit `0e221b28`). Do not copy region messages in a session with devices of v1.8.x and of v1.9.0 or later. See [Mixed versions](#mixed-versions).
- **Changed**: the multipart `Send()` and `Receive()` of a socket take a `Parts::container` ([#507](https://github.com/FairRootGroup/FairMQ/pull/507)). This type is `std::vector<MessagePtr>`, as before.
- **Changed**: `ProgOptions::SetProperty()` for `int` and `std::string` is compiled in the library and not in the header ([#518](https://github.com/FairRootGroup/FairMQ/pull/518)).
- **Build**: FairMQ builds with Boost 1.87 ([#521](https://github.com/FairRootGroup/FairMQ/pull/521)).
- **Build**: the project uses all CMake policies up to CMake 3.30 ([#512](https://github.com/FairRootGroup/FairMQ/pull/512)).
- **CI**: a workflow checks that `codemeta.json` and `.zenodo.json` agree with `AUTHORS` and `CONTRIBUTORS` ([#498](https://github.com/FairRootGroup/FairMQ/pull/498)). Dependabot updates the GitHub Actions and the Git submodules.
- **Build**: the bundled GoogleTest is updated to commit `7d76a23`.
## v1.8.4
Released 2023-11-29 · [GitHub release](https://github.com/FairRootGroup/FairMQ/releases/tag/v1.8.4) · [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.8.3...v1.8.4)
- **Changed**: shmem: if `RegionConfig::rcSegmentSize` is 0, a region uses the reference counting from before v1.8.1 ([#493](https://github.com/FairRootGroup/FairMQ/pull/493)). See [`RegionConfig`](/api/fair/mq/RegionConfig/#rcSegmentSize).
## v1.8.3
Released 2023-11-24 · [GitHub release](https://github.com/FairRootGroup/FairMQ/releases/tag/v1.8.3) · [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.8.2...v1.8.3)
- **Fixed**: shmem: the creation of a reference count segment did not use the stored configuration of the region ([#492](https://github.com/FairRootGroup/FairMQ/pull/492)).
## v1.8.2
Released 2023-11-15 · [GitHub release](https://github.com/FairRootGroup/FairMQ/releases/tag/v1.8.2) · [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.8.1...v1.8.2)
- **Changed**: shmem: the default size of the reference count segment increases to 100,000,000 bytes ([#490](https://github.com/FairRootGroup/FairMQ/pull/490)).
- **Changed**: shmem: the error message is better when the reference count segment has no free space. The transport throws `RefCountBadAlloc` ([#490](https://github.com/FairRootGroup/FairMQ/pull/490)).
## v1.8.1
Released 2023-11-10 · [GitHub release](https://github.com/FairRootGroup/FairMQ/releases/tag/v1.8.1) · [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.8.0...v1.8.1)
- **Changed**: shmem: the reference counts of region messages are in a pool in a dedicated segment. `RegionConfig::rcSegmentSize` sets the size of this segment ([#484](https://github.com/FairRootGroup/FairMQ/pull/484)). See [Copies of region messages](/shmem/regions/#copies-of-region-messages).
- <Badge text="Breaking" variant="danger" /> **Changed**: shmem: the entry of a region in the management segment has a new field. Do not use devices of v1.8.0 or earlier in a session with devices of v1.8.1 or later. See [Mixed versions](#mixed-versions).
- **Changed**: shmem: the `Message` class is smaller ([#485](https://github.com/FairRootGroup/FairMQ/pull/485)). `Message::SetUsedSize()` has an optional alignment argument.
- **Fixed**: the state machine protects the containers of its subscriptions with a mutex.
- **Fixed**: tests no longer use the same addresses.
## v1.8.0
Released 2023-09-06 · [GitHub release](https://github.com/FairRootGroup/FairMQ/releases/tag/v1.8.0) · [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.7.0...v1.8.0)
- **New**: `StateMachine::SubscribeToStateChange()` calls the callbacks in the order of the number at the start of their key ([#481](https://github.com/FairRootGroup/FairMQ/pull/481)). See [`SubscribeToStateChange()`](/api/fair/mq/StateMachine/#SubscribeToStateChange).
## v1.7.0
Released 2023-06-26 · [GitHub release](https://github.com/FairRootGroup/FairMQ/releases/tag/v1.7.0) · [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.6.0...v1.7.0)
- **New**: the CMake variable `FAIRMQ_CHANNEL_DEFAULT_AUTOBIND` sets the default of the channel property `autoBind` ([#475](https://github.com/FairRootGroup/FairMQ/pull/475)). See [Compile definitions](/reference/cmake/#compile-definitions).
## v1.6.0
Released 2023-06-13 · [GitHub release](https://github.com/FairRootGroup/FairMQ/releases/tag/v1.6.0) · [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.5.0...v1.6.0)
- **New**: the option `--shm-metadata-msg-size` sets the size of the zeromq message that carries the shmem metadata ([#435](https://github.com/FairRootGroup/FairMQ/pull/435)). See [Options](/reference/options/).
- <Badge text="Breaking" variant="danger" /> **Changed**: shmem: the metadata message of a multipart message starts with the number of parts. Devices of v1.6.0 or later and devices of v1.5.x cannot exchange multipart shmem messages. See [Mixed versions](#mixed-versions).
- **Fixed**: the compiler warning `-Wunqualified-std-cast-call`.
## v1.5.0
Released 2023-03-07 · [GitHub release](https://github.com/FairRootGroup/FairMQ/releases/tag/v1.5.0) · [All changes](https://github.com/FairRootGroup/FairMQ/compare/v1.4.56...v1.5.0)
- <Badge text="Breaking" variant="danger" /> **Removed**: the components `sdk`, `sdk_commands` and `dds_plugin` ([discussion #392](https://github.com/FairRootGroup/FairMQ/discussions/392)). They moved to the [ODC](https://github.com/FairRootGroup/ODC) project.
- <Badge text="Breaking" variant="danger" /> **Changed**: FairMQ is one shared library again. The exported targets `FairMQ::Tools` and `FairMQ::StateMachine` are removed. Link `FairMQ::FairMQ`.
- <Badge text="Breaking" variant="danger" /> **Changed**: the default of `--shm-monitor` is `false`. By default, the shmem transport does not start the monitor daemon.
- <Badge text="Breaking" variant="danger" /> **Removed**: `Device::TransitionTo()`, without a replacement.
- <Badge text="Breaking" variant="danger" /> **Removed**: the experimental `ofi` transport and the experimental `PMIx` plugin.
- <Badge text="Breaking" variant="danger" /> **Changed**: FairMQ uses `std::filesystem`. To use Boost.Filesystem, set `-DFAIRMQ_HAS_STD_FILESYSTEM=0`. The default is 1 for GCC 9 or later and Clang 9 or later.
- **Deprecated**: the headers and the type names without a namespace, for example `FairMQDevice.h` and `FairMQDevice` ([discussion #423](https://github.com/FairRootGroup/FairMQ/discussions/423)). See [Move from the FairMQ* names](/guides/migrate-names/).
- **Deprecated**: `Device::fChannels`.
- **New**: library and plugin files have kebab-case names, for example `libfairmq-plugin-myplugin.so`. The old names, for example `libFairMQPlugin_myplugin.so`, continue to work.
- **New**: `Device::ChangeState()` is `[[nodiscard]]`. `Device::ChangeStateOrThrow()` throws an exception if the transition is not possible ([#441](https://github.com/FairRootGroup/FairMQ/issues/441)). See [`ChangeStateOrThrow()`](/api/fair/mq/Device/#ChangeStateOrThrow).
- **New**: `operator<<` for `fair::mq::Channel`.
- **New**: the example [custom-controller](/examples/custom-controller/), with a controller plugin that is compiled into the device.
- **Changed**: the ABI version is equal to the release version. FairMQ does not keep ABI compatibility between releases.
- **Changed**: the build types `Release` and `RelWithDebInfo` compile with `-O3` instead of `-O2`.
- **Fixed**: zeromq: messages of the monitor socket leaked.
- **Fixed**: the device protects its container of transports with a mutex.
## Older releases
The [releases page on GitHub](https://github.com/FairRootGroup/FairMQ/releases) lists all releases, also v1.4.56 and earlier.
## Related pages
- [Install](/start/install/): install a release.
- [Contributing](/project/contributing/): the branches and the release tags.
- [Move from the FairMQ* names](/guides/migrate-names/): replace the names that v1.5.0 deprecates.

View File

@@ -0,0 +1,246 @@
---
title: 'Channel properties'
description: 'All properties of a sub-channel: keys, types, defaults, allowed values and effects, read from the code.'
sidebar:
order: 2
code: [fairmq/Channel.h, fairmq/Channel.cxx, fairmq/JSONParser.cxx, fairmq/SuboptParser.cxx, fairmq/zeromq/Socket.h]
---
import Snippet from '../../../components/Snippet.astro';
Each sub-channel of a device has the properties on this page. You give them with `--channel-config`, in a JSON file, or as properties from code. The defaults are the `Default*` constants of [`fair::mq::Channel`](/api/fair/mq/Channel/).
## Keys
A property has the same key in the three places:
| Place | Form | Example |
| --- | --- | --- |
| [`--channel-config`](/reference/options/#opt-channel-config) | `key=value` in the list of the channel | `name=data,type=push,sndBufSize=500` |
| [JSON file](/reference/json/) | `"key": value` in a channel or in a socket | `"sndBufSize": 500` |
| Property | `chans.<name>.<index>.<key>` | `chans.data.0.sndBufSize` |
The keys are case-sensitive. The `--channel-config` parser logs a warning for an unknown key and ignores it ([SuboptParser.cxx](/source/fairmq/SuboptParser.cxx/#L111-L113)). The JSON parser ignores unknown keys without a message. `name` and `numSockets` have no property key: `name` is a part of the key, and `numSockets` is an instruction to the parser.
## All properties
The type is the C++ type of the property. The parsers of `--channel-config` and of JSON files convert the values to this type. A value that the parser cannot convert gives the default, without a message ([_jsonparser.cxx](https://github.com/FairRootGroup/FairMQ/blob/dev/test/properties/_jsonparser.cxx#L157-L161)).
| Key | Type | Default | Allowed values | Effect |
| --- | --- | --- | --- | --- |
| [`name`](#name) | string | none | `a`–`z`, `A`–`Z`, `0`–`9`, `-`, `_`, `[`, `]`, `#` | Name of the channel. |
| [`type`](#type) | string | [`unspecified`](/source/fairmq/Channel.h/#L369) | `push`, `pull`, `pub`, `sub`, `req`, `rep`, `dealer`, `router`, `xpub`, `xsub`, `pair` | Socket type. |
| [`method`](#method) | string | [`unspecified`](/source/fairmq/Channel.h/#L370) | `bind`, `connect` | Bind or connect the endpoints. |
| [`address`](#address) | string | [`unspecified`](/source/fairmq/Channel.h/#L371) | One or more endpoints, separated by `,` | Endpoints of the socket. |
| [`transport`](#transport) | string | [`default`](/source/fairmq/Channel.h/#L367) | `default`, `zeromq`, `shmem` | Transport of the sub-channel. |
| [`sndBufSize`](#sndbufsize-and-rcvbufsize) | int | [`1000`](/source/fairmq/Channel.h/#L372) | 0 or more | Maximum number of messages in the send queue. |
| [`rcvBufSize`](#sndbufsize-and-rcvbufsize) | int | [`1000`](/source/fairmq/Channel.h/#L373) | 0 or more | Maximum number of messages in the receive queue. |
| [`sndKernelSize`](#sndkernelsize-and-rcvkernelsize) | int | [`0`](/source/fairmq/Channel.h/#L374) | 0 or more | Kernel send buffer in bytes. 0: system default. |
| [`rcvKernelSize`](#sndkernelsize-and-rcvkernelsize) | int | [`0`](/source/fairmq/Channel.h/#L375) | 0 or more | Kernel receive buffer in bytes. 0: system default. |
| [`sndTimeoutMs`](#sndtimeoutms-and-rcvtimeoutms) | int | [`-1`](/source/fairmq/Channel.h/#L376) | -1, 0 or more | Default timeout of a send call in ms. |
| [`rcvTimeoutMs`](#sndtimeoutms-and-rcvtimeoutms) | int | [`-1`](/source/fairmq/Channel.h/#L377) | -1, 0 or more | Default timeout of a receive call in ms. |
| [`linger`](#linger) | int | [`500`](/source/fairmq/Channel.h/#L378) | -1, 0 or more | Time in ms that the socket keeps unsent messages after it closes. |
| [`rateLogging`](#ratelogging) | int | [`1`](/source/fairmq/Channel.h/#L379) | 0 or more | Interval of the rate log in seconds. 0: no rate log. |
| [`portRangeMin`](#portrangemin-portrangemax-and-autobind) | int | [`22000`](/source/fairmq/Channel.h/#L380) | A TCP port | Lowest port for autobind. |
| [`portRangeMax`](#portrangemin-portrangemax-and-autobind) | int | [`23000`](/source/fairmq/Channel.h/#L381) | A TCP port | Highest port for autobind. |
| [`autoBind`](#portrangemin-portrangemax-and-autobind) | bool | [`true`](/source/fairmq/Channel.h/#L382-L386) | `true`, `false`, `1`, `0` | Bind to a random port of the range when the bind fails. |
| [`numSockets`](#numsockets) | int | [`0`](/source/fairmq/JSONParser.cxx/#L108) | 0 or more | Number of sub-channels with the same properties. |
The JSON parser uses the same defaults ([JSONParser.cxx](/source/fairmq/JSONParser.cxx/#L90-L105)). The device also uses them for a property that is not set ([Channel.cxx](/source/fairmq/Channel.cxx/#L92-L112)).
## The properties in detail
### `name`
The name of the channel. In `--channel-config`, write `name=data`, or put the name and a colon before the first key: `data:type=push,...` ([SuboptParser.cxx](/source/fairmq/SuboptParser.cxx/#L91-L98)). Each channel must have a name. Without it, the parsers of JSON files and of `--channel-config` throw `boost::property_tree::ptree_bad_path` ([JSONParser.cxx](/source/fairmq/JSONParser.cxx/#L107)). The `--channel-config` parser first logs `missing channel name in argument of option --channel-config`. The config plugin logs the exception, and the device gets no channels from this configuration. In the property key, the name is the `<name>` part of `chans.<name>.<index>.<key>`.
A sub-channel has the name `<name>[<index>]`, for example `data[0]`. Before the device attaches a sub-channel, [`Channel::Validate()`](/api/fair/mq/Channel/#Validate) checks this full name ([Channel.cxx](/source/fairmq/Channel.cxx/#L183-L190)). The allowed characters are `a`–`z`, `A`–`Z`, `0`–`9`, `-`, `_`, `[`, `]` and `#`. For another character, the device logs `channel name contains illegal character` and does not attach the sub-channel. The device then goes to `ERROR`: at once for a binding sub-channel, after the time of `--init-timeout` for a connecting sub-channel ([Device.cxx](/source/fairmq/Device.cxx/#L217-L265)).
### `type`
The type of the socket: `push`, `pull`, `pub`, `sub`, `req`, `rep`, `dealer`, `router`, `xpub`, `xsub` or `pair` ([Channel.cxx](/source/fairmq/Channel.cxx/#L193-L199)). Each type is the ZeroMQ socket type of the same name ([zeromq/Common.h](/source/fairmq/zeromq/Common.h/#L91-L123)). [Channels and sockets](/concepts/channels/#socket-types-and-patterns) describes the patterns.
- The default `unspecified` is not valid. `Validate()` throws [`Channel::ChannelConfigurationError`](/api/fair/mq/Channel/ChannelConfigurationError/) with `Invalid channel type: 'unspecified'`, and the device goes to the state `ERROR`.
- The `shmem` transport throws `SocketError` for `pub` and `sub`: `PUB/SUB socket type is not supported for shared memory transport` ([shmem/Socket.h](/source/fairmq/shmem/Socket.h/#L59-L62)).
- A `sub` socket of the `zeromq` transport subscribes to all messages ([zeromq/Socket.h](/source/fairmq/zeromq/Socket.h/#L70-L74)).
### `method`
- `bind`: the socket waits for peers on its endpoints.
- `connect`: the socket connects to the endpoints of a peer.
The method also sets the state in which the device attaches the sub-channel: `bind` in `BINDING`, `connect` in `CONNECTING` ([Device.cxx](/source/fairmq/Device.cxx/#L185-L210)). An endpoint modifier (`@`, `+` or `>`, see [`address`](#address)) overrides the method for its endpoint.
The device attaches a sub-channel without a method in `CONNECTING`, if its address contains `@`, `+` or `>`. Give a modifier for each endpoint of such a sub-channel. Without a method and without a modifier, the device logs `Cannot update configuration. Socket method (bind/connect) for channel 'data[0]' not specified.` and goes to `ERROR`.
### `address`
One endpoint, or several endpoints separated by `,`. Each endpoint has the form `[modifier]protocol://location`.
| Protocol | Form | `Validate()` checks | Use |
| --- | --- | --- | --- |
| `tcp://` | `tcp://host:port` | A `:` after `tcp://` | Between hosts, or on one host |
| `ipc://` | `ipc://path` | The path is not empty | Between processes on one host, through a Unix domain socket file |
| `inproc://` | `inproc://name` | The name is not empty | Between sub-channels of one device that use the same transport |
The checks are in [Channel.cxx](/source/fairmq/Channel.cxx/#L201-L270). For an address with another protocol, the device logs `missing protocol specifier?` and does not attach the sub-channel, with the same result as for a wrong name. `Validate()` also accepts `verbs://`. This is a remainder of the removed `ofi` transport: the `zeromq` and `shmem` transports cannot use such an address.
**Host of a TCP endpoint.** In a bind, the host is `*` (all interfaces), an IPv4 address or a host name. In a connect, the host is an IPv4 address or a host name. Before it binds or connects, the device replaces a host name with its first IPv4 address ([Device.cxx](/source/fairmq/Device.cxx/#L321-L333), [Network.cxx](/source/fairmq/tools/Network.cxx/#L160-L177)). If the name does not resolve, the device logs `failed to attach channel`. The [network helpers](/reference/tools/#networkh) resolve names and find the addresses of the interfaces.
**Modifiers.** A modifier before an endpoint sets the method of this endpoint ([Device.cxx](/source/fairmq/Device.cxx/#L311-L319)):
| Modifier | Effect | Example |
| --- | --- | --- |
| `@` | Bind this endpoint. | `@tcp://*:5556` |
| `+` or `>` | Connect this endpoint. | `+tcp://host1:5555` |
| none | Use the `method` of the sub-channel. | `tcp://host1:5555` |
**Several endpoints.** The device splits the address at each `,` and binds or connects each endpoint with the one socket of the sub-channel ([Device.cxx](/source/fairmq/Device.cxx/#L302)). For example, a `push` socket with `tcp://host1:5555,tcp://host2:5555` connects to two peers. `Validate()` splits the address at `;` instead ([Channel.cxx](/source/fairmq/Channel.cxx/#L209)). A list with `;` passes the check, but the device gives it to the transport as one endpoint. Use `,`.
:::caution[Several endpoints and `--channel-config`]
In `--channel-config`, the `,` separates the keys. Thus you cannot give several endpoints there. Put them in a JSON file or set them as a property. A second `address=` key makes a second sub-channel, not a second endpoint.
:::
**No address.** A binding sub-channel without an address gets `tcp://<IP of the interface>:1`. The interface is the value of [`--network-interface`](/reference/options/#opt-network-interface). With `default`, the device uses the interface of the default route. If it cannot find a default route, it uses `tcp://*:1` ([Device.cxx](/source/fairmq/Device.cxx/#L176-L198)). For an interface name that does not exist, the device logs `Could not find provided network interface`. Port 1 means "any port": autobind selects the port ([`autoBind`](#portrangemin-portrangemax-and-autobind)).
A connecting sub-channel without a valid address does not fail at once. The device reads the address property again every 50 ms, until the time of [`--init-timeout`](/reference/options/#opt-init-timeout) is over ([Device.cxx](/source/fairmq/Device.cxx/#L244-L262)). Other code can set the address during this time, for example a plugin.
**Address after the attach.** When the address changes during the attach, the device writes the new value to the property ([Device.cxx](/source/fairmq/Device.cxx/#L359-L366)). The value then contains the resolved IPv4 addresses, the port that autobind selected, and `@` or `+` for each endpoint with a modifier. Other code can read the address that the device uses from `chans.<name>.<index>.address`.
### `transport`
- `default`: the default transport of the device, from [`--transport`](/reference/options/#opt-transport) (default `zeromq`).
- `zeromq` or `shmem`: this transport, also if the device default is different.
The names are in [Transports.h](/source/fairmq/Transports.h/#L27-L31). For another value, the device throws `TransportError` with `Unknown transport provided: <value>` when it makes the sub-channels. The device then goes to `ERROR`.
A poller and the data callbacks of `OnData()` use the transport of sub-channel 0 for all sub-channels of a channel. Give all sub-channels of such a channel the same transport. Refer to [Use several transports](/guides/several-transports/).
### `sndBufSize` and `rcvBufSize`
The maximum number of messages in the send queue and in the receive queue of the socket. They are the ZeroMQ high-water marks `ZMQ_SNDHWM` and `ZMQ_RCVHWM` ([zeromq/Socket.h](/source/fairmq/zeromq/Socket.h/#L310-L332)). The `shmem` transport sets the same options on its ZeroMQ socket, which carries the metadata of the messages ([shmem/Socket.h](/source/fairmq/shmem/Socket.h/#L370-L392)). For ZeroMQ, 0 means no limit. A negative value makes `Validate()` throw `ChannelConfigurationError`.
The behavior of a socket with a full queue depends on the socket type. The ZeroMQ documentation of `zmq_socket` describes it.
### `sndKernelSize` and `rcvKernelSize`
The size in bytes of the kernel buffers of the socket: the ZeroMQ options `ZMQ_SNDBUF` and `ZMQ_RCVBUF` ([zeromq/Socket.h](/source/fairmq/zeromq/Socket.h/#L344-L366)). For the value 0, the device does not set the option ([Channel.cxx](/source/fairmq/Channel.cxx/#L332-L338)). ZeroMQ then keeps the default of the operating system. A negative value makes `Validate()` throw `ChannelConfigurationError`.
The start script of the [region example](/examples/region/) sets `sndKernelSize=212992` for the sampler and `rcvKernelSize=212992` for the sink.
### `sndTimeoutMs` and `rcvTimeoutMs`
The timeout of a send or receive call that does not give its own timeout ([Channel.h](/source/fairmq/Channel.h/#L297-L333)). This applies to [`Channel::Send()`](/api/fair/mq/Channel/#Send) and [`Channel::Receive()`](/api/fair/mq/Channel/#Receive), to [`Device::Send()`](/api/fair/mq/Device/#Send) and [`Device::Receive()`](/api/fair/mq/Device/#Receive) without the timeout argument, and to the receive calls of [`OnData()`](/api/fair/mq/Device/#OnData).
- `-1`: wait until the transfer is complete.
- `0`: do not wait. If the transfer is not possible at once, the call returns `TransferCode::timeout` (-2).
- More than 0: wait for this time in ms. Then the call returns `TransferCode::timeout` (-2).
A transition request interrupts each wait. The call then returns `TransferCode::interrupted` (-3) ([zeromq/Socket.h](/source/fairmq/zeromq/Socket.h/#L96-L124)). The transports wait in steps of 100 ms ([zeromq/Common.h](/source/fairmq/zeromq/Common.h/#L64-L77)). Thus the real timeout is the value rounded up to a multiple of 100 ms. The device does not check the value. Refer to [Transfer codes and errors](/reference/transfer-codes/).
:::caution
If `OnData()` has a callback for one sub-channel only, a receive timeout on this sub-channel stops the data loop. The device then goes from `RUNNING` to `READY`.
:::
### `linger`
The time in ms that the socket keeps unsent messages after it closes: the ZeroMQ option `ZMQ_LINGER` ([Channel.cxx](/source/fairmq/Channel.cxx/#L325-L326)). For ZeroMQ, `-1` means no time limit, and `0` means that the socket discards the messages at once. The device does not check the value. To stop a topology without losing messages, see [Linger](/guides/end-of-run/#linger).
### `rateLogging`
The interval in seconds of the rate log of the sub-channel. The value 0 switches the rate log off for this sub-channel. A negative value makes `Validate()` throw `ChannelConfigurationError`.
In `RUNNING`, the device starts a thread for the rate log if one sub-channel or more has a value above 0 ([Device.cxx](/source/fairmq/Device.cxx/#L383-L392)). The thread wakes every second. At the end of the interval of a sub-channel, it logs one line with the severity `info` ([Device.cxx](/source/fairmq/Device.cxx/#L613-L703)):
```txt
data[0]: in: <messages/s> (<MB/s> MB) out: <messages/s> (<MB/s> MB)
```
One MB in this line is 10<sup>6</sup> bytes. Many examples set `rateLogging` to 0. With the default, the device writes one line per second for each sub-channel.
:::caution[Intervals above 1 s]
For an interval of more than 1 s, the logged rates are too high by the factor of the interval. The device divides the counts of the full interval by the time since its last wake-up, which is approximately 1 s.
:::
### `portRangeMin`, `portRangeMax` and `autoBind`
With `autoBind` set to `true`, a failed bind of a `tcp://` endpoint does not stop the device. The device tries random ports from `portRangeMin` to `portRangeMax`, both included, up to 1000 times ([Channel.cxx](/source/fairmq/Channel.cxx/#L346-L386)). After 1000 failed attempts, it logs `could not bind to any (TCP) port in the given range after 1000 attempts`. Autobind does not apply to `ipc://` and `inproc://`.
The default of `autoBind` is `true`. The CMake variable `FAIRMQ_CHANNEL_DEFAULT_AUTOBIND` changes it when you build FairMQ, for example `-DFAIRMQ_CHANNEL_DEFAULT_AUTOBIND=OFF` ([fairmq/CMakeLists.txt](https://github.com/FairRootGroup/FairMQ/blob/dev/fairmq/CMakeLists.txt#L182-L190)). It is a public compile definition, so code that links the CMake target `FairMQ::FairMQ` gets the same default. Refer to [CMake options and variables](/reference/cmake/#compile-definitions).
FairMQ uses port 1 for "any port". A binding sub-channel without an address gets port 1 (see [`address`](#address)). Without root rights, the bind to port 1 fails, and autobind selects a port ([zeromq/Common.h](/source/fairmq/zeromq/Common.h/#L35-L46)).
:::caution[A port in use]
If the configured port is in use, autobind binds to a random port. The device logs this only with the severity `debug`, so peers that connect to the configured port wait. For fixed ports, set `autoBind` to `false`. A failed bind then moves the device to `ERROR`, with `1 of the binding channels could not initialize`.
:::
### `numSockets`
Only in `--channel-config` and on the channel level of a JSON file. For a value above 0, the parser makes this number of sub-channels, all with the properties of the channel ([JSONParser.cxx](/source/fairmq/JSONParser.cxx/#L108-L122)).
- In JSON, the parser ignores the `sockets` array of the channel. All sub-channels get the `address` of the channel.
- In `--channel-config`, the parser ignores the `address=` keys. The sub-channels have no address.
Use it for binding sub-channels without an address: each sub-channel then gets its own port from autobind. With a bind address such as `tcp://*:5555`, only the first sub-channel gets the port 5555. Autobind gives random ports to the others.
## When the device reads the properties
The device makes its sub-channels from the properties when the controller requests the transition `COMPLETE INIT` ([Device.cxx](/source/fairmq/Device.cxx/#L146-L171)). Later changes of a property have no effect on the sub-channel. The exception is the address of a connecting sub-channel that the device could not attach: the device reads it again in `CONNECTING`. After `RESET DEVICE`, the device deletes its sub-channels, and at the next `COMPLETE INIT` it makes new ones from the properties. Refer to [Configuration and properties](/concepts/configuration/#channel-properties).
## Set the properties from code
Set each property with the type of the table: `std::string`, `int` or `bool`. The device reads them with `boost::any_cast`, which throws `boost::bad_any_cast` for another type ([Channel.cxx](/source/fairmq/Channel.cxx/#L24-L31)).
```cpp
fConfig->SetProperty<std::string>("chans.data.0.address", "tcp://localhost:5555");
fConfig->SetProperty<int>("chans.data.0.rcvBufSize", 100);
fConfig->SetProperty<bool>("chans.data.0.autoBind", false);
```
:::caution[String literals]
Give the type `std::string` when the value is a string literal. `SetProperty("chans.data.0.type", "push")` stores a `const char*`, and the device throws an exception when it reads the property.
:::
[`Device::AddChannel()`](/api/fair/mq/Device/#AddChannel) adds a sub-channel from a `Channel` object, at the next free index. It does not copy `sndTimeoutMs` and `rcvTimeoutMs` ([ProgOptions.cxx](/source/fairmq/ProgOptions.cxx/#L353-L377)). Set these two as properties.
### Set socket options directly
The device applies the properties when it makes the socket of a sub-channel, before it binds or connects it ([Channel.cxx](/source/fairmq/Channel.cxx/#L321-L339)). Your code can also change some ZeroMQ options of a socket directly. [`Channel::GetSocket()`](/api/fair/mq/Channel/#GetSocket) returns the [`fair::mq::Socket`](/api/fair/mq/Socket/). In a device, the socket exists from the state `BINDING` or `CONNECTING` until the device deletes its channels in `RESETTING DEVICE`. Use it in `InitTask()` or later.
| Functions | ZeroMQ option | Property |
| --- | --- | --- |
| [`SetLinger()`](/api/fair/mq/Socket/#SetLinger), [`GetLinger()`](/api/fair/mq/Socket/#GetLinger) | `ZMQ_LINGER` | `linger` |
| [`SetSndBufSize()`](/api/fair/mq/Socket/#SetSndBufSize), [`GetSndBufSize()`](/api/fair/mq/Socket/#GetSndBufSize) | `ZMQ_SNDHWM` | `sndBufSize` |
| [`SetRcvBufSize()`](/api/fair/mq/Socket/#SetRcvBufSize), [`GetRcvBufSize()`](/api/fair/mq/Socket/#GetRcvBufSize) | `ZMQ_RCVHWM` | `rcvBufSize` |
| [`SetSndKernelSize()`](/api/fair/mq/Socket/#SetSndKernelSize), [`GetSndKernelSize()`](/api/fair/mq/Socket/#GetSndKernelSize) | `ZMQ_SNDBUF` | `sndKernelSize` |
| [`SetRcvKernelSize()`](/api/fair/mq/Socket/#SetRcvKernelSize), [`GetRcvKernelSize()`](/api/fair/mq/Socket/#GetRcvKernelSize) | `ZMQ_RCVBUF` | `rcvKernelSize` |
These functions throw `SocketError` when ZeroMQ refuses the value ([zeromq/Socket.h](/source/fairmq/zeromq/Socket.h/#L293-L376)). The get functions return the value that ZeroMQ keeps for the socket, not the size that the kernel uses (ZeroMQ behavior). Linux limits the kernel buffer sizes to `net.core.wmem_max` and `net.core.rmem_max` (Linux behavior).
[`SetOption(name, value, size)`](/api/fair/mq/Socket/#SetOption) and [`GetOption(name, value, &size)`](/api/fair/mq/Socket/#GetOption) give a raw value to `zmq_setsockopt()` and `zmq_getsockopt()`. The name selects the ZeroMQ option ([zeromq/Common.h](/source/fairmq/zeromq/Common.h/#L90-L123)):
| Name | ZeroMQ option |
| --- | --- |
| `linger` | `ZMQ_LINGER` |
| `snd-hwm`, `rcv-hwm` | `ZMQ_SNDHWM`, `ZMQ_RCVHWM` |
| `snd-size`, `rcv-size` | `ZMQ_SNDBUF`, `ZMQ_RCVBUF` |
| `rcv-more`, `fd`, `events` | `ZMQ_RCVMORE`, `ZMQ_FD`, `ZMQ_EVENTS`. ZeroMQ can only read these options. |
:::caution[Names that are not options]
The table of names also contains the socket types (`push`, `pull`, `pub`, `sub`, `xpub`, `xsub`, `req`, `rep`, `dealer`, `router`, `pair`), the flags `snd-more`, `no-block`, `snd-more no-block`, `pollin` and `pollout`, and the empty name. These are not options, but `SetOption()` and `GetOption()` give their numbers to ZeroMQ as option numbers. ZeroMQ refuses most of them. Six socket types have the number of another option in `zmq.h`: `rep` is `ZMQ_AFFINITY`, `dealer` is `ZMQ_ROUTING_ID`, `router` is `ZMQ_SUBSCRIBE`, `pull` is `ZMQ_UNSUBSCRIBE`, `push` is `ZMQ_RATE` and `xpub` is `ZMQ_RECOVERY_IVL`. This is a defect of the code. Do not use these names.
:::
For the options of the first three rows, give an `int` and `sizeof(int)`, as the test below does. For a name that is not in the table, `SetOption()` and `GetOption()` throw `fair::mq::zmq::Error` with `getConstant called with an invalid argument: <name>`. When ZeroMQ refuses the option, they only log `Failed setting socket option, reason: <text>` or `Failed getting socket option, reason: <text>`. The tests use the five names of the first three rows with both transports:
<Snippet file="test/transport/_options.cxx" start="void CheckOldOptionInterface(Channel& channel, const string& option)" />
ZeroMQ applies most options only to the binds and connects that come after the change. `ZMQ_LINGER`, `ZMQ_SNDHWM` and `ZMQ_RCVHWM` apply at once (ZeroMQ behavior, see `zmq_setsockopt`). In a device, the socket is already bound or connected when your code runs. Thus set the kernel buffer sizes with the properties. A `Channel` that you make with a transport factory, without a device, has its socket at once. There, set the options before `Bind()` or `Connect()`.
[`Events(&events)`](/api/fair/mq/Socket/#Events) reads `ZMQ_EVENTS` into a `uint32_t` and returns the result of `zmq_getsockopt()`: 0 on success, -1 on an error. The header marks this function as experimental. The [counters](/concepts/channels/#socket-counters) of the socket are on the same object.
## Related pages
- [Channels and sockets](/concepts/channels/): sub-channels, socket types, methods and addresses.
- [Configure channels](/guides/configure-channels/): give the properties with `--channel-config`, a JSON file or code.
- [JSON configuration](/reference/json/): the format of the file for `--mq-config`.
- [Command-line options](/reference/options/): `--channel-config`, `--network-interface`, `--init-timeout`.

View File

@@ -0,0 +1,301 @@
---
title: 'CMake options and variables'
description: 'The CMake options and variables of the FairMQ build, the targets and variables of the installed CMake package, and the install layout.'
sidebar:
order: 6
---
import { FileTree } from '@astrojs/starlight/components';
FairMQ uses CMake. This page lists the CMake options and variables that change the FairMQ build, the targets and variables of the installed CMake package, and the files that the install step writes.
## Set options and variables
Set CMake options and variables with `-D` in the configure step:
```sh
cmake -S fairmq -B build -DCMAKE_BUILD_TYPE=Debug -DBUILD_TESTING=ON
```
At the end of the configure step, CMake prints a summary. The summary shows the components that CMake builds, the dependencies that it found, the install prefix and the compile definitions. [Install](/start/install/) shows the full build.
Some variables on this page are not declared as CMake options. `ccmake` and `cmake-gui` show them only after you set them with `-D`.
## Build options
[`CMakeLists.txt`](https://github.com/FairRootGroup/FairMQ/blob/dev/CMakeLists.txt) declares these options with the macro `fairmq_build_option()`.
| Option | Default | Requires | Description |
| --- | --- | --- | --- |
| `BUILD_FAIRMQ` | `ON` | — | Build the library `libfairmq`, the [built-in devices](/tools/builtin-devices/), [`fairmq-shmmonitor`](/tools/shmmonitor/) and `fairmq-uuid-gen`. |
| `BUILD_TESTING` | `OFF` | `BUILD_FAIRMQ` | Build the tests and add them to CTest. |
| `BUILD_EXAMPLES` | `ON` | `BUILD_FAIRMQ` | Build the [examples](/examples/1-1/) and their start scripts. With `BUILD_TESTING=ON`, CTest also gets the tests of the examples. |
| `BUILD_TIDY_TOOL` | `OFF` | — | Build the static analyzer [`fairmq-tidy`](/tools/fairmq-tidy/). The configure summary marks it as experimental. |
| `USE_EXTERNAL_GTEST` | `OFF` | — | Use an installed GoogleTest, not the bundled copy. The option text in the code says "Not recommended". |
| `FAIRMQ_DEBUG_MODE` | `OFF` | — | Compile with the definition `FAIRMQ_DEBUG_MODE`. See [Compile definitions](#compile-definitions). |
### Options that require other options
`BUILD_TESTING` and `BUILD_EXAMPLES` require `BUILD_FAIRMQ`. For these options, the macro in [`cmake/FairMQBuildOption.cmake`](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/FairMQBuildOption.cmake) uses `cmake_dependent_option()`:
- When `BUILD_FAIRMQ` is `ON`, you can set the two options.
- When `BUILD_FAIRMQ` is `OFF`, the two options are `OFF`, and CMake hides them.
- When one of the two options is `ON` and `BUILD_FAIRMQ` is `OFF`, the configure step stops with this error:
```txt
Cannot enable build option BUILD_TESTING, depending option is not set: BUILD_FAIRMQ
```
The error also occurs when the value `ON` is in the cache from an earlier configure step. Set the dependent options to `OFF` in the same command, for example `-DBUILD_FAIRMQ=OFF -DBUILD_EXAMPLES=OFF`.
## Dependencies
[`cmake/FairMQDependencies.cmake`](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/FairMQDependencies.cmake) finds the dependencies with `find_package2()` of [FairCMakeModules](https://github.com/FairRootGroup/FairCMakeModules). The build options select the packages that the build needs.
| Package | Version | Needed when | Kind |
| --- | --- | --- | --- |
| Threads | any | `BUILD_FAIRMQ` | public |
| FairLogger | 1.6.0 or later | `BUILD_FAIRMQ` or `BUILD_TIDY_TOOL` | public |
| Boost | 1.66 or later, but not 1.88 | `BUILD_FAIRMQ` or `BUILD_TIDY_TOOL` | public |
| ZeroMQ | 4.1.4 or later | `BUILD_FAIRMQ` | private |
| PicoSHA2 | bundled | `BUILD_FAIRMQ` | bundled |
| GoogleTest | bundled | `BUILD_TESTING` | bundled, or public with `USE_EXTERNAL_GTEST` |
| LLVM, Clang, CLI11 | any | `BUILD_TIDY_TOOL` | private |
| FairCMakeModules | 0.2 or later | always | private, bundled if CMake does not find it |
The Boost components are `container`, `program_options`, `filesystem`, `date_time` and `regex`.
The kinds have these effects:
- **Public**: the installed package records the dependency. A project that uses FairMQ must find the package too. See [The installed package](#the-installed-package).
- **Private**: only the FairMQ build uses the package.
- **Bundled**: the code is in a Git submodule in `extern/`. The configure step runs `git submodule update --init` for it. Then it builds GoogleTest and FairCMakeModules in the build directory under `extern/`. The log of this build is `build.log` in the same directory. PicoSHA2 is a header-only library.
Boost 1.88 replaced the Boost.Process API with version 2. With Boost 1.88, the configure step stops with an error. With Boost 1.89 or later, FairMQ uses the header `boost/process/v1.hpp`.
To find a package in a location that is not standard, add its prefix to `CMAKE_PREFIX_PATH`. Or set `<NAME>_ROOT`, with the package name in upper case, for example `-DFAIRLOGGER_ROOT=/opt/fairlogger`. `find_package2()` also reads an environment variable with the same name.
## Version
[`cmake/GitHelper.cmake`](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/GitHelper.cmake) reads the version from Git with `git describe --tags --dirty --match "v*"`. For example, the tag description `v1.11.0-47-ge366c401` gives the Git version `1.11.0-47-ge366c401` and the project version `1.11.0`.
:::caution[Build from a Git checkout with the tags]
Without `.git`, or without the tags, the version is `0.0.0.0`. The library, the package directory and the package version then use `0.0.0.0`, and a request such as `find_package(FairMQ 1.11)` does not find the package.
:::
The configure step writes the header `fairmq/Version.h` from `fairmq/Version.h.in`. The install step copies it to `include/fairmq/`.
| Macro | Value for v1.11.0 |
| --- | --- |
| `FAIRMQ_VERSION` | `"1.11.0"` |
| `FAIRMQ_VERSION_MAJOR`, `FAIRMQ_VERSION_MINOR`, `FAIRMQ_VERSION_PATCH` | `1`, `11`, `0` |
| `FAIRMQ_VERSION_DEC` | The expression `(1 * 100000) + (11 * 1000) + (0 * 10)`, that is 111000 |
| `FAIRMQ_GIT_VERSION` | The Git version, for example `"1.11.0-47-ge366c401"` |
| `FAIRMQ_GIT_DATE` | The commit date of the built commit (`git log -1 --format=%cd`) |
| `FAIRMQ_BUILD_TYPE` | The value of `CMAKE_BUILD_TYPE`, for example `"RelWithDebInfo"` |
| `FAIRMQ_REPO_URL` | `"https://github.com/FairRootGroup/FairMQ"` |
| `FAIRMQ_LICENSE` | `"LGPL-3.0"` |
| `FAIRMQ_COPYRIGHT` | `"2012-2025 GSI"` |
## Build type and compiler flags
[`cmake/FairMQProjectSettings.cmake`](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/FairMQProjectSettings.cmake) sets these values.
| Variable | Default | Description |
| --- | --- | --- |
| `CMAKE_BUILD_TYPE` | `RelWithDebInfo` | The build type. See the next table. A multi-config generator gets the types `Debug`, `Release` and `RelWithDebInfo`. |
| `CMAKE_CXX_STANDARD` | not set | If you set it, the value must be 17 or more. The target `FairMQ::FairMQ` requires C++17 in all cases. |
| `CMAKE_CXX_EXTENSIONS` | `OFF` | Compile without the language extensions of the compiler. |
| `BUILD_SHARED_LIBS` | `ON` | `ON` builds `libfairmq` as a shared library, `OFF` as a static archive. The CI builds only the shared library. |
| `CMAKE_POSITION_INDEPENDENT_CODE` | `ON` | Compile all code as position-independent code (`-fPIC`). FairMQ sets `ON` also when you set `OFF`. |
| `CMAKE_EXPORT_COMPILE_COMMANDS` | `ON` | Write `compile_commands.json` in the build directory. FairMQ always sets `ON`. `fairmq-tidy` needs this file. |
FairMQ sets the compiler flags of each build type:
| Build type | Flags |
| --- | --- |
| `Debug` | `-Og -g`, the warnings, the sanitizers |
| `RelWithDebInfo` | `-O3 -g -DNDEBUG`, the warnings, the sanitizers |
| `Release` | `-O3 -DNDEBUG` |
The warnings are `-Wshadow -Wall -Wextra -Wpedantic`. The sanitizers are the flags of the [sanitizer options](#sanitizers). FairMQ also adds `-fdiagnostics-color=always` to `CMAKE_CXX_FLAGS`, or `-fdiagnostics-color=never` with `DISABLE_COLOR`.
FairMQ sets the variables `CMAKE_CXX_FLAGS_<CONFIG>` as normal variables. Thus a value from `-DCMAKE_CXX_FLAGS_RELEASE=…` has no effect. Give additional flags in `CMAKE_CXX_FLAGS`.
## Sanitizers
[`cmake/FairMQProjectSettings.cmake`](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/FairMQProjectSettings.cmake) declares these options.
| Option | Default | Flag | Notes |
| --- | --- | --- | --- |
| `ENABLE_SANITIZER_ADDRESS` | `OFF` | `-fsanitize=address` | — |
| `ENABLE_SANITIZER_LEAK` | `OFF` | `-fsanitize=leak` | The tests use the suppressions in `test/leak_sanitizer_suppressions.txt`. This requires CMake 3.22 or later. |
| `ENABLE_SANITIZER_UNDEFINED_BEHAVIOR` | `OFF` | `-fsanitize=undefined` | — |
| `ENABLE_SANITIZER_THREAD` | `OFF` | `-fsanitize=thread` | Not together with the address or the leak sanitizer. CMake then shows a warning and ignores the option. |
| `ENABLE_SANITIZER_MEMORY` | `OFF` | `-fsanitize=memory` | Clang only. Not together with the address, the thread or the leak sanitizer. |
FairMQ joins the selected sanitizers in one flag, for example `-fsanitize=address,leak,undefined`. Only the `Debug` and the `RelWithDebInfo` flags get this flag. A `Release` build has no sanitizers.
## Static analysis
| Variable | Default | Description | Source |
| --- | --- | --- | --- |
| `RUN_STATIC_ANALYSIS` | `OFF` | Run `clang-tidy --extra-arg=-std=c++17` and `cpplint` on each file that the build compiles. `clang-tidy` uses the checks in `.clang-tidy`. CMake searches the programs in `PATH`. | [FairMQProjectSettings.cmake](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/FairMQProjectSettings.cmake) |
| `RUN_FAIRMQ_TIDY` | `OFF` | With `BUILD_TIDY_TOOL=ON`: run `fairmq-tidy` on the sources of the library, the programs and the tests. | [fairmq/CMakeLists.txt](https://github.com/FairRootGroup/FairMQ/blob/dev/fairmq/CMakeLists.txt), [GTestHelper.cmake](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/GTestHelper.cmake) |
With `RUN_STATIC_ANALYSIS`, CMake also searches `iwyu`, and the summary shows the result. The build does not run `iwyu`: `FairMQProjectSettings.cmake` sets `CMAKE_CXX_IWYU`, and CMake does not read this variable.
[`cmake/FairMQTidy.cmake`](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/FairMQTidy.cmake) defines `fairmq_target_tidy(TARGET <target> [EXTRA_ARGS <args>] [CLANG_EXECUTABLE <clang>])`. It runs `fairmq-tidy` on the `.cpp` and `.cxx` files of a target. The installed package has this module when it has the component `tidy_tool`. See [Check code with fairmq-tidy](/guides/fairmq-tidy/).
## Other variables
| Variable | Default | Description | Source |
| --- | --- | --- | --- |
| `CMAKE_INSTALL_PREFIX` | the CMake default | The install prefix. The summary shows it. | CMake |
| `DISABLE_COLOR` | `OFF` | `ON`: no colors in the configure summary and in the output of the compiler. | [FairMQProjectSettings.cmake](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/FairMQProjectSettings.cmake) |
| `ENABLE_CCACHE` | `OFF` | With the Ninja generator: compile through `ccache`, if CMake finds it. Other generators ignore it. For them, set `CMAKE_CXX_COMPILER_LAUNCHER=ccache`. | [FairMQProjectSettings.cmake](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/FairMQProjectSettings.cmake) |
| `FAIRMQ_TEST_LD_LIBRARY_PATH` | not set | A directory that CTest adds to the start of `LD_LIBRARY_PATH` of each test and each example test. It requires CMake 3.22 or later. The CI uses it to run the tests with a libstdc++ that has ThreadSanitizer instrumentation. | [test/CMakeLists.txt](https://github.com/FairRootGroup/FairMQ/blob/dev/test/CMakeLists.txt), [examples/CMakeLists.txt](https://github.com/FairRootGroup/FairMQ/blob/dev/examples/CMakeLists.txt) |
## Compile definitions
These variables set compile definitions on the target `FairMQ::FairMQ`. The definitions are public. Thus the targets that link to `FairMQ::FairMQ` get the same definitions as the library.
| Variable | Default | Compile definition | Effect |
| --- | --- | --- | --- |
| `FAIRMQ_HAS_STD_FILESYSTEM` | `1`, but `0` for GCC and Clang older than 9 | `FAIRMQ_HAS_STD_FILESYSTEM=1` or `=0` | `1`: FairMQ uses `std::filesystem`. `0`: FairMQ uses Boost.Filesystem. |
| `FAIRMQ_HAS_STD_PMR` | `1`, but `0` for Clang | `FAIRMQ_HAS_STD_PMR=1` or `=0` | No effect: the code does not read this definition. Since v1.10.0, FairMQ uses `std::pmr` with all compilers. |
| `FAIRMQ_CHANNEL_DEFAULT_AUTOBIND` | not set | `FAIRMQ_CHANNEL_DEFAULT_AUTOBIND=true` or `=false` | Sets [`Channel::DefaultAutoBind`](/api/fair/mq/Channel/#DefaultAutoBind), the default of the channel property `autoBind`. Without the variable, the default is `true`. The variable accepts all CMake booleans, for example `ON` and `OFF`. |
| `FAIRMQ_DEBUG_MODE` | `OFF` | `FAIRMQ_DEBUG_MODE` | The shmem transport counts the messages in each segment and records each message. `fairmq-shmmonitor` shows the counts, and its option `--debug` prints the messages. In the state `RESETTING DEVICE`, the transport throws an error if messages of the device still exist. This mode can decrease the performance. |
The sources are [`cmake/FairMQProjectSettings.cmake`](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/FairMQProjectSettings.cmake) and [`fairmq/CMakeLists.txt`](https://github.com/FairRootGroup/FairMQ/blob/dev/fairmq/CMakeLists.txt). The summary of the configure step shows the values.
With `autoBind`, a channel that cannot bind to its TCP port tries random ports from `portRangeMin` (default `22000`) to `portRangeMax` (default `23000`). See [Channel properties](/reference/channel-properties/).
The target also has the public definitions `BOOST_ERROR_CODE_HEADER_ONLY` and `BOOST_ASIO_HAS_HAS_STD_CHRONO`.
## The installed package
The install step writes the CMake package to `lib/cmake/FairMQ-<version>/` in the install prefix. `find_package(FairMQ)` finds it when the prefix is a standard location or is in `CMAKE_PREFIX_PATH`:
```cmake
find_package(FairMQ 1.11 REQUIRED COMPONENTS fairmq)
message(STATUS "FairMQ ${FairMQ_GIT_VERSION} in ${FairMQ_PREFIX}")
```
The file `FairMQConfigVersion.cmake` accepts a request for the same version or an older version (`AnyNewerVersion`). For example, FairMQ 1.11.0 satisfies `find_package(FairMQ 1.9)`. [Use FairMQ in a CMake project](/start/cmake/) shows the full set-up of a project. The build directory has no package: see [The build tree](/start/cmake/#the-build-tree).
[`cmake/FairMQConfig.cmake.in`](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/FairMQConfig.cmake.in) and [`cmake/FairMQPackage.cmake`](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/FairMQPackage.cmake) make the package.
### Components
| Component | Present when | Installed files |
| --- | --- | --- |
| `fairmq` | `BUILD_FAIRMQ` | The library, the programs, the headers and `FindZeroMQ.cmake` |
| `tests` | `BUILD_TESTING` | None. The install step does not install the tests. |
| `examples` | `BUILD_EXAMPLES` | The example programs, their start scripts and their configuration files |
| `tidy_tool` | `BUILD_TIDY_TOOL` | `fairmq-tidy` and `FairMQTidy.cmake` |
If you request a component that the installation does not have, `find_package()` does not find FairMQ. For example, `find_package(FairMQ COMPONENTS tidy_tool)` fails if FairMQ was built without `BUILD_TIDY_TOOL`.
### Imported targets
All targets are in the namespace `FairMQ::`.
| Target | Type | Component |
| --- | --- | --- |
| `FairMQ::FairMQ` | Library `libfairmq` | `fairmq` |
| `FairMQ::fairmq-bsampler`, `FairMQ::fairmq-merger`, `FairMQ::fairmq-multiplier`, `FairMQ::fairmq-proxy`, `FairMQ::fairmq-sink`, `FairMQ::fairmq-splitter` | Programs: the [built-in devices](/tools/builtin-devices/) | `fairmq` |
| `FairMQ::fairmq-shmmonitor` | Program: [fairmq-shmmonitor](/tools/shmmonitor/) | `fairmq` |
| `FairMQ::fairmq-uuid-gen` | Program: [prints a UUID](/reference/tools/#fairmq-uuid-gen) | `fairmq` |
| `FairMQ::fairmq-tidy` | Program: [fairmq-tidy](/tools/fairmq-tidy/) | `tidy_tool` |
The package does not export the example programs.
`FairMQ::FairMQ` gives these usage requirements to the targets that link to it:
- C++17 (`cxx_std_17`).
- The include directories `include/fairmq` and `include` of the prefix. Thus `#include <fairmq/Device.h>` and the deprecated `#include <FairMQDevice.h>` both work. See [Move from the FairMQ* names](/guides/migrate-names/).
- The [compile definitions](#compile-definitions).
- The libraries `Threads::Threads`, `dl`, `rt` (Linux only), `Boost::boost`, `Boost::container`, `Boost::program_options`, `Boost::filesystem`, `Boost::regex` and `FairLogger::FairLogger`.
:::caution[Find the dependencies before you link]
The package does not search its dependencies. Your project must find Boost, FairLogger and Threads before it links to `FairMQ::FairMQ`. `find_package2_implicit_dependencies()` of FairCMakeModules reads the variables `FairMQ_PACKAGE_DEPENDENCIES`, `FairMQ_<dep>_VERSION` and `FairMQ_<dep>_COMPONENTS` and finds the packages.
:::
### Variables
| Variable | Value |
| --- | --- |
| `FairMQ_VERSION` | The version, `MAJOR.MINOR.PATCH`, for example `1.11.0`. |
| `FairMQ_GIT_VERSION` | The [Git version](#version), for example `1.11.0-47-ge366c401`. |
| `FairMQ_GIT_DATE` | The commit date of the built commit. |
| `FairMQ_VERSION_HOTFIX` | Empty for a version with three numbers, for example `1.11.0`. The code sets `0` only if `PROJECT_VERSION_TWEAK` is not defined, but `project()` always defines it. |
| `FairMQ_PREFIX` | The install prefix. The package computes it from the location of its config file. |
| `FairMQ_BINDIR` | `${FairMQ_PREFIX}/bin` |
| `FairMQ_INCDIR` | `${FairMQ_PREFIX}/include` |
| `FairMQ_LIBDIR` | `${FairMQ_PREFIX}/lib`, or the value of `CMAKE_INSTALL_LIBDIR`, for example `lib64` |
| `FairMQ_DATADIR` | `${FairMQ_PREFIX}/share/fairmq` |
| `FairMQ_CMAKEMODDIR` | `${FairMQ_PREFIX}/share/fairmq/cmake`. The package adds this directory to the start of `CMAKE_MODULE_PATH`. |
| `FairMQ_BUILD_TYPE` | The `CMAKE_BUILD_TYPE` of the FairMQ build. |
| `FairMQ_BUILD_TYPE_UPPER` | The same value in upper case. |
| `FairMQ_CXX_FLAGS` | `CMAKE_CXX_FLAGS` and `CMAKE_CXX_FLAGS_<BUILD_TYPE>` of the FairMQ build, as a list. |
| `FairMQ_PACKAGE_DEPENDENCIES` | The public dependencies: `Threads`, `FairLogger`, `Boost`, and the public dependencies that these packages declare. With `BUILD_TESTING` and `USE_EXTERNAL_GTEST`, also `GTest`. |
| `FairMQ_<dep>_VERSION` | The minimum version of `<dep>` that the build required, for example `FairMQ_FairLogger_VERSION` is `1.6.0`. |
| `FairMQ_<dep>_COMPONENTS` | The components of `<dep>` that the build required, for example the five components in `FairMQ_Boost_COMPONENTS`. |
| `FairMQ_<component>_FOUND` | `TRUE` for each [component](#components) of the installation. |
| `FairMQ_PACKAGE_COMPONENTS` | Empty. The variable must list the components, but a typo in `cmake/FairMQPackage.cmake` empties it. Use `FairMQ_<component>_FOUND`. |
## Install layout
The install step writes these files in the install prefix. The directory names come from `GNUInstallDirs`. Thus the library directory can be `lib64` instead of `lib`.
<FileTree>
- bin/
- fairmq-bsampler
- fairmq-merger
- fairmq-multiplier
- fairmq-proxy
- fairmq-sink
- fairmq-splitter
- fairmq-shmmonitor
- fairmq-uuid-gen
- fairmq-tidy with `BUILD_TIDY_TOOL`
- fairmq-ex-1-1-sampler the example programs, with `BUILD_EXAMPLES`
- fairmq-start-ex-1-1.sh the start scripts of the examples
- …
- include/
- fairmq/
- Device.h the public headers
- Version.h made by the configure step
- options/
- shmem/
- tools/
- …
- lib/
- libfairmq.so.1.11.0 the library
- libfairmq.so a link to the library
- cmake/
- FairMQ-1.11.0/
- FairMQConfig.cmake
- FairMQConfigVersion.cmake
- FairMQTargets.cmake
- FairMQTargets-relwithdebinfo.cmake
- share/
- fairmq/
- cmake/
- FindZeroMQ.cmake
- FairMQTidy.cmake with `BUILD_TIDY_TOOL`
- ex-1-n-1.json the configuration files of the examples
- …
</FileTree>
The file name of the library has the full version. FairMQ does not keep binary compatibility between releases. Thus you must build your programs again for each new FairMQ version.
If the library directory of the prefix is not a system directory, the installed programs and libraries get a run path. On Linux it is `$ORIGIN/../lib` (a `RUNPATH`), on macOS `@loader_path/../lib`. `CMAKE_INSTALL_RPATH_USE_LINK_PATH` is `ON` by default, so the run path also has the directories of the dependencies.
## Related pages
- [Install](/start/install/): build and install FairMQ.
- [Use FairMQ in a CMake project](/start/cmake/): find the package and link your devices.
- [Check code with fairmq-tidy](/guides/fairmq-tidy/): the static analyzer and `fairmq_target_tidy()`.
- [Contributing](/project/contributing/): build and run the tests.

View File

@@ -0,0 +1,404 @@
---
title: 'Glossary'
description: 'The terms of FairMQ in alphabetical order, each with a short definition and a link to the page that explains it.'
sidebar:
order: 7
tableOfContents:
minHeadingLevel: 2
maxHeadingLevel: 2
---
This page lists the terms of FairMQ in alphabetical order. Each entry has a short definition and a link to the page
that explains the term.
## A
### Acknowledgement
The message that tells the creator of an unmanaged region that the receivers no longer use a block. The shmem
transport sends it when the last message of the block is destroyed. Then the region callback of the creator runs. See
[Acknowledgements](/shmem/regions/#acknowledgements).
### Autobind
A channel property (`autoBind`, default `true`). When a TCP bind fails, the device binds the sub-channel to a random
port from `portRangeMin` to `portRangeMax`. See [Automatic ports](/concepts/channels/#automatic-ports).
## B
### Bind and connect
The two methods of a sub-channel (the property `method`). A socket that binds waits for peers at its address. A socket
that connects goes to the address of a peer. See [Bind and connect](/concepts/channels/#bind-and-connect).
### Built-in devices
The ready-made devices of FairMQ: `fairmq-bsampler`, `fairmq-sink`, `fairmq-splitter`, `fairmq-merger`,
`fairmq-multiplier` and `fairmq-proxy`. See [Built-in devices](/tools/builtin-devices/).
## C
### Channel
A named group of sub-channels of a device, for example `data`. A device sends and receives messages through its
channels. See [Channels and sockets](/concepts/channels/).
### Config plugin
The built-in plugin `config`. In `INITIALIZING DEVICE`, it reads `--mq-config` or `--channel-config` and writes the
channel properties. See [The config plugin](/concepts/plugins/#the-config-plugin).
### Control mode
The mode of the control plugin, set with `--control`: `dynamic` (default), `interactive`, `external`, `static`, `gui`
or `none`. See [Control modes](/concepts/plugins/#control-modes).
### Control plugin
The built-in plugin `control`. It is the default controller of a device. By default, it also handles the signals
`SIGINT` and `SIGTERM`. See [The control plugin](/concepts/plugins/#the-control-plugin).
### Controller
The code that requests the transitions of a device. Of all plugins, only one at a time has the controller role. See
[The controller role](/concepts/plugins/#the-controller-role) and
[Control a device from code](/guides/control-from-code/).
## D
### Data callback
A function that the device calls in `RUNNING` for each message or multipart message that a channel receives. Register
it with `OnData()`. See [Receive data with callbacks or loops](/guides/receive-data/).
### Device
An object of [`fair::mq::Device`](/api/fair/mq/Device/) or of a class that derives from it. It has channels,
properties, transports and a state machine. See [Devices](/concepts/devices/).
### Device counter
A counter in the management segment of a session. Each shmem transport increments it when it starts and decrements
it in its destructor. The transport that brings it to 0 removes the shared memory of the session, unless
`--shm-no-cleanup` is `true`. See
[The device counter and cleanup](/shmem/sessions/#the-device-counter-and-cleanup).
### Device ID
The name of a device in a topology, set with `--id` (default empty). Without `--config-key`, the config plugin selects
the channel configuration of the device with it. See [Configuration and properties](/concepts/configuration/).
### DeviceRunner
The class [`fair::mq::DeviceRunner`](/api/fair/mq/DeviceRunner/). It loads the plugins, parses the command line,
makes the device and runs its state machine. See [How a device starts](/concepts/plugins/#how-a-device-starts).
## E
### Endpoint
One address of a socket, for example `tcp://*:5555`. The address of a sub-channel can have several endpoints,
separated by `,`. See [Addresses and endpoints](/concepts/channels/#addresses-and-endpoints).
### ERROR
The state after an exception in a hook, or after the transition `ErrorFound`. No transition leaves it. See
[The ERROR state](/concepts/states/#the-error-state).
## F
### fairmq-shmmonitor
The tool that shows and removes the shared memory of FairMQ sessions. It can also run as a daemon that cleans up after
the devices. See [fairmq-shmmonitor](/tools/shmmonitor/).
### fairmq-tidy
A Clang tool that finds the deprecated `FairMQ*` type names in your code. See [fairmq-tidy](/tools/fairmq-tidy/) and
[Check code with fairmq-tidy](/guides/fairmq-tidy/).
## H
### Heartbeat
A counter in the management segment of a session. Each shmem transport increments it every 100 ms. The monitor daemon
of `--shm-monitor true` removes the shared memory of the session when the heartbeat does not change for more than
2000 ms. See
[What the daemon does](/shmem/monitor/#what-the-daemon-does).
### Hook
A virtual function of `fair::mq::Device` that the state machine calls, for example `InitTask()`, `Run()` or
`ResetTask()`. Override the hooks to add your code. See [The hooks](/concepts/devices/#the-hooks).
## I
### I/O thread
A thread of ZeroMQ that moves the data of the sockets (ZeroMQ behavior). Each transport factory has one ZeroMQ context with
`--io-threads` I/O threads (default 1). See [Threads in a device](/concepts/threads/#the-threads-of-a-device-process).
### Idling state
A state in which the device waits for the next transition from the controller: `IDLE`, `INITIALIZED`, `BOUND`,
`DEVICE READY` and `READY`. See [Idling states and working states](/concepts/states/#idling-states-and-working-states).
### Interactive mode
The default control mode, `--control dynamic`. The control plugin moves the device to `RUNNING`. Then it reads keys from
the terminal, for example `s` for `Stop`. See [Keys of the interactive mode](/concepts/plugins/#keys-of-the-interactive-mode).
### Interruption
When a transition is requested, the device calls `Interrupt()` of its transports. Then a `Send()` or `Receive()` that
must wait returns the transfer code `interrupted` (-3). The next state resumes the transports. See
[Handle interrupted transfers](/guides/errors-timeouts/#handle-interrupted-transfers).
## L
### Linger
A channel property (`linger`, default 500 ms), the ZeroMQ option `ZMQ_LINGER`. The time that a socket keeps the unsent
messages of its queue after it closes (ZeroMQ behavior). A channel without a device has the default of the socket,
1000 ms. See [Channel properties](/reference/channel-properties/#linger).
## M
### Managed segment
A shared memory segment that the shmem transport creates and manages. It holds the buffers of the messages. Its size
is `--shm-segment-size` (default 2 GiB). See [Managed segments](/shmem/sessions/#managed-segments).
### Management segment
The shared memory segment `fmq_<shmId>_mng` (6.25 MiB) of a session. It holds the data that the devices of the session
share, for example the device counter, the heartbeat and the lists of the segments and regions. See
[The management segment](/shmem/sessions/#the-management-segment).
### Memory resource
A `std::pmr` memory resource. Each transport factory has one, a [`fair::mq::ChannelResource`](/api/fair/mq/ChannelResource/).
Each allocation from it is a message of the transport. See [Use std::pmr memory resources](/guides/pmr/).
### Message
An object of the type [`fair::mq::Message`](/api/fair/mq/Message/) with a buffer of data. Code holds it in a
`fair::mq::MessagePtr`, which is a `std::unique_ptr<Message>`. See [Messages and multipart](/concepts/messages/).
### MetaHeader
The metadata that the shmem transport sends through the socket for each message: the size, the hint, the handles of
the block and of its reference count, the ID of the segment or region, and a flag for a block in a region. The data stays in shared memory. See
[Send a message](/shmem/how-it-works/#send-a-message) and [Out-of-band buffers](/shmem/side-channel/).
### Multipart message
Several messages that one transfer sends and receives together, in a [`fair::mq::Parts`](/api/fair/mq/Parts/) object.
Each message is a part. See [Multipart messages](/concepts/messages/#multipart-messages).
## O
### Option
An argument of the command line of a device, for example `--rate`. After the parse, each option with a value is a
property with the same name. See [Command-line options](/reference/options/).
### Out-of-band buffer
A shmem buffer that a device does not send. It sends the `MetaHeader` of the buffer in its own data, and the
receivers read the buffer in place. See [Out-of-band buffers](/shmem/side-channel/).
## P
### Part
One message of a multipart message. See [Multipart message](#multipart-message).
### Peer
The socket at the other end of a connection of a sub-channel, and the device that has it. FairMQ does not watch the
peers. See [When a peer stops or restarts](/guides/errors-timeouts/#when-a-peer-stops-or-restarts).
### Plugin
A class that derives from [`fair::mq::Plugin`](/api/fair/mq/Plugin/) and runs in the process of a device. It can read
and set properties, follow the state and control the device. See [Plugins and control](/concepts/plugins/).
### Plugin manager
The class [`fair::mq::PluginManager`](/api/fair/mq/PluginManager/). It finds, loads, creates and owns the plugins of a
device. It loads the plugins of `-P`, and it searches the directories of `-S` for their files. See
[Load a plugin](/concepts/plugins/#load-a-plugin).
### PluginServices
The class [`fair::mq::PluginServices`](/api/fair/mq/PluginServices/). It connects the plugins to the device and to its
properties. See [What a plugin can do](/concepts/plugins/#what-a-plugin-can-do).
### Poller
An object of the type [`fair::mq::Poller`](/api/fair/mq/Poller/). It waits until one of several sub-channels can
receive or send a message. Make it with `NewPoller()`. See [Poll several channels](/guides/poll-channels/).
### ProgOptions
The class [`fair::mq::ProgOptions`](/api/fair/mq/ProgOptions/), the store of all properties of a device. See
[The property store](/concepts/configuration/#the-property-store).
### Property
A key and a value in the property store, for example `rate` or `chans.data.0.address`. The device, its plugins and your
code read and change the properties. See [Configuration and properties](/concepts/configuration/).
## Q
### Queue
The messages that a socket holds before it sends them, or after it receives them. The channel properties `sndBufSize`
and `rcvBufSize` (default 1000) set the maximum number of messages: the ZeroMQ high-water marks `ZMQ_SNDHWM` and
`ZMQ_RCVHWM`. See
[Queues, timeouts and the rate log](/concepts/channels/#queues-timeouts-and-the-rate-log).
## R
### Rate logging
The log line with the message rate and the data rate of a sub-channel in `RUNNING`. The channel property `rateLogging`
sets the interval in seconds (default 1, 0 is off). See
[Queues, timeouts and the rate log](/concepts/channels/#queues-timeouts-and-the-rate-log).
### Region
An unmanaged region: a buffer that your code creates with `NewUnmanagedRegion()` and fills. Messages can point into
it. A callback tells your code when the receivers no longer use a block. See [Unmanaged regions](/shmem/regions/).
### runDevice.h
The header `<fairmq/runDevice.h>`. It has a `main()` function that runs your device with `DeviceRunner`. Your code
gives the functions `getDevice()` and `addCustomOptions()`. See [Use runDevice.h](/concepts/devices/#use-rundeviceh).
### Runner hook
A function that `DeviceRunner` calls at one step of the start: `hooks::LoadPlugins`, `hooks::SetCustomCmdLineOptions`,
`hooks::ModifyRawCmdLineArgs` or `hooks::InstantiateDevice`. Add it with `AddHook()`. See
[How a device starts](/concepts/plugins/#how-a-device-starts).
## S
### Session
The name of the shared memory of a group of devices, set with `--session` (default `default`). Devices that exchange
messages with the shmem transport must use the same session. See [The session name](/shmem/sessions/#the-session-name).
### Severity
The level of a log line, for example `info` or `debug`. The option `--severity` selects the lines on the console. See
[Severities](/tools/logging/#severities).
### shmem
The shared memory transport. The data of a message stays in shared memory, and only a small header goes through the
socket. See [How shared memory works](/shmem/how-it-works/).
### shmId
A short ID of 8 hexadecimal digits, made from the user ID and the session name. The shmem transport uses it in the
names of its shared memory objects. See [The shmId](/shmem/sessions/#the-shmid).
### Socket
The object that does the transfers of one sub-channel, a [`fair::mq::Socket`](/api/fair/mq/Socket/) of the transport.
See [Channels and sockets](/concepts/channels/).
### Socket type
The property `type` of a sub-channel: `push`, `pull`, `pub`, `sub`, `req`, `rep`, `pair`, `dealer`, `router`, `xpub`
or `xsub`. The type sets the pattern of the communication. See
[Socket types and patterns](/concepts/channels/#socket-types-and-patterns).
### State
One step in the life of a device, for example `IDLE`, `READY` or `RUNNING`. The enum is
[`fair::mq::State`](/api/fair/mq/State/). See [Device states](/concepts/states/).
### State machine
The part of a device that holds the state and calls the hooks. It changes the state only through transitions. The
class is [`fair::mq::StateMachine`](/api/fair/mq/StateMachine/). See [Device states](/concepts/states/).
### Sub-channel
One element of a channel, with one socket and its own address, for example `data[0]`. See
[Channels and sub-channels](/concepts/channels/#channels-and-sub-channels).
## T
### Timeout
The time in ms that a `Send()` or `Receive()` waits. Give it as an argument of the call, or with the channel
properties `sndTimeoutMs` and `rcvTimeoutMs` (default -1, no limit). See
[Set a timeout](/guides/errors-timeouts/#set-a-timeout).
### Topology
A set of devices and the channels between them, for example a sampler and a sink. See
[Overview](/start/overview/) and [Design a topology](/guides/design-topology/).
### Transfer code
A negative return value of `Send()` and `Receive()`: `error` (-1), `timeout` (-2) or `interrupted` (-3). A transfer
that works returns the number of bytes. See [Transfer codes and errors](/reference/transfer-codes/).
### Transition
A request to change the state, for example `InitDevice` or `Run`. A controller requests most transitions. The device
requests `Auto` and `Stop` itself, and `ErrorFound` after an exception in a hook. See
[Transitions](/concepts/states/#transitions).
### Transport
The implementation of the messages, sockets, pollers and regions: `zeromq` (default) or `shmem`. Each sub-channel can
use its own transport. See [Transports](/concepts/transports/).
### Transport factory
An object of the type [`fair::mq::TransportFactory`](/api/fair/mq/TransportFactory/). It makes the messages, sockets,
pollers and regions of one transport. See [Make a transport factory](/concepts/transports/#make-a-transport-factory).
## U
### Unmanaged region
See [Region](#region).
## W
### Working state
A state in which the device does its work and calls your hooks, for example `INITIALIZING TASK` or `RUNNING`. At the
end, the device itself requests the next transition. In `INITIALIZING DEVICE`, the device waits for `CompleteInit`
from the controller instead. See
[Idling states and working states](/concepts/states/#idling-states-and-working-states).
## Z
### Zero copy
A transfer in which the transport does not copy the data of the message. With shmem, only the `MetaHeader` goes
through the socket, and `Copy()` gives a second message for the same block. See
[How shared memory works](/shmem/how-it-works/).
### zeromq
The default transport. It uses the libzmq library, and the data of each message goes through the socket. See
[The zeromq transport](/concepts/transports/#the-zeromq-transport).
## Related pages
- [Devices](/concepts/devices/): the device, its hooks and how it starts.
- [Device states](/concepts/states/): the states and transitions.
- [Channels and sockets](/concepts/channels/): channels, sub-channels, socket types and addresses.
- [Messages and multipart](/concepts/messages/): messages and parts.
- [Transports](/concepts/transports/): the zeromq and shmem transports.
- [Configuration and properties](/concepts/configuration/): options and properties.
- [Plugins and control](/concepts/plugins/): plugins, controllers and the control modes.

View File

@@ -0,0 +1,145 @@
---
title: 'JSON configuration'
description: 'The format of the JSON file for --mq-config: devices, channels and sockets, how a device finds its entry, and the errors.'
sidebar:
order: 3
code: [fairmq/JSONParser.h, fairmq/JSONParser.cxx, fairmq/plugins/config/Config.cxx]
---
import Snippet from '../../../components/Snippet.astro';
A JSON file describes the channels of one or more devices. Give it to a device with `--mq-config <file>`. The device reads only the entry with its ID or its `--config-key`, and stores the channels of this entry as properties.
## A complete file
The file of the [1-n-1 example](/examples/1-n-1/) has three entries: one for the sampler, one for the two processors, and one for the sink.
<Snippet file="examples/1-n-1/ex-1-n-1.json" />
## Structure
The parser reads this tree ([JSONParser.cxx](/source/fairmq/JSONParser.cxx/#L39-L190)):
```txt
fairMQOptions object, required
└── devices array of device entries
└── { } device entry: id or key, channels
└── channels array of channels
└── { } channel: name, properties, numSockets, sockets
└── sockets array of sockets
└── { } socket: properties
```
Each socket object makes one sub-channel. Its index is its position in the `sockets` array, from 0. The properties of the sub-channel get the keys `chans.<name>.<index>.<property>`, for example `chans.data1.0.address`. The parser ignores all keys that it does not know, on each level.
## Keys
### Device entry
| Key | Type | Meaning |
| --- | --- | --- |
| `id` | string | The device ID that selects this entry. The parser uses it only if the entry has no `key`. |
| `key` | string | The value that selects this entry. Several devices can use one entry with `--config-key`. |
| `channels` | array | The channels of the device. |
An entry needs `id` or `key`, otherwise no device can select it.
### Channel
| Key | Type | Meaning |
| --- | --- | --- |
| `name` | string | Required. The name of the channel. |
| `sockets` | array | One object for each sub-channel. Without `sockets` and without `numSockets`, the channel has one sub-channel. |
| `numSockets` | int | For a value above 0: the number of sub-channels. The parser then ignores `sockets`. See [`numSockets`](#numsockets). |
| `type`, `method`, `address`, `transport`, `sndBufSize`, `rcvBufSize`, `sndKernelSize`, `rcvKernelSize`, `sndTimeoutMs`, `rcvTimeoutMs`, `linger`, `rateLogging`, `portRangeMin`, `portRangeMax`, `autoBind` | see [Channel properties](/reference/channel-properties/) | The values for all sub-channels of the channel. |
### Socket
| Key | Type | Meaning |
| --- | --- | --- |
| `type`, `method`, `address`, `transport`, `sndBufSize`, `rcvBufSize`, `sndKernelSize`, `rcvKernelSize`, `sndTimeoutMs`, `rcvTimeoutMs`, `linger`, `rateLogging`, `portRangeMin`, `portRangeMax`, `autoBind` | see [Channel properties](/reference/channel-properties/) | The values for this sub-channel. They override the values of the channel. |
`name` and `numSockets` have no effect in a socket object.
## How the device finds its entry
The [config plugin](/concepts/configuration/#the-config-plugin) reads the file when the device goes into the state `INITIALIZING DEVICE` ([Config.cxx](/source/fairmq/plugins/config/Config.cxx/#L25-L53)):
1. The plugin takes the value of `--config-key`. Without `--config-key`, it takes the value of `--id`.
2. The parser compares this value with the `key` of each device entry. For an entry without `key`, it compares the value with `id` ([JSONParser.cxx](/source/fairmq/JSONParser.cxx/#L69-L74)).
3. The parser reads the channels of each entry that matches.
An entry with a `key` does not match its `id`. Several devices can use the same entry. In the start script of the 1-n-1 example, both processors have their own ID and the same key `processor`:
<Snippet file="examples/1-n-1/fairmq-start-ex-1-n-1.sh.in" start="PROCESSOR1=" end="xterm -geometry 80x23+500+330" />
- **No entry matches.** The device gets no channels from the file, and the parser shows no error. A device without channels logs the warning `No channels created after finishing initialization` in `CONNECTING`.
- **Several entries match.** The parser reads all of them. For a property that is in two entries, the value of the first entry stays.
- **`--mq-config` and `--channel-config`.** If you give both, the plugin reads only the JSON file.
## Channel values and socket values
The values of a channel are the defaults of its sockets. A socket object can override each of them. This configuration of the parser tests shows the rules:
<Snippet file="test/properties/_jsonparser.cxx" start="auto const kConfig" end='})";' />
For the device ID `sampler`, the parser makes these sub-channels. The tests in the same file check the values.
| Sub-channel | Values from the socket | Values from the channel | Other properties |
| --- | --- | --- | --- |
| `data[0]` | `address` | `type`, `method`, `transport`, `sndBufSize` | Defaults |
| `data[1]` | `address`, `method`, `transport`, `rateLogging` | `type`, `sndBufSize` | Defaults |
| `fanout[0]` to `fanout[2]` | none, because of `numSockets` | `type`, `address` | Defaults |
| `plain[0]` | none, because there is no `sockets` array | `type`, `autoBind` | Defaults |
The entry with the ID `other` has the key `sink`. `--config-key sink` selects it, but `--id other` does not.
## `numSockets`
With `numSockets` above 0, the parser makes this number of sub-channels. All of them get the values of the channel, also the `address`. The parser then ignores the `sockets` array ([JSONParser.cxx](/source/fairmq/JSONParser.cxx/#L108-L122)). [Channel properties](/reference/channel-properties/#numsockets) describes the effect on binding sub-channels.
## Value types
Write strings as JSON strings, numbers as JSON numbers, and booleans as `true` or `false`. [Channel properties](/reference/channel-properties/) gives the type of each property.
:::caution[Wrong types]
The parser reads each value with a default ([JSONParser.cxx](/source/fairmq/JSONParser.cxx/#L90-L105)). If it cannot convert a value, it uses the default and shows no error. For example, `"sndBufSize": "big"` gives `sndBufSize` 1000. To see the values, start the device with `--severity trace`: the parser then logs each property of each sub-channel.
:::
## Errors
| Problem | Result |
| --- | --- |
| The file does not exist, or it is not valid JSON. | `boost::property_tree::json_parser_error` |
| The file has no `fairMQOptions` object. | `boost::property_tree::ptree_bad_path` |
| A channel has no `name`. | `boost::property_tree::ptree_bad_path` |
| The ID is empty. This occurs only when you call the parser from code. | [`fair::mq::ParserError`](/api/fair/mq/ParserError/): ``no device ID provided. Provide with `--id` cmd option`` |
| No entry matches the ID or the key. | No error. The device has no channels from the file. |
| A value has the wrong type. | No error. The parser uses the default. |
The config plugin catches the exceptions and logs their message with the severity `error` ([Config.cxx](/source/fairmq/plugins/config/Config.cxx/#L46-L48)). The device then continues without the channels of the file. If the device has no `--id` and no `--config-key`, the plugin logs the warning `No device ID or config-key provided for the configuration parser.` and does not read the file.
:::caution
A device with a broken file can start without channels. If your device does not find a channel, look for an error message from the parser at the start of the log.
:::
## Parse a file from code
[`fair::mq::JSONParser()`](/api/fair/mq/#JSONParser) reads a file and returns the properties of one device entry. [`PtreeParser()`](/api/fair/mq/#PtreeParser) does the same for a Boost property tree. Give the result to [`ProgOptions::SetProperties()`](/api/fair/mq/ProgOptions/#SetProperties):
```cpp
#include <fairmq/JSONParser.h>
#include <fairmq/ProgOptions.h>
fair::mq::ProgOptions config;
config.SetProperties(fair::mq::JSONParser("ex-1-n-1.json", "sampler1"));
```
The second argument is the ID or the key of the entry.
## Related pages
- [Channel properties](/reference/channel-properties/): all keys of a channel and a socket, with the defaults.
- [Configure channels](/guides/configure-channels/): the JSON file, `--channel-config` and properties from code.
- [Configuration and properties](/concepts/configuration/): how the device reads its configuration.
- [Command-line options](/reference/options/): `--mq-config`, `--config-key` and `--id`.

View File

@@ -0,0 +1,98 @@
---
title: 'Command-line options'
description: 'All command-line options of a device made with runDevice.h: where they come from, the value formats, --help, --print-options and the full table.'
sidebar:
order: 1
code: [fairmq/ProgOptions.cxx, fairmq/plugins/config/Config.cxx, fairmq/plugins/control/Control.cxx, fairmq/PluginManager.cxx, fairmq/DeviceRunner.cxx]
---
import OptionsTable from '../../../components/OptionsTable.astro';
import Snippet from '../../../components/Snippet.astro';
A device made with `runDevice.h` accepts the options on this page. The [table](#all-options) at the end lists the options that each such device has, with the defaults from the code. Each option becomes a property with the same name, so your code reads it with [`GetProperty()`](/api/fair/mq/ProgOptions/#GetProperty).
## Where the options come from
The device runner ([`DeviceRunner`](/api/fair/mq/DeviceRunner/)) collects the options from several places before it parses the command line ([DeviceRunner.cxx](/source/fairmq/DeviceRunner.cxx/#L108-L132)):
| Source | Group in `--help` | Group in the table | Options |
| --- | --- | --- | --- |
| [`ProgOptions`](/api/fair/mq/ProgOptions/) | `FairMQ Command Line Options` | General, Logging | `--help`, `--version`, `--print-options`, the log options |
| The config plugin | `FairMQ device options` | Device, Shared memory | Device ID, transport, channel configuration, shared memory |
| The control plugin | `Control (builtin) Plugin` | Control | `--control`, `--catch-signals` |
| The plugin manager | `Plugin Manager` | Plugins | `-P`, `-S` |
| Your device | `Custom options` | Not in the table | The options of `addCustomOptions()` |
| Other plugins | The name that the plugin gives | Not in the table | The options of each plugin that you load with `-P` |
The device runner always loads the config plugin and the control plugin. The [config plugin](/concepts/configuration/#the-config-plugin) reads the channel configuration. The control plugin moves the device through its states. Refer to [Plugins and control](/concepts/plugins/).
## Show the options of a device
`--help` (or `-h`) prints all options of the device, with their groups, defaults and descriptions. Then the program stops before it makes the device ([DeviceRunner.cxx](/source/fairmq/DeviceRunner.cxx/#L29-L39)).
`--print-options` prints one line for each option, in the format `name:value:type:description` ([ProgOptions.cxx](/source/fairmq/ProgOptions.cxx/#L430-L448)). The value is the value after the parse of the command line. For an option without a value, the value is empty and the type is `<unknown>`. Then the program stops before it makes the device.
```sh
fairmq-ex-1-1-sampler --id sampler1 --print-options
```
Some lines of the output:
```txt
help::<unknown>:Print help
id:sampler1:string:Device ID.
transport:zeromq:string:Transport ('zeromq'/'shmem').
control:dynamic:string:Control mode, 'static' or 'dynamic' (aliases for dynamic are external and interactive), 'none', 'gui'
```
When the device starts, it logs all properties with the severity `debug`, after the line `Configuration:` ([ProgOptions.cxx](/source/fairmq/ProgOptions.cxx/#L384-L428)). Each line has the form `name = value <type> origin`. The origin is `[default]`, `[provided]` or `[empty]`. The channel properties from `--channel-config` and `--mq-config` are not in this log, because the config plugin reads them later, in `INITIALIZING DEVICE`.
:::caution[`--version` and `--print-channels`]
`--version` and `--print-channels` print nothing in this version. The device runner sets the console log to `nolog` for these two options, and then writes the output to the log ([DeviceRunner.cxx](/source/fairmq/DeviceRunner.cxx/#L41-L42)). The device runner then ends the device with the transition `END` ([DeviceRunner.cxx](/source/fairmq/DeviceRunner.cxx/#L154-L168)). `--print-channels` is for the channels that a device registers with [`RegisterChannelEndpoint()`](/api/fair/mq/Device/#RegisterChannelEndpoint), not for the configured channels.
:::
## Value formats
- A long option takes its value as `--name value` or `--name=value` ([ProgOptions.cxx](/source/fairmq/ProgOptions.cxx/#L124-L125)).
- A short option takes its value as `-P value` or `-Pvalue`.
- A boolean option takes `true` or `false`, for example `--color false`.
- `--print-options` and `--print-channels` need no value.
- `--help` and `--version` take no value.
- Sizes are in bytes, for example `--shm-segment-size 1000000000`.
- `--channel-config` and `-S` take several values after the option. Give one value for each channel after one `--channel-config`, as the examples do:
<Snippet file="examples/multiple-channels/fairmq-start-ex-multiple-channels.sh.in" start="SAMPLER=" end="name=broadcast" />
:::caution[Unknown options]
The device ignores options that it does not know ([ProgOptions.cxx](/source/fairmq/ProgOptions.cxx/#L119-L121)). For example, the device starts also with the misspelled option `--chanel-config`, but without channels. It logs each unknown option only with the severity `debug`: `detected unregistered option`.
:::
## Custom options
With `runDevice.h`, your program defines the function `addCustomOptions()`. The device runner adds these options in the group `Custom options` ([runDevice.h](/source/fairmq/runDevice.h/#L33-L37)). Use the types and the defaults of Boost.Program_options:
<Snippet file="examples/1-1/sampler.cxx" start="void addCustomOptions" end="^}" />
Read the values in your device as properties, with the same type as in the option:
<Snippet file="examples/1-1/sampler.cxx" start="void InitTask()" />
For a property with another type, `GetProperty()` throws an exception. [Configuration and properties](/concepts/configuration/#custom-options) describes the properties.
## Plugin options
A plugin can declare its own options. The device runner adds the options of each plugin that you load with `-P`, so `--help -P <plugin>` shows them. A plugin option is a property like the others. Refer to [Write a plugin](/guides/write-plugin/).
## All options
The table shows the options of a device made with `runDevice.h`, without custom options and the options of other plugins. Use the filter to find an option, or select a group. The link at the end of each description goes to the line of the code that defines the option.
<OptionsTable />
## Related pages
- [Configuration and properties](/concepts/configuration/): how options, JSON files and plugins give properties.
- [Channel properties](/reference/channel-properties/): the keys for `--channel-config`.
- [JSON configuration](/reference/json/): the file for `--mq-config`.
- [Plugins and control](/concepts/plugins/): `--control`, `-P` and the plugin search path.
- [Logging](/tools/logging/): `--severity`, `--verbosity` and the log file.

View File

@@ -0,0 +1,234 @@
---
title: 'States and transitions'
description: 'All states and transitions of the device state machine as tables: values, names, the transition matrix, the interactive keys and the errors.'
sidebar:
order: 4
code: [fairmq/States.h, fairmq/States.cxx, fairmq/StateMachine.cxx, fairmq/Device.h, fairmq/plugins/control/Control.cxx]
---
import Snippet from '../../../components/Snippet.astro';
This page lists all states and transitions of the device state machine as tables. It also gives the
keys of the interactive controller, the name functions and the errors of invalid transitions. For
an introduction, see [Device states](/concepts/states/).
## States
The enum [`fair::mq::State`](/api/fair/mq/State/) is in
[`fairmq/States.h`](/source/fairmq/States.h/#L19-L37). Its underlying type is `int`. The name is the
string that [`GetStateName()`](/api/fair/mq/#GetStateName) returns and that the log shows.
| State | Value | Name | Kind | Hooks |
| --- | --- | --- | --- | --- |
| [`Undefined`](/api/fair/mq/State/#Undefined) | 0 | `UNDEFINED` | Not used | — |
| [`Ok`](/api/fair/mq/State/#Ok) | 1 | `OK` | Internal, see below | — |
| [`Error`](/api/fair/mq/State/#Error) | 2 | `ERROR` | Error state, final | — |
| [`Idle`](/api/fair/mq/State/#Idle) | 3 | `IDLE` | Idling state, initial | — |
| [`InitializingDevice`](/api/fair/mq/State/#InitializingDevice) | 4 | `INITIALIZING DEVICE` | Working state | `Init()` |
| [`Initialized`](/api/fair/mq/State/#Initialized) | 5 | `INITIALIZED` | Idling state | — |
| [`Binding`](/api/fair/mq/State/#Binding) | 6 | `BINDING` | Working state | `Bind()` |
| [`Bound`](/api/fair/mq/State/#Bound) | 7 | `BOUND` | Idling state | — |
| [`Connecting`](/api/fair/mq/State/#Connecting) | 8 | `CONNECTING` | Working state | `Connect()` |
| [`DeviceReady`](/api/fair/mq/State/#DeviceReady) | 9 | `DEVICE READY` | Idling state | — |
| [`InitializingTask`](/api/fair/mq/State/#InitializingTask) | 10 | `INITIALIZING TASK` | Working state | `InitTask()` |
| [`Ready`](/api/fair/mq/State/#Ready) | 11 | `READY` | Idling state | — |
| [`Running`](/api/fair/mq/State/#Running) | 12 | `RUNNING` | Working state | `PreRun()`, `ConditionalRun()`, `Run()`, `PostRun()`, data callbacks |
| [`ResettingTask`](/api/fair/mq/State/#ResettingTask) | 13 | `RESETTING TASK` | Working state | `ResetTask()` |
| [`ResettingDevice`](/api/fair/mq/State/#ResettingDevice) | 14 | `RESETTING DEVICE` | Working state | `Reset()` |
| [`Exiting`](/api/fair/mq/State/#Exiting) | 15 | `EXITING` | Final state | — |
The state machine has two regions. The first region holds the states from `IDLE` to `EXITING`. The
second region holds `OK` and `ERROR`, and starts in `OK`. A device does not report the state `OK`.
[`StateQueue::WaitForNext()`](/api/fair/mq/StateQueue/#WaitForNext-2) with a timeout returns `Ok`
when no state arrives.
The log line `No transition from state … on transition …` uses other names. They have an underscore
instead of a space, for example `DEVICE_READY` and `INIT_TASK`
([`StateMachine.cxx`](/source/fairmq/StateMachine.cxx/#L45-L75)).
## Transitions
The enum [`fair::mq::Transition`](/api/fair/mq/Transition/) is in
[`fairmq/States.h`](/source/fairmq/States.h/#L39-L53). The key column gives the key of the
interactive controller.
| Transition | Value | Name | From | To | Requested by | Key |
| --- | --- | --- | --- | --- | --- | --- |
| [`Auto`](/api/fair/mq/Transition/#Auto) | 0 | `AUTO` | `BINDING`, `CONNECTING`, `INITIALIZING TASK`, `RESETTING TASK`, `RESETTING DEVICE` | The next state, see the matrix | The device | — |
| [`InitDevice`](/api/fair/mq/Transition/#InitDevice) | 1 | `INIT DEVICE` | `IDLE` | `INITIALIZING DEVICE` | Controller | `i` |
| [`CompleteInit`](/api/fair/mq/Transition/#CompleteInit) | 2 | `COMPLETE INIT` | `INITIALIZING DEVICE` | `INITIALIZED` | Controller | `i` |
| [`Bind`](/api/fair/mq/Transition/#Bind) | 3 | `BIND` | `INITIALIZED` | `BINDING` | Controller | `b` |
| [`Connect`](/api/fair/mq/Transition/#Connect) | 4 | `CONNECT` | `BOUND` | `CONNECTING` | Controller | `x` |
| [`InitTask`](/api/fair/mq/Transition/#InitTask) | 5 | `INIT TASK` | `DEVICE READY` | `INITIALIZING TASK` | Controller | `j` |
| [`Run`](/api/fair/mq/Transition/#Run) | 6 | `RUN` | `READY` | `RUNNING` | Controller | `r` |
| [`Stop`](/api/fair/mq/Transition/#Stop) | 7 | `STOP` | `RUNNING` | `READY` | Controller, or the device at the end of its work | `s` |
| [`ResetTask`](/api/fair/mq/Transition/#ResetTask) | 8 | `RESET TASK` | `READY` | `RESETTING TASK` | Controller | `t` |
| [`ResetDevice`](/api/fair/mq/Transition/#ResetDevice) | 9 | `RESET DEVICE` | `INITIALIZED`, `BOUND`, `DEVICE READY` | `RESETTING DEVICE` | Controller | `d` |
| [`End`](/api/fair/mq/Transition/#End) | 10 | `END` | `IDLE` | `EXITING` | Controller | `q` (shutdown sequence) |
| [`ErrorFound`](/api/fair/mq/Transition/#ErrorFound) | 11 | `ERROR FOUND` | All states | `ERROR` | The device after an exception, or your code | — |
## Transition matrix
The rows are the current states, and the columns are the transitions. A cell gives the next state.
A dash means that the state machine refuses the transition. The column `ErrorFound` is not in the
matrix: from all states, `ErrorFound` leads to `ERROR`. The source is the `transition_table` in
[`StateMachine.cxx`](/source/fairmq/StateMachine.cxx/#L117-L144).
| Current state | `InitDevice` | `CompleteInit` | `Bind` | `Connect` | `InitTask` | `Run` | `Stop` | `ResetTask` | `ResetDevice` | `End` | `Auto` |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `IDLE` | `INITIALIZING DEVICE` | — | — | — | — | — | — | — | — | `EXITING` | — |
| `INITIALIZING DEVICE` | — | `INITIALIZED` | — | — | — | — | — | — | — | — | — |
| `INITIALIZED` | — | — | `BINDING` | — | — | — | — | — | `RESETTING DEVICE` | — | — |
| `BINDING` | — | — | — | — | — | — | — | — | — | — | `BOUND` |
| `BOUND` | — | — | — | `CONNECTING` | — | — | — | — | `RESETTING DEVICE` | — | — |
| `CONNECTING` | — | — | — | — | — | — | — | — | — | — | `DEVICE READY` |
| `DEVICE READY` | — | — | — | — | `INITIALIZING TASK` | — | — | — | `RESETTING DEVICE` | — | — |
| `INITIALIZING TASK` | — | — | — | — | — | — | — | — | — | — | `READY` |
| `READY` | — | — | — | — | — | `RUNNING` | — | `RESETTING TASK` | — | — | — |
| `RUNNING` | — | — | — | — | — | — | `READY` | — | — | — | — |
| `RESETTING TASK` | — | — | — | — | — | — | — | — | — | — | `DEVICE READY` |
| `RESETTING DEVICE` | — | — | — | — | — | — | — | — | — | — | `IDLE` |
| `EXITING` | — | — | — | — | — | — | — | — | — | — | — |
| `ERROR` | — | — | — | — | — | — | — | — | — | — | — |
## Rules
- The state machine accepts one transition at a time. While a transition is pending, it refuses all
other transitions except `ErrorFound`.
- A transition is pending from the call of `ChangeState()` until the next state starts. The next
state starts only after the hooks of the current state return.
- In a working state, the device requests `Auto` after its hooks, but only when no other transition
is pending. At the end of `RUNNING`, the device requests `Stop` in the same way.
- `INITIALIZING DEVICE` waits for `CompleteInit` before it calls `Init()`.
- Each new transition interrupts the transports. The transports resume at the start of the next
state.
- In `EXITING` and `ERROR`, the state machine has stopped, and the state does not change. In
`EXITING`, `ChangeState()` returns `false` for all transitions except `ErrorFound`. In `ERROR`,
`ChangeState()` can return `true` (known defect, see the disabled test
`StateMachine.RefusesTransitionsInError`).
## Keys of the interactive controller
With `--control dynamic` (default), `interactive` or `external`, the control plugin reads keys from
the standard input. It reads one character at a time, without Enter. The plugin prints the line
` --> [key] action` before it does the action. Source:
[`Control.cxx`](/source/fairmq/plugins/control/Control.cxx/#L154-L272).
| Key | Action |
| --- | --- |
| `h` | Prints the help and the state machine. |
| `c` | Logs the current state. The plugin prints ` --> [i] check current state`. |
| `p` | Logs the number of connected peers of each sub-channel. |
| `i` | Requests `InitDevice`. When `INITIALIZING DEVICE` starts, it requests `CompleteInit`. |
| `b` | Requests `Bind`. |
| `x` | Requests `Connect`. |
| `j` | Requests `InitTask`. |
| `r` | Requests `Run`. |
| `s` | Requests `Stop`. |
| `t` | Requests `ResetTask`. |
| `d` | Requests `ResetDevice`. |
| `q` | Ends the key input and runs the shutdown sequence (see below). |
| `k` | Increases the log severity of the console. |
| `l` | Decreases the log severity of the console. |
| `n` | Increases the log verbosity. |
| `m` | Decreases the log verbosity. |
| Other | Prints `Invalid input: [key].` and the help. |
The keys `b`, `x`, `j`, `r`, `s`, `t` and `d` request only one transition. They do not wait for
the `Auto` transitions. If the state does not accept the transition, the state does not change.
:::caution[Known defect]
If several keys arrive in one read, for example `cq` from a pipe, the plugin handles only the first
key. See the disabled test `ControlPlugin.SeveralKeysInOneInput` in `test/device/_runner.cxx`.
:::
## Startup and shutdown sequences
The control modes `dynamic`, `static` and `gui` start with the same sequence
([`RunStartupSequence()`](/source/fairmq/plugins/control/Control.cxx/#L104-L142)). The plugin requests
a transition and waits for the next states:
| Step | Request | Wait for |
| --- | --- | --- |
| 1 | `InitDevice` | `INITIALIZING DEVICE` |
| 2 | `CompleteInit` | `INITIALIZED` |
| 3 | `Bind` | `BINDING`, then `BOUND` |
| 4 | `Connect` | `CONNECTING`, then `DEVICE READY` |
| 5 | `InitTask` | `INITIALIZING TASK`, then `READY` |
| 6 | `Run` | `RUNNING` |
A signal stops the sequence after the current step, and the plugin runs the shutdown sequence. The
state `ERROR` also stops the sequence, but without the shutdown sequence. The shutdown sequence
([`RunShutdownSequence()`](/source/fairmq/plugins/control/Control.cxx/#L471-L506)) requests one
transition for each state, until `EXITING` or `ERROR`:
| Current state | Request |
| --- | --- |
| `IDLE` | `End` |
| `INITIALIZING DEVICE` | `CompleteInit` |
| `INITIALIZED`, `BOUND`, `DEVICE READY` | `ResetDevice` |
| `READY` | `ResetTask` |
| `RUNNING` | `Stop` |
| Other states | None. The plugin waits for the next state. |
## Name functions
These functions in the namespace `fair::mq` convert between the enums and the names
([`States.h`](/source/fairmq/States.h/#L55-L63)):
<Snippet file="fairmq/States.h" start="std::string GetStateName(State);" end="operator<<(std::ostream& os, const Transition& transition)" />
- [`GetStateName()`](/api/fair/mq/#GetStateName) and
[`GetTransitionName()`](/api/fair/mq/#GetTransitionName) return the name with spaces, for example
`DEVICE READY`. The `operator<<` for `State` and `Transition` writes the same name.
- [`GetState()`](/api/fair/mq/#GetState) and [`GetTransition()`](/api/fair/mq/#GetTransition) accept
only these names, in upper case and with spaces.
- All four functions throw `std::out_of_range` for an unknown name or value.
Other functions use the same names:
| Function | Description |
| --- | --- |
| [`Device::ChangeState(const std::string&)`](/api/fair/mq/Device/#ChangeState-2) | Requests the transition with this name, for example `"INIT DEVICE"`. |
| [`Device::ChangeStateOrThrow(const std::string&)`](/api/fair/mq/Device/#ChangeStateOrThrow-2) | The same, but throws if the state machine refuses the transition. |
| [`Device::WaitForState(const std::string&)`](/api/fair/mq/Device/#WaitForState-2) | Waits for the state with this name. |
| [`Device::GetCurrentStateName()`](/api/fair/mq/Device/#GetCurrentStateName) | Returns the name of the current state. |
| [`PluginServices::ToDeviceState()`](/api/fair/mq/PluginServices/#ToDeviceState), [`ToDeviceStateTransition()`](/api/fair/mq/PluginServices/#ToDeviceStateTransition) | Call `GetState()` and `GetTransition()`. |
| [`PluginServices::ToStr()`](/api/fair/mq/PluginServices/#ToStr), [`ToStr()`](/api/fair/mq/PluginServices/#ToStr-2) | Call `GetStateName()` and `GetTransitionName()`. |
| [`Device::GetStateName()`](/api/fair/mq/Device/#GetStateName), [`Device::GetTransitionName()`](/api/fair/mq/Device/#GetTransitionName) | Deprecated static functions. Use the functions of `States.h`. |
The test `States.UnknownNameThrows` shows the exceptions:
<Snippet file="test/state_machine/_state_machine.cxx" start="TEST(States, UnknownNameThrows)" />
## Errors of invalid transitions
| Call | Problem | Result |
| --- | --- | --- |
| [`Device::ChangeState(Transition)`](/api/fair/mq/Device/#ChangeState) | The current state does not accept the transition. | Returns `false`. Logs `No transition from state … on transition …`. |
| `Device::ChangeState(Transition)` | Another transition is pending. | Returns `false`. Logs `Transition … incoming, but another state transition is already ongoing.` |
| [`Device::ChangeStateOrThrow(Transition)`](/api/fair/mq/Device/#ChangeStateOrThrow) | `ChangeState()` returns `false`. | Throws `std::system_error` with the code [`ErrorCode::DeviceChangeStateFailed`](/api/fair/mq/ErrorCode/#DeviceChangeStateFailed) and the text `Invalid transition: <NAME>`. |
| The functions with a `std::string` | The name is unknown. | Throw `std::out_of_range`. |
| [`PluginServices::ChangeDeviceState()`](/api/fair/mq/PluginServices/#ChangeDeviceState) | Another plugin controls the device. | Throws [`PluginServices::DeviceControlError`](/api/fair/mq/PluginServices/DeviceControlError/). Otherwise, it returns the result of `ChangeState()`. Without a controller, the calling plugin becomes the controller. |
| [`Device::WaitForState()`](/api/fair/mq/Device/#WaitForState), [`Device::WaitForNextState()`](/api/fair/mq/Device/#WaitForNextState) | The next state in the queue is `ERROR`. | Throw [`DeviceErrorState`](/api/fair/mq/DeviceErrorState/) with the text `Controlled device transitioned to error state.` |
`ChangeState()` is `[[nodiscard]]`. The compiler warns when your code ignores the return value.
Use `ChangeStateOrThrow()` when a refused transition is an error in your program. The test
`Transitions.InvalidChangeStateOrThrow` requests `Connect` in `IDLE`:
<Snippet file="test/device/_transitions.cxx" start="TEST(Transitions, InvalidChangeStateOrThrow)" />
:::caution[Known defect]
After an exception in a hook, the device does not put `ERROR` into the queue of `WaitForState()`.
A thread that waits there for another state then waits forever.
:::
For the error codes and all exceptions of FairMQ, see
[Transfer codes and errors](/reference/transfer-codes/).
## Related pages
- [Device states](/concepts/states/): the state machine with a diagram, and the hooks in each state.
- [Plugins and control](/concepts/plugins/): the control plugin and the device control of plugins.
- [Control a device from code](/guides/control-from-code/): request transitions in your program.
- [Transfer codes and errors](/reference/transfer-codes/): `ErrorCode` and the exceptions.

View File

@@ -0,0 +1,388 @@
---
title: Helpers in fair::mq::tools
description: The installed helper headers of fair::mq::tools (network, UUIDs, child processes, strings, rate limits, versions) and the tool fairmq-uuid-gen.
sidebar:
order: 6.5
code: [fairmq/Tools.h, fairmq/tools/Process.h, fairmq/tools/Network.cxx, fairmq/tools/Strings.h, fairmq/tools/runUuidGenerator.cxx]
---
import Snippet from '../../../components/Snippet.astro';
import OptionsTable from '../../../components/OptionsTable.astro';
The namespace `fair::mq::tools` contains small helpers that FairMQ uses in its own code: network
lookups, UUIDs, child processes, string functions, a rate limiter and a version type. The
installation includes their headers, so your devices and tests can use them. Some helpers are
internal in practice: only the tests use them, or only the key input of FairMQ programs.
## The installed headers
`fairmq/CMakeLists.txt` installs twelve headers of `fairmq/tools/` and the header `fairmq/Tools.h`,
which includes eleven of them. The table shows where FairMQ uses each header.
| Header | Contents | Used by | For your code |
| --- | --- | --- | --- |
| [`fairmq/Tools.h`](#toolsh) | Includes all headers of this table, except `IO.h`. | `Device.h`, `Channel.cxx`, `TransportFactory.cxx` | Use the single headers. |
| [`tools/Strings.h`](#stringsh) | `ToString()`, `ToStrVector()`, `StrStartsWith()`, `StrEndsWith()` | Most parts of FairMQ | Use. |
| [`tools/Unique.h`](#uniqueh) | `Uuid()`, `UuidHash()` | `TransportFactory.cxx`, `fairmq-uuid-gen`, the tests | Use. |
| [`tools/Network.h`](#networkh) | `getHostIPs()`, `getInterfaceIP()`, `getDefaultRouteNetworkInterface()`, `getIpFromHostname()`, `DefaultRouteDetectionError` | `Device.cxx` | Use. |
| [`tools/Process.h`](#processh) | `execute()`, `execute_result` | The tests of FairMQ | Use in tests. |
| [`tools/RateLimit.h`](#ratelimith) | `RateLimiter` | `Device.cxx` (`--rate`), `fairmq-bsampler`, the region example | Use. |
| [`tools/Version.h`](#versionh) | `Version` | `Device`, `Plugin` | Use. It is a type of the device and plugin API. |
| [`tools/Exceptions.h`](#exceptionsh) | `CallOnDestruction` | `Device.cxx`, `StateMachine.cxx` | Use. |
| [`tools/Semaphore.h`](#semaphoreh) | `Semaphore`, `SharedSemaphore` | Only `test/tools/` | Internal in practice. |
| [`tools/InstanceLimit.h`](#instancelimith) | `InstanceLimiter` | Only `test/tools/` | Internal in practice. |
| [`tools/IO.h`](#ioh) | `NonCanonicalInput` | The control plugin, `fairmq-shmmonitor` | Internal in practice. |
| [`tools/Compiler.h`](#compilerh-and-cppstlh) | The macro `__FAIRMQ_ALWAYS_INLINE` | Nothing | Internal. |
| [`tools/CppSTL.h`](#compilerh-and-cppstlh) | No declarations | Nothing | Internal. |
Include a header as `<fairmq/tools/<Name>.h>`, and link your target to `FairMQ::FairMQ` (see
[Use FairMQ in a CMake project](/start/cmake/)). The functions of `Network.h`, `Process.h`,
`Semaphore.h` and `Unique.h` are compiled into `libfairmq`. The other headers need no library.
The test suite `Tools` in [`test/tools/`](https://github.com/FairRootGroup/FairMQ/tree/dev/test/tools)
tests most helpers. Run it with `ctest -R '^Tools\.'` in a build with `BUILD_TESTING=ON` (see
[Contributing](/project/contributing/#select-tests)).
## Tools.h
[`fairmq/Tools.h`](/source/fairmq/Tools.h/) includes all headers of `fairmq/tools/` except `IO.h`.
`fairmq/Device.h` includes `fairmq/Tools.h`. Thus a source file of a device has the helpers without
an include. Include the header of each helper that you use, so that your code does not depend on
the includes of `Device.h`.
Do not confuse `fairmq/tools/Version.h` with `fairmq/Version.h`. The build generates
`fairmq/Version.h` from `Version.h.in`. It defines macros, for example `FAIRMQ_VERSION`,
`FAIRMQ_VERSION_MAJOR` and `FAIRMQ_GIT_VERSION`.
## Strings.h
| Function | What it does |
| --- | --- |
| [`ToString(T&&... t) -> std::string`](/api/fair/mq/tools/#ToString) | Writes all arguments with `operator<<` into a `std::stringstream`, without separators, and returns the string. |
| [`ToStrVector(const int argc, char*const* argv, const bool dropProgramName = true) -> std::vector<std::string>`](/api/fair/mq/tools/#ToStrVector) | Copies the command-line arguments of `main()` into a vector. With `dropProgramName = true`, the vector does not contain `argv[0]`. |
| [`bool StrStartsWith(std::string const& str, std::string const& start)`](/api/fair/mq/tools/#StrStartsWith) | `true` if `str` starts with `start`. |
| [`bool StrEndsWith(std::string const& str, std::string const& end)`](/api/fair/mq/tools/#StrEndsWith) | `true` if `str` ends with `end`. |
`ToString()` uses the formatting of the stream. Thus `2.5` gives `2.5`, and each type with an
`operator<<` works. FairMQ uses it for the texts of its exceptions and log lines. `DeviceRunner`
uses `ToStrVector()`. `fairmq-shmmonitor --list-all` uses `StrStartsWith()`
and `StrEndsWith()` to find the files of FairMQ.
The tests show the behavior, also for empty strings:
<Snippet file="test/tools/_tools.cxx" start="TEST(Strings, ToString)" />
<Snippet file="test/tools/_tools.cxx" start="TEST(Strings, StartsAndEndsWith)" />
<Snippet file="test/tools/_tools.cxx" start="TEST(Strings, ToStrVector)" />
## Unique.h
| Function | What it returns |
| --- | --- |
| [`std::string Uuid()`](/api/fair/mq/tools/#Uuid) | A new random UUID as a string with 36 characters. |
| [`std::size_t UuidHash()`](/api/fair/mq/tools/#UuidHash) | The hash of a new random UUID. |
Each call makes a new UUID with the random generator of Boost.Uuid. `UuidHash()` returns
`boost::hash` of the UUID, not the hash of the string of an earlier `Uuid()` call.
[Unique.cxx](/source/fairmq/tools/Unique.cxx/#L11-L13) makes Boost use the files `/dev/*random`
instead of `getrandom()` and `getentropy()`.
FairMQ uses these functions here:
- [`TransportFactory::CreateTransportFactory()`](/api/fair/mq/TransportFactory/#CreateTransportFactory)
gives a factory with an empty ID the ID `Uuid()` ([TransportFactory.cxx](/source/fairmq/TransportFactory.cxx/#L29-L32)).
- [`fairmq-uuid-gen`](#fairmq-uuid-gen) prints the result of one of the two functions.
- The tests make unique session names and `ipc://` addresses with them, for example
`Configure()` and `IpcAddress` in [`test/helper/Transport.h`](https://github.com/FairRootGroup/FairMQ/blob/dev/test/helper/Transport.h).
The test makes 1000 values of each function and checks that they are all different:
<Snippet file="test/tools/_tools.cxx" start="TEST(Unique, UuidsAreUnique)" />
## Network.h
| Function | What it returns | On failure |
| --- | --- | --- |
| [`getHostIPs()`](/api/fair/mq/tools/#getHostIPs) | A `std::map<std::string, std::string>`: the name of each network interface and its IPv4 address. | Throws `std::runtime_error` if `getifaddrs()` or `getnameinfo()` fails. |
| [`getInterfaceIP(const std::string& interface)`](/api/fair/mq/tools/#getInterfaceIP) | The IPv4 address of the interface, from `getHostIPs()`. | Returns `""`. For an unknown interface, it logs `Could not find provided network interface: "<name>"!, exiting.` at the severity `error`. The program continues. |
| [`getDefaultRouteNetworkInterface()`](/api/fair/mq/tools/#getDefaultRouteNetworkInterface) | The name of the interface of the default route. | Throws [`DefaultRouteDetectionError`](/api/fair/mq/tools/DefaultRouteDetectionError/) if it finds no interface. Returns `""` if `popen()` fails. |
| [`getIpFromHostname(const std::string& hostname)`](/api/fair/mq/tools/#getIpFromHostname) | The first IPv4 address of the host name. | Returns `""` and logs a warning or an error. |
- `getHostIPs()` lists only IPv4 addresses (`AF_INET`). If an interface has several IPv4 addresses,
the map keeps the first one.
- On Linux, `getDefaultRouteNetworkInterface()` reads `/proc/net/route` and selects the line with
the destination `00000000`. If it finds none, it runs `ip route | grep default | cut -d " " -f 5 | head -n 1`.
On macOS, it runs `route -n get default | grep interface | cut -d ":" -f 2`
([Network.cxx](/source/fairmq/tools/Network.cxx/#L95-L158)).
- `getIpFromHostname()` resolves the name with the TCP resolver of Boost.Asio, for IPv4 only.
The device uses these functions for its channel addresses
([Device.cxx](/source/fairmq/Device.cxx/#L185-L198)):
- A binding sub-channel without an address gets the IPv4 address of `--network-interface`. With the
value `default`, the device asks `getDefaultRouteNetworkInterface()`. If it throws, the device
binds to `tcp://*:1`. See [Configure channels](/guides/configure-channels/#addresses-on-several-hosts).
- The device replaces the host name of a `tcp://` endpoint with the result of `getIpFromHostname()`.
See [Channel properties](/reference/channel-properties/).
This program prints the interfaces, the interface of the default route and an address of a host name:
```cpp title="network.cxx"
#include <fairmq/tools/Network.h>
#include <iostream>
int main()
{
for (auto const& [name, ip] : fair::mq::tools::getHostIPs()) {
std::cout << name << ": " << ip << '\n';
}
try {
auto const interface = fair::mq::tools::getDefaultRouteNetworkInterface();
std::cout << "default route: " << interface << ", "
<< fair::mq::tools::getInterfaceIP(interface) << '\n';
} catch (fair::mq::tools::DefaultRouteDetectionError const& e) {
std::cout << e.what() << '\n';
}
std::cout << "localhost: " << fair::mq::tools::getIpFromHostname("localhost") << '\n';
return 0;
}
```
The tests in [`test/tools/_network.cxx`](https://github.com/FairRootGroup/FairMQ/blob/dev/test/tools/_network.cxx)
check that `localhost` gives `127.0.0.1` and that an unknown host name gives an empty string:
<Snippet file="test/tools/_network.cxx" start="TEST(Tools, NetworkIPv4Localhost)" />
## Process.h
[`execute()`](/api/fair/mq/tools/#execute) starts a command in a child process, waits until it
stops, and returns an [`execute_result`](/api/fair/mq/tools/execute_result/). The result has the
captured output [`console_out`](/api/fair/mq/tools/execute_result/#console_out) and the exit code
[`exit_code`](/api/fair/mq/tools/execute_result/#exit_code).
```cpp
execute_result execute(const std::string& cmd,
const std::string& prefix = "",
const std::string& input = "",
int sig = -1);
execute_result execute(const std::string& cmd,
const std::string& prefix,
const std::string& input,
int sig,
std::chrono::milliseconds timeout);
```
| Parameter | Effect |
| --- | --- |
| `cmd` | The command line. For shell syntax, for example a redirection, run it with `sh -c`, as the test below does. |
| `prefix` | The text before each line of the output, for example `"[sampler] "`. |
| `input` | Text for the standard input of the child. `execute()` writes it 1000 ms after the start. It does not close the standard input after that. |
| `sig` | A signal, for example `SIGINT`. If it is not `-1`, `execute()` sends it to the child 2000 ms after the start. |
| `timeout` | [Second overload](/api/fair/mq/tools/#execute-2) only. After this time, `execute()` stops the child with `SIGKILL`. `0` means no limit. The first overload has no limit. |
The [overload with `timeout`](/api/fair/mq/tools/#execute-2) is on `dev` and is not in a release yet (see
[Release notes](/project/release-notes/#unreleased-on-dev)).
`execute()` writes each line to `std::cout` and to `console_out`, with the prefix
([Process.cxx](/source/fairmq/tools/Process.cxx/#L72-L201)):
- first the command, then `fair::mq::tools::execute: pid: <pid>`,
- each line of the standard output of the child,
- each line of the standard error, after the text `error: `,
- `fair::mq::tools::execute: timeout after <n> ms, killing pid <pid>` if the timeout ends,
- at the end, `fair::mq::tools::execute: exit code: <n>`.
Since v1.11.0, calls from several threads write whole lines to `std::cout`. The test helper
`RunDevices()` in [`test/helper/Devices.h`](https://github.com/FairRootGroup/FairMQ/blob/dev/test/helper/Devices.h)
starts each device of a test with `execute()` in its own thread. See
[Test your devices](/guides/test-devices/).
The tests show the output, the exit code, the signal and the timeout. When a signal stops the child,
the tests expect the number of the signal as `exit_code`, for example `SIGKILL` after the timeout.
<Snippet file="test/tools/_tools.cxx" start="TEST(Execute, OutputAndExitCode)" />
<Snippet file="test/tools/_tools.cxx" start="TEST(Execute, Timeout)" />
## RateLimit.h
[`RateLimiter`](/api/fair/mq/tools/RateLimiter/) limits a loop to a number of iterations per second.
| Member | What it does |
| --- | --- |
| [`explicit RateLimiter(float rate)`](/api/fair/mq/tools/RateLimiter/#RateLimiter) | Sets the rate in Hz. A rate of 0 or less sets 1 GHz, which means no limit in practice. |
| [`void maybe_sleep()`](/api/fair/mq/tools/RateLimiter/#maybe_sleep) | Call it at the end of each iteration. It sleeps if the iterations come too fast. |
`maybe_sleep()` reads the clock only every n-th call. It measures the mean time of an iteration, and
it changes n and the sleep time until the time agrees with the rate
([RateLimit.h](/source/fairmq/tools/RateLimit.h/#L68-L124)). The device uses a `RateLimiter` for
`--rate` in its `ConditionalRun()` loop, and only for rates above 0.001:
<Snippet file="fairmq/Device.cxx" start="tools::RateLimiter rateLimiter(fRate);" />
`fairmq-bsampler` uses it for `--msg-rate` (see [Built-in devices](/tools/builtin-devices/#fairmq-bsampler)).
The test checks a low lower limit of the time (350 ms for 0.5 s), because a slow machine makes the
loop slower, never faster. The upper limit is 5 s:
<Snippet file="test/tools/_tools.cxx" start="TEST(RateLimiter, LimitsTheRate)" />
The test `RateLimiter.ZeroRateDoesNotSleep` checks that 100000 calls with the rate 0 take less
than 1 s.
## Version.h
[`Version`](/api/fair/mq/tools/Version/) holds three numbers:
[`fkMajor`](/api/fair/mq/tools/Version/#fkMajor), [`fkMinor`](/api/fair/mq/tools/Version/#fkMinor)
and [`fkPatch`](/api/fair/mq/tools/Version/#fkPatch), all `const int`. Make it with braces, for
example `fair::mq::tools::Version{1, 2, 0}`.
- The operators `<`, `>`, `<=`, `>=`, `==` and `!=` compare the major, then the minor, then the
patch number.
- [`operator<<`](/api/fair/mq/tools/Version/#operator-shl) writes `1.2.0`.
The type is part of the device and plugin API:
- The constructors [`Device(tools::Version)`](/api/fair/mq/Device/#Device-3) and
[`Device(ProgOptions&, tools::Version)`](/api/fair/mq/Device/#Device-4) set the version of your
device. The default is `{0, 0, 0}`. [`GetVersion()`](/api/fair/mq/Device/#GetVersion) returns it.
`DeviceRunner` logs it for `--version`. Today `--version` prints nothing: this is a known defect,
see the disabled tests in `test/device/_runner.cxx`.
- [`Plugin::Version`](/api/fair/mq/Plugin/#Version) is an alias of `tools::Version`. See
[Write a plugin](/guides/write-plugin/).
<Snippet file="test/plugins/_plugin.cxx" start="TEST(PluginVersion, Operators)" />
## Exceptions.h
[`CallOnDestruction`](/api/fair/mq/tools/CallOnDestruction/) calls a function in its destructor.
Use it to run code when a scope ends with an exception, without a `catch` block.
| Member | What it does |
| --- | --- |
| [`CallOnDestruction(std::function<void()> c, bool enable = true)`](/api/fair/mq/tools/CallOnDestruction/#CallOnDestruction) | Stores the function. |
| [`enable()`](/api/fair/mq/tools/CallOnDestruction/#enable), [`disable()`](/api/fair/mq/tools/CallOnDestruction/#disable) | Switch the call on or off. |
| [`~CallOnDestruction()`](/api/fair/mq/tools/CallOnDestruction/#dtor) | Calls the function if the object is enabled. |
The device uses it in the state `RUNNING`. If `PreRun()`, `ConditionalRun()`, `Run()`, `PostRun()`
or a data callback throws, the destructor requests the transition `ERROR FOUND`. At the normal end of the function,
`cod.disable()` stops the call ([Device.cxx](/source/fairmq/Device.cxx/#L398-L431)):
<Snippet file="fairmq/Device.cxx" start="tools::CallOnDestruction cod(" />
`StateMachine::ProcessWork()` uses the same pattern to go to `ERROR`
([StateMachine.cxx](/source/fairmq/StateMachine.cxx/#L400-L413)). A destructor is `noexcept` by
default in C++. Thus a callback that throws ends the program with `std::terminate()`. No test of
`test/tools/` covers this class. The tests of the `ERROR` state in `test/device/` show its effect.
## Semaphore.h
Internal in practice: the library does not use these classes.
| Class | Description |
| --- | --- |
| [`Semaphore`](/api/fair/mq/tools/Semaphore/) | A counting semaphore with a mutex and a condition variable. Not copyable. |
| [`SharedSemaphore`](/api/fair/mq/tools/SharedSemaphore/) | Copyable. All copies share one `Semaphore` through a `std::shared_ptr`. |
Both classes have the same members:
[`Semaphore()`](/api/fair/mq/tools/Semaphore/#Semaphore) starts with the count 0, and
[`explicit Semaphore(std::size_t initial_count)`](/api/fair/mq/tools/Semaphore/#Semaphore-2) with the given
count. [`Wait()`](/api/fair/mq/tools/Semaphore/#Wait) blocks until the count is above 0, then
decrements it. [`Signal()`](/api/fair/mq/tools/Semaphore/#Signal) increments the count and wakes one
waiting thread. [`GetCount()`](/api/fair/mq/tools/Semaphore/#GetCount) returns the count.
`Wait()` has no timeout. For tests, the test helper `test::Semaphore` in
[`test/helper/Sync.h`](https://github.com/FairRootGroup/FairMQ/blob/dev/test/helper/Sync.h) has a
`Wait()` with a deadline, so that a missing signal does not block the test. An installed FairMQ does
not contain the test helpers. Copy the file into your project if you need it.
<Snippet file="test/tools/_tools.cxx" start="TEST(SharedSemaphore, CopiesShareTheCount)" />
## InstanceLimit.h
Internal in practice: the library does not use this class.
[`InstanceLimiter<Tag, Max>`](/api/fair/mq/tools/InstanceLimiter/) counts its objects. The
constructor increments a static counter. If `Max` objects exist already, it throws
`std::runtime_error` with the text `More than <Max> instances of <Tag> in parallel not supported`.
The destructor decrements the counter. [`GetCount()`](/api/fair/mq/tools/InstanceLimiter/#GetCount)
returns it.
- Each pair of `Tag` and `Max` has its own counter.
- `Tag` must be default-constructible and must have an `operator<<`, because the text of the
exception contains `Tag()`.
- The counter is a plain `static int` without a lock
([InstanceLimit.h](/source/fairmq/tools/InstanceLimit.h/#L46-L50)).
In the test, `TestTag` writes `TestTag` with its `operator<<`:
<Snippet file="test/tools/_tools.cxx" start="TEST(InstanceLimiter, ThrowsAboveTheLimit)" />
## IO.h
Internal in practice: the control plugin uses it for the keys of the interactive mode
([Control.cxx](/source/fairmq/plugins/control/Control.cxx/#L162)), and `fairmq-shmmonitor -i` for
its keys ([Monitor.cxx](/source/fairmq/shmem/Monitor.cxx/#L368)). `fairmq/Tools.h` does not include
this header.
The constructor of [`NonCanonicalInput`](/api/fair/mq/tools/NonCanonicalInput/) switches off the
flags `ICANON` and `ECHO` of the terminal on the standard input. Then a program gets each key at
once, and the terminal does not show it. The destructor switches both flags on again. It does not
restore the earlier settings. The class is not copyable and not movable. No test covers it.
## Compiler.h and CppSTL.h
Both headers are internal.
- `Compiler.h` defines the macro `__FAIRMQ_ALWAYS_INLINE` as `__attribute__((always_inline)) inline`.
No file of the repository uses it.
- `CppSTL.h` contains only the empty namespace `fair::mq::tools`.
## fairmq-uuid-gen
`fairmq-uuid-gen` prints a new random UUID, or the hash of a new UUID, and stops. It calls
[`Uuid()`](/api/fair/mq/tools/#Uuid) or [`UuidHash()`](/api/fair/mq/tools/#UuidHash). The build makes
it in the directory `fairmq` of the build tree. The installation puts it into `<prefix>/bin`. The
imported target is `FairMQ::fairmq-uuid-gen` (see
[Use FairMQ in a CMake project](/start/cmake/#imported-targets)).
<OptionsTable file="fairmq/tools/runUuidGenerator.cxx" id="uuid" />
:::caution[`-h` is not the help]
`-h` is the short form of `--hash`. The help has only the long form `--help`.
:::
| Command | Output |
| --- | --- |
| `fairmq-uuid-gen` | A UUID with 36 characters. |
| `fairmq-uuid-gen -h` | The hash as a decimal number. |
| `fairmq-uuid-gen --help` | `UUID generator` and the options. |
The output is one line on the standard output:
<Snippet file="fairmq/tools/runUuidGenerator.cxx" start="if (hash)" end="return 0;" />
The exit code is 0. For a wrong option, the tool writes
`Unhandled Exception reached the top of main: <text>, application will now exit` to the standard
error and returns 2.
The test scripts of the examples make a new session name for each run with `-h`. They also use the
session name in the `ipc://` addresses, so that two tests at the same time do not use the same
shared memory or the same socket files:
<Snippet file="examples/1-1/test-ex-1-1.sh.in" start='session="$(' end="chanAddr=" />
The hash has only digits, so it can be part of a file name. [Test your devices](/guides/test-devices/)
shows a complete test script.
## Related pages
- [Test your devices](/guides/test-devices/): `fairmq-uuid-gen` and `execute()` in tests.
- [Receive data with callbacks or loops](/guides/receive-data/#use-conditionalrun): `--rate` and the `RateLimiter`.
- [Configure channels](/guides/configure-channels/): addresses, network interfaces and host names.
- [Sessions and segments](/shmem/sessions/#keep-two-topologies-apart): why each test needs its own session.
- [API reference of fair::mq::tools](/api/fair/mq/tools/)

View File

@@ -0,0 +1,159 @@
---
title: 'Transfer codes and errors'
description: 'The return values of Send() and Receive(), the ErrorCode values with their messages, and all exception types of FairMQ.'
sidebar:
order: 5
code: [fairmq/Socket.h, fairmq/Error.h, fairmq/Message.h, fairmq/Device.h, fairmq/zeromq/Common.h]
---
This page lists the return values of the transfer functions, the error codes of `fairmq/Error.h`,
and all exception types of FairMQ. For the handling of these errors, see
[Handle errors and timeouts](/guides/errors-timeouts/).
## Transfer codes
The enum [`fair::mq::TransferCode`](/api/fair/mq/TransferCode/) is in
[`fairmq/Socket.h`](/source/fairmq/Socket.h/#L25-L31). Its underlying type is `int`.
| Code | Value | Returned when |
| --- | --- | --- |
| [`success`](/api/fair/mq/TransferCode/#success) | 0 | Never. A complete transfer returns the number of bytes, which is 0 for an empty message. |
| [`error`](/api/fair/mq/TransferCode/#error) | -1 | The transfer failed. The transport logs `Failed transfer on socket …` with the reason. If the transport is terminated, it logs `Terminating socket …` (severity `debug`). |
| [`timeout`](/api/fair/mq/TransferCode/#timeout) | -2 | The timeout ended before the transfer was possible. With the timeout 0, the transfer was not possible at once. |
| [`interrupted`](/api/fair/mq/TransferCode/#interrupted) | -3 | The transport is interrupted, because a transition is pending. |
These functions return an `int64_t` with the number of bytes or a negative code:
| Function | Description |
| --- | --- |
| [`Device::Send()`](/api/fair/mq/Device/#Send), [`Device::Receive()`](/api/fair/mq/Device/#Receive) | Use the timeout of the channel. |
| [`Device::Send(…, timeout)`](/api/fair/mq/Device/#Send-2), [`Device::Receive(…, timeout)`](/api/fair/mq/Device/#Receive-2) | Use the timeout argument. |
| [`Channel::Send()`](/api/fair/mq/Channel/#Send), [`Channel::Receive()`](/api/fair/mq/Channel/#Receive) | Use the timeout argument, if you give one. Otherwise they use the timeout of the channel. |
| [`Socket::Send()`](/api/fair/mq/Socket/#Send), [`Socket::Receive()`](/api/fair/mq/Socket/#Receive) | The virtual functions of the transports. The default timeout is `-1`. |
All functions accept a `MessagePtr`, a `Parts` or a `std::vector<MessagePtr>`. For a multipart
message, the number of bytes is the sum of all parts.
### Timeout values
| Timeout | Behavior |
| --- | --- |
| Negative, default `-1` | Wait until the transfer is possible, or until an interruption. |
| `0` | Do not wait. |
| Positive | Wait up to this time in ms, rounded up to a multiple of 100 ms. |
The channel properties `sndTimeoutMs` and `rcvTimeoutMs` give the timeout of a channel. Their
default is `-1` ([`Channel.h`](/source/fairmq/Channel.h/#L376-L377)). The steps of 100 ms come from
the internal socket timeout of the zeromq and shmem transports
([`zeromq/Common.h`](/source/fairmq/zeromq/Common.h/#L64-L77)).
:::caution[Known defect]
The transports do not agree on an empty `Parts`. zeromq logs `Will not send empty vector` and returns
`error`. shmem sends a message with zero parts and returns 0. See the disabled test
`PartsTransfer.EmptyPartsIsRefused` in `test/parts/_access.cxx`.
:::
## Error codes
The enum [`fair::mq::ErrorCode`](/api/fair/mq/ErrorCode/) is in
[`fairmq/Error.h`](/source/fairmq/Error.h/#L31-L39). Its category
[`ErrorCategory`](/api/fair/mq/ErrorCategory/) has the name `fairmq`. The messages come from
[`ErrorCategory::message()`](/api/fair/mq/ErrorCategory/#message).
| Code | Value | Message | Used by |
| --- | --- | --- | --- |
| [`OperationInProgress`](/api/fair/mq/ErrorCode/#OperationInProgress) | 10 | `async operation already in progress` | Not used in this version. |
| [`OperationTimeout`](/api/fair/mq/ErrorCode/#OperationTimeout) | 11 | `async operation timed out` | Not used in this version. |
| [`OperationCanceled`](/api/fair/mq/ErrorCode/#OperationCanceled) | 12 | `async operation canceled` | Not used in this version. |
| [`DeviceChangeStateFailed`](/api/fair/mq/ErrorCode/#DeviceChangeStateFailed) | 13 | `failed to change state of a fairmq device` | [`Device::ChangeStateOrThrow()`](/api/fair/mq/Device/#ChangeStateOrThrow) |
| [`DeviceGetPropertiesFailed`](/api/fair/mq/ErrorCode/#DeviceGetPropertiesFailed) | 14 | `failed to get fairmq device properties` | Not used in this version. |
| [`DeviceSetPropertiesFailed`](/api/fair/mq/ErrorCode/#DeviceSetPropertiesFailed) | 15 | `failed to set fairmq device properties` | Not used in this version. |
| Other values | — | `(unrecognized error)` | — |
[`MakeErrorCode(ErrorCode)`](/api/fair/mq/#MakeErrorCode) returns a `std::error_code` with the value
and the category. `ChangeStateOrThrow()` throws a `std::system_error` with this code and the text
`Invalid transition: <NAME>`.
:::caution
- `fairmq/Error.h` specializes `std::is_error_code_enum` for `ErrorCode`, but it has no function
`make_error_code()`. Thus `std::error_code ec = fair::mq::ErrorCode::OperationTimeout;` does not
compile. Use `MakeErrorCode()`.
- The category object `fair::mq::ec` is `static` in the header. Each translation unit has its own
object, and a comparison of two `std::error_code` objects can fail. Compare `value()` and
`category().name()`.
:::
## FairMQ exceptions
All exceptions of FairMQ derive from `std::runtime_error`, except `PluginManager::BadSearchPath`.
Thus `catch (std::exception const&)` catches all of them. The namespace is `fair::mq`.
### Device, states and configuration
| Exception | Header | Thrown when |
| --- | --- | --- |
| [`DeviceErrorState`](/api/fair/mq/DeviceErrorState/) | [`States.h`](/source/fairmq/States.h/#L60) | A `StateQueue` gives the state `ERROR`, for example in `Device::WaitForState()`. The interactive controller also throws it in `ERROR`. Text: `Controlled device transitioned to error state.` |
| [`StateMachine::ErrorStateException`](/api/fair/mq/StateMachine/ErrorStateException/) | [`StateMachine.h`](/source/fairmq/StateMachine.h/#L56) | `RunStateMachine()` ends after the transition `ErrorFound`. Text: `Device transitioned to error state`. |
| [`PropertyNotFoundError`](/api/fair/mq/PropertyNotFoundError/) | [`ProgOptions.h`](/source/fairmq/ProgOptions.h/#L30) | `GetProperty<T>(key)` or `GetPropertyAsString(key)` without a default, for a key that does not exist. Text: `Config has no key: <key>`. |
| [`ParserError`](/api/fair/mq/ParserError/) | [`JSONParser.h`](/source/fairmq/JSONParser.h/#L27) | `JSONParser()`, `SuboptParser()` or `PtreeParser()` gets an empty device id. The config plugin does not call the parser without an id. |
| [`Channel::ChannelConfigurationError`](/api/fair/mq/Channel/ChannelConfigurationError/) | [`Channel.h`](/source/fairmq/Channel.h/#L89) | `Channel::Validate()` finds an invalid type, an invalid method, a negative buffer or kernel size, or a negative `rateLogging`. |
| [`PollerError`](/api/fair/mq/PollerError/) | [`Poller.h`](/source/fairmq/Poller.h/#L37) | A poller gets an unknown channel name (in the constructor, `CheckInput()` or `CheckOutput()`), or the poll fails. |
| [`OngoingTransition`](/api/fair/mq/OngoingTransition/) | [`Device.h`](/source/fairmq/Device.h/#L46) | Not thrown in this version. |
| [`RuntimeError`](/api/fair/mq/RuntimeError/) | [`Error.h`](/source/fairmq/Error.h/#L23) | Not thrown in this version. Its constructor joins all arguments to one text. |
### Transports, sockets and messages
| Exception | Header | Thrown when |
| --- | --- | --- |
| [`TransportFactoryError`](/api/fair/mq/TransportFactoryError/) | [`TransportFactory.h`](/source/fairmq/TransportFactory.h/#L237) | `TransportFactory::CreateTransportFactory()` gets an unknown type. Text: `Unavailable transport requested: <type>`. |
| [`TransportError`](/api/fair/mq/TransportError/) | [`Transports.h`](/source/fairmq/Transports.h/#L22) | A channel has an unknown transport (`Unknown transport provided: <name>`), or a region message gets a region of the other transport. Also when shmem cannot create, open or lock a segment or a region, when a region id already exists, when the data of a region message is outside the region, or when the region of a message is unknown. In the constructor of the shmem transport, a segment error becomes a `std::runtime_error` (see below). |
| [`SocketError`](/api/fair/mq/SocketError/) | [`Socket.h`](/source/fairmq/Socket.h/#L99) | A socket cannot be created, or a socket option cannot be set or read. With shmem also for `pub` and `sub` sockets, and for a received message that is not a shmem message. |
| [`MessageBadAlloc`](/api/fair/mq/MessageBadAlloc/) | [`Message.h`](/source/fairmq/Message.h/#L74) | shmem cannot allocate a message: the size is larger than the segment, the attempts end, or a transition interrupts the wait between two attempts. |
| [`RefCountBadAlloc`](/api/fair/mq/RefCountBadAlloc/) | [`Message.h`](/source/fairmq/Message.h/#L79) | shmem copies a message of an unmanaged region, and the reference count segment of the region is full. |
| [`MessageError`](/api/fair/mq/MessageError/) | [`Message.h`](/source/fairmq/Message.h/#L69) | Only in a build with `FAIRMQ_DEBUG_MODE`: shmem resets the transport while messages still exist. |
| [`shmem::SharedMemoryError`](/api/fair/mq/shmem/SharedMemoryError/) | [`shmem/Common.h`](/source/fairmq/shmem/Common.h/#L37) | The option `shm-allocation` has an unknown value, or shmem cannot find the segment or the region of a message. Also when `shmem::GetDataAddressFromHandle()` gets a transport that is not shmem. |
| [`shmem::Monitor::DaemonPresent`](/api/fair/mq/shmem/Monitor/DaemonPresent/) | [`shmem/Monitor.h`](/source/fairmq/shmem/Monitor.h/#L158) | A monitor in monitoring mode already runs for this session. |
| [`shmem::Monitor::MonitorError`](/api/fair/mq/shmem/Monitor/MonitorError/) | [`shmem/Monitor.h`](/source/fairmq/shmem/Monitor.h/#L159) | The monitor cannot find a segment, or the allocation algorithm is unknown. |
| `zmq::Error` | [`zeromq/Common.h`](/source/fairmq/zeromq/Common.h/#L21) | A socket type or a socket option name is unknown. Text: `getConstant called with an invalid argument: <name>`. |
| `zmq::ContextError` | [`zeromq/Context.h`](/source/fairmq/zeromq/Context.h/#L32) | The zeromq context cannot be created or configured. |
| [`tools::DefaultRouteDetectionError`](/api/fair/mq/tools/DefaultRouteDetectionError/) | [`tools/Network.h`](/source/fairmq/tools/Network.h/#L19) | The network interface of the default route is unknown. For a bind channel without an address, the device catches it and binds to `tcp://*:1`. See [Network.h](/reference/tools/#networkh). |
### Plugins
| Exception | Header | Thrown when |
| --- | --- | --- |
| [`PluginServices::DeviceControlError`](/api/fair/mq/PluginServices/DeviceControlError/) | [`PluginServices.h`](/source/fairmq/PluginServices.h/#L94) | A plugin calls `TakeDeviceControl()` or `ChangeDeviceState()` while another plugin controls the device. |
| [`PluginManager::BadSearchPath`](/api/fair/mq/PluginManager/BadSearchPath/) | [`PluginManager.h`](/source/fairmq/PluginManager.h/#L74) | A plugin search path is empty or is not a directory. The base class is `std::invalid_argument`. |
| [`PluginManager::PluginNotFound`](/api/fair/mq/PluginManager/PluginNotFound/) | [`PluginManager.h`](/source/fairmq/PluginManager.h/#L77) | The plugin manager cannot find the file of a plugin. |
| [`PluginManager::PluginLoadError`](/api/fair/mq/PluginManager/PluginLoadError/) | [`PluginManager.h`](/source/fairmq/PluginManager.h/#L80) | The plugin manager cannot load a plugin. |
| [`PluginManager::PluginInstantiationError`](/api/fair/mq/PluginManager/PluginInstantiationError/) | [`PluginManager.h`](/source/fairmq/PluginManager.h/#L82) | The plugin manager cannot create a plugin object. |
| [`PluginManager::ProgramOptionsParseError`](/api/fair/mq/PluginManager/ProgramOptionsParseError/) | [`PluginManager.h`](/source/fairmq/PluginManager.h/#L85) | The options of the plugin manager on the command line are not valid. |
## Standard exceptions
FairMQ also throws exceptions of the standard library and of Boost:
| Exception | Thrown when |
| --- | --- |
| `std::system_error` | `Device::ChangeStateOrThrow()`: the state machine refuses the transition. |
| `std::out_of_range` | A name function of `States.h` gets an unknown name or value. `Device::GetChannel()` and `GetNumSubChannels()` get an unknown channel. The property `transport` of the device has an unknown value. |
| `std::runtime_error` | In `BINDING`, a channel cannot bind. In `CONNECTING`, the time `init-timeout` ends. In `INITIALIZING DEVICE`, a channel has no method. `Device::NewPoller()` gets channels with different transports. The shmem transport cannot start: `failed creating context, reason: …` or `Could not initialize shared memory transport: …`. |
| `std::bad_alloc` | zeromq cannot allocate the buffer of a message with an alignment (`malloc()` fails). A shmem socket cannot allocate the zeromq message for the metadata. |
| `boost::bad_any_cast` | `GetProperty<T>()` with a type `T` that is not the type of the property. |
| `boost::program_options::error` | The command line has a value that is not valid for its option, or a required option is missing. |
In a hook, each of these exceptions moves the device to `ERROR`. See
[Device states](/concepts/states/). The config plugin is different: it catches the exceptions of the
parsers for `--mq-config` and `--channel-config`, and logs their text with the severity `error`.
The device then starts without these channels.
## Related pages
- [Handle errors and timeouts](/guides/errors-timeouts/): how to react to these codes and
exceptions.
- [States and transitions](/reference/states/): the errors of invalid transitions.
- [Channel properties](/reference/channel-properties/): `sndTimeoutMs`, `rcvTimeoutMs` and the other
properties.
- [Tune shared memory](/shmem/tuning/): the options for the shmem allocation.
- [Channels and sockets](/concepts/channels/#behavior-of-each-socket-type): when each socket type waits,
drops a message or returns an error.

View File

@@ -0,0 +1,174 @@
---
title: 'How shared memory works'
description: 'The shmem transport moves only a small header through the socket. The data stays in shared memory.'
sidebar:
order: 1
code: [fairmq/shmem/Socket.h, fairmq/shmem/Message.h, fairmq/shmem/Manager.h, fairmq/shmem/Common.h, fairmq/shmem/TransportFactory.h]
---
import ZeroCopyExplainer from '../../../components/diagrams/ZeroCopyExplainer.astro';
import Snippet from '../../../components/Snippet.astro';
The shmem transport moves messages between devices on one host without a copy of the payload.
The payload stays in a shared memory segment. Only a small header goes through a ZeroMQ socket.
<ZeroCopyExplainer />
## Use the shmem transport
Set `--transport shmem` for the device, or set the property `transport` of a channel. The default
transport is `zeromq`. This example starts the sampler and the sink of the 1-1 example with shmem:
```sh
fairmq-ex-1-1-sampler --id sampler1 --transport shmem --rate 1 \
--channel-config name=data,type=push,method=bind,address=ipc:///tmp/fmq-1-1-data
fairmq-ex-1-1-sink --id sink1 --transport shmem \
--channel-config name=data,type=pull,method=connect,address=ipc:///tmp/fmq-1-1-data
```
The code of the devices does not change. [`NewMessage()`](/api/fair/mq/Device/#NewMessage),
[`Send()`](/api/fair/mq/Device/#Send) and [`Receive()`](/api/fair/mq/Device/#Receive) are the same
for all transports. The two devices find the same shared memory because they have the same session
(`default`) and the same user. See [Sessions and segments](/shmem/sessions/).
## The parts of the transport
| Part | What it does |
| --- | --- |
| [`Manager`](/api/fair/mq/shmem/Manager/) | One for each shmem transport factory. A device has one. The manager opens or creates the shared memory of the session, counts the devices and writes a heartbeat every 100 ms. |
| Managed segment | A segment of Boost.Interprocess (on Linux, a file in [`/dev/shm`](/shmem/tuning/#space-in-devshm)), with the name `fmq_<shmId>_m_0`. [`NewMessage(size)`](/api/fair/mq/shmem/TransportFactory/#CreateMessage-3) allocates the blocks of the messages in it. The size is `--shm-segment-size`, default 2 GiB. |
| Management segment | `fmq_<shmId>_mng`, 6.25 MiB. It holds the data that the devices of a session share: counters and the lists of segments and regions. |
| Socket | Each shmem socket is a ZeroMQ socket of the same type. It carries only the metadata of the messages. |
## A block in the segment
`NewMessage(size)` allocates a block in the segment of the device. Before the payload, the block has
a small header ([`ShmHeader`](/api/fair/mq/shmem/ShmHeader/)). The header holds the reference count
of the block and the offset of the payload. The payload starts at an aligned address: at least
`alignof(std::max_align_t)`, or the [`Alignment`](/api/fair/mq/Alignment/) that you give.
The message object in your process holds the metadata of the block: the size, the handle, the ID of
the segment and a local pointer. The handle is a handle of Boost.Interprocess: the offset of the
block from the start of the segment. The handle is the same in all processes. The address is not the same, because each process
maps the segment at a different address.
## Send a message
`Send()` writes the metadata of the message into a [`MetaHeader`](/api/fair/mq/shmem/MetaHeader/) and
sends it in one ZeroMQ message ([Socket.h](/source/fairmq/shmem/Socket.h/#L118-L161)). The payload
does not go through the socket.
| Field | Type | Content |
| --- | --- | --- |
| `fSize` | `size_t` | Size of the payload in bytes. |
| `fHint` | `size_t` | The hint of a region message. FairMQ gives it back in the region callback. |
| `fHandle` | `handle_t` | Offset of the block in the managed segment, or of the data in the region. |
| `fShared` | `handle_t` | Handle of the shared reference count of a copied region message. `-1`: no copy. |
| `fRegionId` | `uint16_t` | ID of the unmanaged region. |
| `fSegmentId` | `uint16_t` | ID of the managed segment. |
| `fManaged` | `bool` | `true`: the block is in a managed segment. `false`: the block is in an unmanaged region. |
On 64-bit systems the `MetaHeader` has 40 bytes. It is the wire format of the transport, so a test
checks its size and the offsets of its fields.
After a successful send, the transport marks the message of the sender as queued. A queued message
does not free its block when you destroy it, because the receiver owns the block now. `Send()`
returns the size of the payload, not the size of the header.
For a multipart message, `Send()` puts all headers into one ZeroMQ message: the number of parts, then
one `MetaHeader` for each part. The queue limits of the channel (`sndBufSize`, `rcvBufSize`) count
this as one message. The option `--shm-metadata-msg-size` can make the ZeroMQ message larger, see
[Tune and debug](/shmem/tuning/#set-the-size-of-the-metadata-message).
## Receive a message
`Receive()` reads the `MetaHeader` into the message. It does not touch the payload. The first call of
[`GetData()`](/api/fair/mq/Message/#GetData) changes the handle into an address in the receiver. The
address is the start of the segment in the receiver plus the handle. If the receiver did not open
this segment before, the transport opens it now. For a region message, the address is the start of
the region plus the handle.
The receiver reads the payload in place. `Receive()` returns the size of the payload.
Both ends of a channel must use the same transport. If `Receive()` of a single message gets fewer
bytes than one `MetaHeader`, it throws [`SocketError`](/api/fair/mq/SocketError/): "Received message
is not a valid FairMQ shared memory message". `Receive()` of a multipart message does not check this.
## Copy a message without a copy
[`Copy()`](/api/fair/mq/Message/#Copy) of the shmem transport does not copy the payload. The new
message points to the same block, and the transport increments the reference count of the block.
[`GetRefCount()`](/api/fair/mq/shmem/Message/#GetRefCount) of
[`shmem::Message`](/api/fair/mq/shmem/Message/) shows the count. In this test, the original and the
copy have the same data address and a reference count of 2. After the copy is destroyed, the count
is 1 again:
<Snippet file="test/message/_message.cxx" start="auto ZeroCopy(bool" />
Use `Copy()` to send the same data on two channels: send the original on one channel and the copy
on the other. Do not change the data after `Copy()`. The interface defines that as undefined
behavior, and all copies use the same memory. The interface does not guarantee that `Copy()` does
not copy. It is a property of the shmem transport.
## Free the block
When you destroy a message or call [`Rebuild()`](/api/fair/mq/Message/#Rebuild), the transport
decrements the reference count of the block. When the count was 1, the transport gives the block back
to the segment ([Message.h](/source/fairmq/shmem/Message.h/#L372-L411)). Then new messages can use the
memory.
A message in an unmanaged region does not go back to a segment. The transport sends an
acknowledgement to the creator of the region. See [Unmanaged regions](/shmem/regions/).
## Data from your own buffer
The shmem transport cannot use a buffer of your process in place. `NewMessage(data, size, ffn, hint)`
allocates a block in the segment, copies the data into it, and calls `ffn(data, hint)` at once. If
`ffn` is `nullptr`, the transport calls `free(data)`
([Message.h](/source/fairmq/shmem/Message.h/#L64-L78)). With the size 0, the transport calls
neither `ffn` nor `free()`. `NewSimpleMessage()` and `NewStaticMessage()` use the same constructor,
so they also copy. To send a buffer of your own with each transport, see
[Send a buffer of your own](/guides/send-data-types/#send-a-buffer-of-your-own).
If you send a message of another transport on a shmem channel, the channel copies it into a new
shmem message. To write data into shared memory directly, with your own layout, use an
[unmanaged region](/shmem/regions/).
## Rules for your code
- Do not use the data of a message after a successful `Send()`. The receiver owns the block.
- Do not keep a pointer from `GetData()` after you destroy or rebuild the message. The segment gives
the memory to new messages.
- Do not change the data of a message after `Copy()`.
- Do not give an address to another process. The address is valid only in your process. Send the
message, or send its `MetaHeader` (see [Out-of-band buffers](/shmem/side-channel/)).
- Receive into an empty message, for example from `NewMessage()`. To use a message again for
`Receive()`, for example after `Send()`, call `Rebuild()` first. `Receive()` replaces only the
metadata. It does not free the old block, and `GetData()` can then return the old address.
- Receive a multipart message into `Parts`, and a single message into a `MessagePtr`. The metadata of
the two has a different format, and the shmem transport does not check it.
- Destroy all messages and regions before the device destroys its transports. The device does that
in the state `RESETTING DEVICE`. Destroy them in `ResetTask()` at the latest.
## Limits
- **One host.** The socket can use `tcp://`, but the segment exists only on the local host. All
devices of a session must run on the same host. FairMQ does not check this. For devices in
containers, see [Containers](/shmem/sessions/#containers).
- **One user and one session.** The names of the shared memory objects contain a hash of the user ID
and the session name. See [Sessions and segments](/shmem/sessions/).
- **No `pub` and `sub`.** A shmem socket of the type `pub` or `sub` throws `SocketError` ("PUB/SUB
socket type is not supported for shared memory transport"). To send the same data to several
receivers, use `Copy()` and one channel for each receiver. The tests run `push`/`pull`, `pair` and
`req`/`rep` with shmem.
- **The segment size.** A message must fit into the segment. If it does not fit, `NewMessage()` throws
[`MessageBadAlloc`](/api/fair/mq/MessageBadAlloc/) at once. If the segment is full, `NewMessage()`
throws `MessageBadAlloc` or tries again. See [Tune and debug](/shmem/tuning/).
## Related pages
- [Sessions and segments](/shmem/sessions/): the shared memory objects of a session.
- [Unmanaged regions](/shmem/regions/): memory that your device fills itself.
- [Tune and debug](/shmem/tuning/): segment size, full segments and debug mode.
- [Transports](/concepts/transports/): the zeromq and the shmem transport.
- [Messages and multipart](/concepts/messages/): the message interface.

View File

@@ -0,0 +1,340 @@
---
title: 'Monitor and clean up'
description: 'Find and remove shared memory that devices left behind.'
sidebar:
order: 4
code: [fairmq/shmem/Monitor.h, fairmq/shmem/Monitor.cxx, fairmq/shmem/Manager.h, fairmq/shmem/Manager.cxx, fairmq/shmem/runMonitor.cxx]
---
import Snippet from '../../../components/Snippet.astro';
Shared memory stays in the system until a process removes it. Normally, the last device of a
session removes it. This page tells you how to find shared memory that stays, and how to remove it.
## When shared memory stays
The last shmem transport of a session removes all objects of the session. See
[The device counter and cleanup](/shmem/sessions/#the-device-counter-and-cleanup). The objects
stay in these cases:
- A device stops and does not destroy its transport, for example after a crash or `kill -9`. Its
count stays in the device counter, so the counter does not reach 0. See also
[Shared memory after a peer ends](/guides/errors-timeouts/#shared-memory-after-a-peer-ends).
- The devices run with `--shm-no-cleanup true`.
- The creator of a file-backed region stops and does not destroy the region. The file stays.
The objects use memory of the system until you remove them. If you start devices with the same
session again, they open the old objects. The device counter then starts at the old value and does
not reach 0 when the devices stop.
## Find the shared memory
### All sessions
`fairmq-shmmonitor --list-all` looks for the files of FairMQ in `/dev/shm/`. For each management
segment, it prints the status of the session. For each file that does not start with `fmq_` or
`sem.fmq_`, it prints "The file '…' does not belong to FairMQ, skipping...".
```sh
fairmq-shmmonitor --list-all
```
The option `--list-all-path` sets a different directory.
You can also list the files directly. All names start with `fmq_<shmId>_` or `sem.fmq_<shmId>_`:
```sh
ls -l /dev/shm/ | grep fmq_
```
### One session
Without a mode option, `fairmq-shmmonitor` prints the status of one session one time and stops:
```sh
fairmq-shmmonitor --session default
fairmq-shmmonitor --shmid eca859e3
```
The status has this form ([Monitor.cxx](/source/fairmq/shmem/Monitor.cxx/#L185-L304)). The tool
writes it as one log entry with a time stamp before the first line. The sample shows it without the
time stamp:
```txt
shm id: <shmId>, session: <name>, creator id: <user ID>, devices: <n>, managed segments:
[<segment ID>]: total: <bytes>, msgs: <n>, free: <bytes>, used: <bytes>
[m]: total: <bytes>, free: <bytes>, used: <bytes>
unmanaged regions:
[<region ID>]: alive, size: <bytes>, rcCountSegment size: <bytes>, free: <bytes>, used: <bytes>
```
- `devices` is the device counter. If it is not 0 and no device of the session runs, a device did
not stop correctly.
- `msgs` is the number of messages in the segment. It shows `NODEBUG` if FairMQ was compiled
without `FAIRMQ_DEBUG_MODE`.
- `[m]` is the management segment.
- A region is `alive` or `destroyed`. For a region without a reference count segment, the line ends
with `rcCountSegment: not found`.
If the session does not exist, the tool prints `No segments found.`
### From code
The class [`fair::mq::shmem::Monitor`](/api/fair/mq/shmem/Monitor/) has static functions to check a
session. Each function takes a [`SessionId`](/api/fair/mq/shmem/SessionId/) or a
[`ShmId`](/api/fair/mq/shmem/ShmId/). A `SessionId` gives the shmId for the current user.
- [`SegmentIsPresent(id, segmentId)`](/api/fair/mq/shmem/Monitor/#SegmentIsPresent) returns `true` if
the segment exists.
- [`RegionIsPresent(id, regionId)`](/api/fair/mq/shmem/Monitor/#RegionIsPresent) returns `true` if
the region exists.
- [`GetFreeMemory(id, segmentId)`](/api/fair/mq/shmem/Monitor/#GetFreeMemory) returns the free bytes
of a segment. It throws [`MonitorError`](/api/fair/mq/shmem/Monitor/MonitorError/) if the session
or the segment does not exist.
See [The Monitor API](#the-monitor-api) for all functions.
## Remove the shared memory
Remove the objects of a session only when no device of the session runs.
### With fairmq-shmmonitor
```sh
fairmq-shmmonitor --cleanup --session default
fairmq-shmmonitor --cleanup --shmid eca859e3
```
The tool reads the lists in the management segment. It removes each region with its queue and its
reference count segment, each managed segment, the management segment and the monitor mutex
`sem.fmq_<shmId>_ms`. The transport does not register a file-backed region, so the tool does not
remove its file. The output shows each object that it removed. For a session with one managed
segment, no regions and no monitor, the output is:
```txt
Cleaning up for shared memory id 'eca859e3'...
Found 0 unmanaged regions...
Found 1 managed segments...
Successfully removed 'fmq_eca859e3_m_0'.
Successfully removed 'fmq_eca859e3_mng'.
```
Objects that do not exist give a message only at the severity `debug`. If the management segment
does not exist, the tool cannot find the other objects. It prints "Did not find
'fmq_eca859e3_mng' management segment. No regions to cleanup." Then remove the files by hand.
### From code
[`Monitor::Cleanup()`](/api/fair/mq/shmem/Monitor/#Cleanup) removes the objects of the devices of a
session. It returns a `std::vector` of pairs: the name of each object and `true` if it was removed.
With `verbose = true` (the default), it writes each step to the log.
[`Monitor::CleanupFull()`](/api/fair/mq/shmem/Monitor/#CleanupFull) also removes the monitor mutex.
The command line option `--cleanup` calls `CleanupFull()`.
This test keeps a segment with `--shm-no-cleanup` and then removes it:
<Snippet file="test/transport/_shmem.cxx" start="TEST(Monitor, CleanupAfterNoCleanup)" />
### By hand
On Linux, Boost.Interprocess keeps the objects as files in `/dev/shm`. Remove the files of the
shmId:
```sh
rm /dev/shm/fmq_eca859e3_*
rm /dev/shm/sem.fmq_eca859e3_ms
```
A file-backed region is a file at `<path>fmq_<shmId>_rg_<id>`. Remove it at its path.
### Reset the content
`fairmq-shmmonitor --reset-content` is experimental. It removes all allocations in the managed
segments of a session, but keeps the segments. It also removes the queues and the reference count
segments of the regions. Use it only when no device uses the memory. In code, use
[`Monitor::ResetContent()`](/api/fair/mq/shmem/Monitor/#ResetContent). The program `keep-alive` of
the [region example](/examples/region/) calls it when it receives `SIGUSR1`.
## Automatic cleanup with `--shm-monitor`
With `--shm-monitor true`, the shmem transport makes sure that a monitor daemon runs for the
session. The monitor removes the memory if all devices stop without cleanup.
1. When the transport starts, it looks for the named mutex `sem.fmq_<shmId>_ms`. If the mutex
exists, a monitor runs, and the transport continues.
2. Otherwise it looks for `fairmq-shmmonitor` in the directory `$FAIRMQ_PATH`, then in `$PATH`.
3. It starts the monitor with this command
([Manager.cxx](/source/fairmq/shmem/Manager.cxx/#L26-L53)):
```sh
fairmq-shmmonitor -x -m --shmid <shmId> -d -t 2000
```
4. It waits up to 10000 ms for the named mutex of the monitor.
If the transport cannot find `fairmq-shmmonitor`, it writes a warning and continues without a
monitor:
```txt
could not find fairmq-shmmonitor in "$FAIRMQ_PATH:$PATH"
```
If the monitor does not create its mutex in time, the transport throws, and the device goes to the
state `ERROR`. The error is "Could not initialize shared memory transport: Did not get response
from fairmq-shmmonitor after 10000 milliseconds. Exiting."
Set the environment variable `FAIRMQ_SHMMONITOR_VERBOSE=true` to add `--verbose`. The monitor then
writes its log to a file. The start scripts of the examples set `FAIRMQ_PATH` for the search in
step 2.
### What the daemon does
The command above starts the monitor mode (`-m`) as a daemon (`-d`), with self-destruction (`-x`)
and a heartbeat timeout of 2000 ms (`-t 2000`).
- Each shmem transport increments the heartbeat in the management segment every 100 ms.
- The monitor reads the heartbeat every 200 ms and looks for the management segment every 100 ms.
- If the heartbeat does not change for more than 2000 ms, the monitor removes all objects of the
session. Then it stops.
- If the management segment disappears, the devices removed the memory. The monitor stops.
- If the monitor finds no management segment within 4000 ms (2 × timeout) after its start, it
stops.
- When the monitor stops, it removes its mutex `sem.fmq_<shmId>_ms`.
The heartbeat stops only when all transports of the session stop. If one device crashes, the
monitor waits for the other devices. When they stop, the device counter is not 0, so they do not
remove the memory. Then the heartbeat stops, and the monitor removes the memory.
The monitor writes these messages to its log:
```txt
no heartbeats since over 2000 milliseconds, cleaning...
self destructing (segment has been observed and cleaned up by the monitor)
self destructing (segment has been observed and cleaned up orderly)
self destructing (no segments observed within (timeout * 2) since start)
```
:::caution[`--shm-monitor` removes memory that must stay]
Do not use `--shm-monitor true` together with `--shm-no-cleanup true`. The monitor removes the
memory 2000 ms after the last heartbeat. The start script `fairmq-start-ex-region-advanced-external.sh`
uses `--shm-monitor false` for this reason.
:::
An interactive monitor (`fairmq-shmmonitor -i`) also holds the mutex `sem.fmq_<shmId>_ms`. While it
runs, the transports do not start a daemon. The interactive mode does not remove memory after a
heartbeat timeout. See [fairmq-shmmonitor](/tools/shmmonitor/#interactive-mode).
## Clean up after a crash
A device that crashes leaves the objects of its session. Select one of these ways to remove them.
Each cleanup must run only after all devices of the session stopped.
| Way | It works | It does not work |
| --- | --- | --- |
| A shell trap in the start script | When the script ends, also after an error with `set -e`, `SIGTERM`, `SIGINT` or `SIGHUP` (Bash behavior). | When the script itself gets `SIGKILL`, or when the host stops. |
| A CTest cleanup test | After the tests that require the fixture, also when they fail or time out (CTest behavior). | When `ctest` itself stops. The session name must be fixed in CMake. |
| [`--shm-monitor true`](#automatic-cleanup-with---shm-monitor) | 2000 ms after the last heartbeat, also after `kill -9` of all devices. The daemon runs in its own process session (`setsid()`), so a signal to the process group of the devices does not stop it. | Without `fairmq-shmmonitor` in `$FAIRMQ_PATH` or `$PATH`, or when the monitor stops together with the devices. It also removes the memory of devices with `--shm-no-cleanup true`. |
| A private `/dev/shm` for each Slurm job | At the end of each job (Slurm behavior). | For devices in different jobs: they cannot share memory. It needs a configuration by the administrator. |
| [By hand](#remove-the-shared-memory): `fairmq-shmmonitor --cleanup`, or `rm` of the [files of the session](/shmem/sessions/#the-shared-memory-objects) | At all times when no device of the session runs. | You must know the session name or the shmId. |
### A shell trap
Stop the devices first, then remove the memory. In Bash, the trap `EXIT` also runs when the script
ends because of an error with `set -e`, or because of `SIGTERM`, `SIGINT` or `SIGHUP`. It does not
run on `SIGKILL`.
```sh title="run-1-1.sh"
#!/bin/bash
set -e
session="$(fairmq-uuid-gen -h)"
addr="ipc:///tmp/fmq_${session}_data"
cleanup() {
set +e
kill -TERM $SAMPLER_PID $SINK_PID 2>/dev/null
wait $SAMPLER_PID $SINK_PID
fairmq-shmmonitor --cleanup --session "$session"
}
trap cleanup EXIT
fairmq-ex-1-1-sampler --id sampler1 --transport shmem --session "$session" \
--control static --rate 1 --max-iterations 10 \
--channel-config name=data,type=push,method=bind,address=$addr &
SAMPLER_PID=$!
fairmq-ex-1-1-sink --id sink1 --transport shmem --session "$session" \
--control static --max-iterations 10 \
--channel-config name=data,type=pull,method=connect,address=$addr &
SINK_PID=$!
wait $SAMPLER_PID $SINK_PID
```
After a normal end, the devices removed the memory already, and `fairmq-shmmonitor` only reports
that it did not find the management segment. The short forms of the options are `-c` and `-s`.
The test scripts of the examples (`examples/*/test-ex-*.sh.in`) set their traps on `TERM` only.
### A CTest cleanup test
The tests of FairMQ do not use CTest fixtures. In your project, give the cleanup test the
property `FIXTURES_CLEANUP`. CTest runs it after all tests that give the same fixture name in
`FIXTURES_REQUIRED`, also when they fail (CMake 3.7 or later). Give the topology test and the
cleanup test the same session name:
```cmake
add_test(NAME topology COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/run-topology.sh ci-topology)
add_test(NAME topology-shm-cleanup
COMMAND $<TARGET_FILE:FairMQ::fairmq-shmmonitor> --cleanup --session ci-topology)
set_tests_properties(topology PROPERTIES FIXTURES_REQUIRED shm)
set_tests_properties(topology-shm-cleanup PROPERTIES FIXTURES_CLEANUP shm)
```
`FairMQ::fairmq-shmmonitor` is the imported target of the tool. See
[Imported targets](/reference/cmake/#imported-targets).
### A private /dev/shm for each Slurm job
The Slurm plugin `job_container/tmpfs` gives each job a private `/tmp` and `/dev/shm`. From Slurm
25.11, the plugin has the name `namespace/tmpfs`. When the job ends, Slurm removes all files in them
(Slurm behavior). The administrator sets it in `slurm.conf` and in
[`job_container.conf`](https://slurm.schedmd.com/job_container.conf.html). All devices of
one session must then run in the same job.
## The Monitor API
Include `<fairmq/shmem/Monitor.h>`. The class is in the FairMQ library. All functions in this table
are static. They take a `ShmId` or a `SessionId` as the first argument. `PrintShm()` takes only a
`ShmId`. `ListAll()` and the `Remove…()` functions take a path or a name.
| Function | What it does |
| --- | --- |
| [`Cleanup(id, verbose = true)`](/api/fair/mq/shmem/Monitor/#Cleanup) | Removes the regions, their queues and reference count segments, the managed segments and the management segment. |
| [`CleanupFull(id, verbose = true)`](/api/fair/mq/shmem/Monitor/#CleanupFull) | `Cleanup()`, and removes the monitor mutex. |
| [`ResetContent(id, verbose = true)`](/api/fair/mq/shmem/Monitor/#ResetContent) | Experimental. Removes all allocations in the managed segments, and the queues and reference count segments of the regions. |
| [`ResetContent(id, segmentCfgs, regionCfgs, verbose = true)`](/api/fair/mq/shmem/Monitor/#ResetContent-3) | Experimental. Makes the management segment again, registers the given [`SegmentConfig`](/api/fair/mq/shmem/SegmentConfig/) and `RegionConfig` entries, then resets the content. |
| [`PrintShm(shmId)`](/api/fair/mq/shmem/Monitor/#PrintShm) | Prints the status of the session. Returns `false` if the session does not exist. |
| [`ListAll(path)`](/api/fair/mq/shmem/Monitor/#ListAll) | Prints the status of all sessions in a directory. |
| [`SegmentIsPresent(id, segmentId)`](/api/fair/mq/shmem/Monitor/#SegmentIsPresent) | Returns `true` if the managed segment can be opened. |
| [`RegionIsPresent(id, regionId)`](/api/fair/mq/shmem/Monitor/#RegionIsPresent) | Returns `true` if the region can be opened. |
| [`GetFreeMemory(id, segmentId)`](/api/fair/mq/shmem/Monitor/#GetFreeMemory) | Returns the free bytes of a managed segment. Throws `MonitorError`. |
| [`PrintDebugInfo(id)`](/api/fair/mq/shmem/Monitor/#PrintDebugInfo) | Prints the messages in the segments. Needs `FAIRMQ_DEBUG_MODE`. |
| [`GetDebugInfo(id)`](/api/fair/mq/shmem/Monitor/#GetDebugInfo) | Returns the messages in the segments. Needs `FAIRMQ_DEBUG_MODE`. See the caution below. |
| [`RemoveObject(name)`](/api/fair/mq/shmem/Monitor/#RemoveObject), [`RemoveFileMapping()`](/api/fair/mq/shmem/Monitor/#RemoveFileMapping), [`RemoveQueue()`](/api/fair/mq/shmem/Monitor/#RemoveQueue), [`RemoveMutex()`](/api/fair/mq/shmem/Monitor/#RemoveMutex), [`RemoveCondition()`](/api/fair/mq/shmem/Monitor/#RemoveCondition) | Remove one object by its full name. Return `true` if it was removed. |
:::caution[GetDebugInfo()]
`GetDebugInfo()` has a known defect: it writes out of the bounds of its result vectors and returns
empty lists. Its test is disabled. Use `PrintDebugInfo()` or `fairmq-shmmonitor --debug`.
:::
The tool `fairmq-shmmonitor` also uses a `Monitor` object: the constructor
[`Monitor()`](/api/fair/mq/shmem/Monitor/#Monitor) takes the shmId and the mode flags.
[`CatchSignals()`](/api/fair/mq/shmem/Monitor/#CatchSignals) handles `SIGINT` and `SIGTERM`, and
[`Run()`](/api/fair/mq/shmem/Monitor/#Run) runs the mode. If a monitor runs already for the shmId
and the view-only flag is `false`, the constructor throws
[`DaemonPresent`](/api/fair/mq/shmem/Monitor/DaemonPresent/).
## Related pages
- [fairmq-shmmonitor](/tools/shmmonitor/): all options and modes of the tool.
- [Sessions and segments](/shmem/sessions/): the objects of a session and their names.
- [Tune and debug](/shmem/tuning/): debug mode and the list of messages.
- [Command-line options](/reference/options/): `--shm-monitor` and `--shm-no-cleanup`.
- [Test your devices](/guides/test-devices/#clean-up-shared-memory-after-a-failed-test): clean up after a failed test.

View File

@@ -0,0 +1,296 @@
---
title: 'Unmanaged regions'
description: 'Memory that your device creates and fills. FairMQ tells you when the receivers no longer use it.'
sidebar:
order: 3
code: [fairmq/UnmanagedRegion.h, fairmq/shmem/UnmanagedRegion.h, fairmq/shmem/UnmanagedRegionImpl.h, fairmq/shmem/Manager.h, fairmq/shmem/Message.h]
---
import RegionAckExplainer from '../../../components/diagrams/RegionAckExplainer.astro';
import Snippet from '../../../components/Snippet.astro';
An unmanaged region is a block of shared memory that your device creates and fills itself. Your
device sends messages that point into the region. FairMQ calls your callback when the receivers no
longer use a part of the region, so that your device can write new data into it.
<RegionAckExplainer />
## When to use a region
With `NewMessage(size)`, the transport selects the memory for each message in the managed segment.
With a region, your code selects the memory. Use a region when the data must be at a known place.
For example, a library or a hardware driver can write into a buffer that you give it. The data then
goes to the receivers without a copy.
The region is a shared memory object `fmq_<shmId>_rg_<id>` of the session. See
[Sessions and segments](/shmem/sessions/).
## Create a region
Use [`NewUnmanagedRegionFor()`](/api/fair/mq/Device/#NewUnmanagedRegionFor) of the device. It
creates the region with the transport of a channel. The messages of the region must use the same
transport. [`NewUnmanagedRegion()`](/api/fair/mq/Device/#NewUnmanagedRegion) uses the default
transport of the device. Both give their arguments to
[`TransportFactory::CreateUnmanagedRegion()`](/api/fair/mq/TransportFactory/#CreateUnmanagedRegion-5).
The sampler of the region example creates a region of 10000000 bytes in `InitTask()`:
<Snippet file="examples/region/sampler.cxx" start="void InitTask() override" />
`CreateUnmanagedRegion()` has these overloads:
| Overload | Arguments |
| --- | --- |
| [5](/api/fair/mq/TransportFactory/#CreateUnmanagedRegion-5) | `size_t size, RegionCallback callback, RegionConfig cfg` |
| [6](/api/fair/mq/TransportFactory/#CreateUnmanagedRegion-6) | `size_t size, RegionBulkCallback bulkCallback, RegionConfig cfg` |
| [1](/api/fair/mq/TransportFactory/#CreateUnmanagedRegion), [2](/api/fair/mq/TransportFactory/#CreateUnmanagedRegion-2) | `size_t size`, a callback (default `nullptr`), `const std::string& path = ""`, `int flags = 0`, `RegionConfig cfg = RegionConfig()` |
| [3](/api/fair/mq/TransportFactory/#CreateUnmanagedRegion-3), [4](/api/fair/mq/TransportFactory/#CreateUnmanagedRegion-4) | `size_t size, int64_t userFlags`, a callback (default `nullptr`), `path`, `flags`, `cfg` |
Use the overloads 5 and 6. The overloads 1 to 4 write their argument `path` into `cfg.path` and
`flags` into `cfg.creationFlags`. The overloads 3 and 4 also write `userFlags` into `cfg.userFlags`.
These values replace the values in your `RegionConfig`.
### The region ID
Each region has an ID in the session. [`GetId()`](/api/fair/mq/UnmanagedRegion/#GetId) returns it.
Set the ID with `RegionConfig::id`. Without it, the shmem transport takes the next value of a
counter of the session. The first value is 1024.
An ID must be unique in a session. If the same transport created a region with the ID before,
`CreateUnmanagedRegion()` throws [`TransportError`](/api/fair/mq/TransportError/):
```txt
Unmanaged Region with id 10 already exists. Only unique IDs per session are allowed.
```
If another process created the region and the region exists, the transport opens it and takes
control of it. See [External regions](#external-regions).
:::caution[Do not use an ID again]
The management segment keeps the entry of a destroyed region. A new region with the ID of a
destroyed region in the same session throws `TransportError` ("has already been registered").
:::
## Callbacks
The callback tells your device that the receivers no longer use a block of the region. A block is
the memory of one message: its address, its size and its hint.
| Type | Signature | Calls |
| --- | --- | --- |
| [`RegionCallback`](/api/fair/mq/#RegionCallback) | `void(void* ptr, size_t size, void* hint)` | One call for each block. |
| [`RegionBulkCallback`](/api/fair/mq/#RegionBulkCallback) | `void(const std::vector<fair::mq::RegionBlock>& blocks)` | One call for each bunch of up to 256 blocks. |
[`RegionBlock`](/api/fair/mq/RegionBlock/) has the fields `ptr`, `size` and `hint`. The hint is the
value that you gave to `NewMessage()`. FairMQ does not use it. Use it to find the block in your own
records.
The callback runs in a [separate thread](/concepts/threads/#which-thread-runs-your-code) of the transport, the ack receiver. Protect the data that the
callback and your device share, for example with a mutex. The sampler above uses `fMtx`.
Give a callback for each region that sends messages. Without a callback, the creator does not start
an ack receiver, and nothing empties the queue of the region. When the queue is full, the ack sender
of a receiver tries again in a loop and uses CPU time.
This test creates one region with a `RegionCallback` and one with a `RegionBulkCallback`. The hints
are pointers to two `int` values:
<Snippet file="test/region/_region.cxx" start="CreateUnmanagedRegion(r1Size, [&](void* ptr" end="ptr2 = region2->GetData();" />
## The region configuration
[`RegionConfig`](/api/fair/mq/RegionConfig/) has these fields
([UnmanagedRegion.h](/source/fairmq/UnmanagedRegion.h/)). The constructor
[`RegionConfig(lock, zero)`](/api/fair/mq/RegionConfig/#RegionConfig-2) sets the first two.
| Field | Default | Effect with shmem |
| --- | --- | --- |
| [`lock`](/api/fair/mq/RegionConfig/#lock) | `false` | Locks the memory of the region in RAM with `mlock()`. If this fails, the creation throws `TransportError` ("Could not lock region"). |
| [`zero`](/api/fair/mq/RegionConfig/#zero) | `false` | Writes zeros to the region after the creation. |
| [`removeOnDestruction`](/api/fair/mq/RegionConfig/#removeOnDestruction) | `true` | The creator removes the region, its file and its reference count segment when you destroy the region object. |
| [`creationFlags`](/api/fair/mq/RegionConfig/#creationFlags) | `0` | Map options for `boost::interprocess::mapped_region` when the transport maps the region. |
| [`userFlags`](/api/fair/mq/RegionConfig/#userFlags) | `0` | Your own value. The transport does not use it. Other devices get it in `RegionInfo::flags`. |
| [`size`](/api/fair/mq/RegionConfig/#size) | `0` | Not used by `CreateUnmanagedRegion()`. The `size` argument sets the size. |
| [`rcSegmentSize`](/api/fair/mq/RegionConfig/#rcSegmentSize) | `100000000` | Size in bytes of the reference count segment `fmq_<shmId>_rrc_<id>`. See [Copies of region messages](#copies-of-region-messages). |
| [`path`](/api/fair/mq/RegionConfig/#path) | `""` | A prefix for a file. If it is not empty, a file holds the region. See [File-backed regions](#file-backed-regions). |
| [`id`](/api/fair/mq/RegionConfig/#id) | not set | The region ID. Without it, the transport selects the next ID from 1024. |
| [`linger`](/api/fair/mq/RegionConfig/#linger) | `100` | Time in ms. When you destroy the region, the creator receives acknowledgements for this time. See [Linger](#linger). |
If Boost.Interprocess cannot create or open the region, the transport writes "cannot create region.
Already created/not cleaned up?" to the log. Then it throws the Boost exception again.
## Send messages from a region
Make a message with [`NewMessageFor(channel, index, region, ptr, size, hint)`](/api/fair/mq/Device/#NewMessageFor)
or `NewMessage(region, ptr, size, hint)`. The transport does not allocate memory for the message.
The message points to `size` bytes at `ptr` in the region. The sampler of the example sends 64 parts
in each multipart message:
<Snippet file="examples/region/sampler.cxx" start="for (int i = 0; i < 64; ++i)" />
The example sends the same bytes at the start of the region in all parts. A real device must manage
the memory of its region. It can write into a block again only after the callback for that block.
Rules for region messages:
- `ptr` must point into the region. Otherwise the shmem transport throws `TransportError` ("trying to
create region message with data from outside the region").
- The transport checks only `ptr`. You must make sure that `ptr + size` is not after the end of the
region.
- The region and the message must use the same transport. Otherwise the transport throws
`TransportError` ("region type (…) does not match message type (…)").
- Do not change a block after `Send()` until its callback. The receivers read the data in place.
- Do not call [`SetUsedSize()`](/api/fair/mq/Message/#SetUsedSize) on a region message with the shmem
transport. It treats the block as a block of the managed segment. Give the correct size to
`NewMessage()` instead.
A receiver does not need to do anything special. The transport opens the region in the receiver at
the first `GetData()` of a region message, or when the receiver destroys the message.
## Acknowledgements
When the last message for a block is destroyed, the transport sends an acknowledgement to the
creator of the region ([UnmanagedRegion.h](/source/fairmq/shmem/UnmanagedRegion.h/#L350-L443)):
1. The transport puts the block into a list in the process that destroys the message. This is
usually the receiver. It is the sender if the message was not sent.
2. The ack sender thread of that process sends the list to the queue `fmq_<shmId>_rgq_<id>`. It sends
a bunch when the list holds 256 blocks. Otherwise it sends the blocks of the list every 500 ms.
3. The queue holds up to 1024 bunches.
4. The ack receiver thread of the creator reads the queue and calls the callback.
An acknowledgement can arrive up to 500 ms after the destruction of the message. Plan the size of
the region for this delay.
A receiver starts an ack sender when it opens the region. The creator starts an ack sender and an
ack receiver when you give a callback.
## Region events
A device can learn when regions and managed segments of the session are created and destroyed. Call
[`SubscribeToRegionEvents()`](/api/fair/mq/TransportFactory/#SubscribeToRegionEvents) on the
transport. The sampler logs all events:
<Snippet file="examples/region/sampler.cxx" start="GetChannel(fChanName, 0).Transport()->SubscribeToRegionEvents" />
The callback gets a [`RegionInfo`](/api/fair/mq/RegionInfo/):
| Field | Content |
| --- | --- |
| `managed` | `true` for a managed segment, `false` for a region. |
| `id` | The ID of the segment or the region. |
| `ptr`, `size` | The address in this process and the size. For a destroyed region: `nullptr` and `0`. |
| `flags` | The `userFlags` of the creator of the region. |
| `event` | [`RegionEvent`](/api/fair/mq/RegionEvent/): `created`, `destroyed` or `local_only`. |
Behavior of the shmem transport:
- The callback runs in a separate thread. The transport checks for changes every 50 ms.
- At the start, the callback gets a `created` event for each segment and region that exists.
- A region gives a `destroyed` event only when the creator removes it (`removeOnDestruction` is
`true`).
- If a region is created and destroyed between two checks, the callback gets no event for it.
- To give the address in this process, the transport opens each region of the session.
- A new subscription replaces the old one.
Call [`UnsubscribeFromRegionEvents()`](/api/fair/mq/TransportFactory/#UnsubscribeFromRegionEvents)
before the transport is destroyed, for example in `ResetTask()`.
[`SubscribedToRegionEvents()`](/api/fair/mq/TransportFactory/#SubscribedToRegionEvents) tells if a
subscription is active. [`GetRegionInfo()`](/api/fair/mq/TransportFactory/#GetRegionInfo) returns the
current list of `RegionInfo` at once.
## File-backed regions
Set `RegionConfig::path` to put the region into a file. The path is a prefix of the file name. The
creator creates the file `<path>fmq_<shmId>_rg_<id>` with the size of the region and maps it. For
example, the path `/tmp/` gives `/tmp/fmq_eca859e3_rg_1024`. End the path with `/` to use a
directory.
When the creator destroys the region and `removeOnDestruction` is `true`, it removes the file.
:::caution[File-backed regions stay in one transport]
The creator does not register a file-backed region in the management segment. Devices in other
processes cannot open the region: `GetData()` of a received message returns `nullptr`.
`fairmq-shmmonitor` does not show the region and does not remove the file.
:::
## External regions
A separate program can create a region before the devices start, for example with
`fair::mq::shmem::UnmanagedRegion` (see
[Create segments before the devices start](/shmem/sessions/#create-segments-before-the-devices-start)).
A device then gets control of the region:
1. Set `RegionConfig::id` to the ID of the existing region.
2. Set `removeOnDestruction` to `false`, so that the device does not remove the region.
3. Give the size of the existing region to `CreateUnmanagedRegion()`. If the size is different and
not 0, the transport throws `TransportError` ("Created/opened region size … does not match
configured size").
4. Start the devices with the same session or `--shmid`, and with `--shm-no-cleanup true`. Do not
use `--shm-monitor true`. The monitor removes the memory when the devices stop. See
[Monitor and clean up](/shmem/monitor/#automatic-cleanup-with---shm-monitor).
The sampler does this with `--external-region true`:
<Snippet file="examples/region/sampler.cxx" start="fair::mq::RegionConfig regionCfg;" end="regionCfg.rcSegmentSize" />
The opened region uses the `rcSegmentSize` of its creator. The start script
`fairmq-start-ex-region-advanced-external.sh` runs this setup. See the
[region example](/examples/region/).
## Copies of region messages
[`Copy()`](/api/fair/mq/Message/#Copy) of a region message does not copy the data. The copy and the
original share a reference count. The transport sends the acknowledgement when the last of them is
destroyed. The processor of the example sends each part on two channels:
<Snippet file="examples/region/processor.cxx" start="for (const auto& inPart : inParts)" />
The shared reference count is in the reference count segment `fmq_<shmId>_rrc_<id>` of the region.
Its size is `rcSegmentSize`.
- If the segment is full, `Copy()` throws [`RefCountBadAlloc`](/api/fair/mq/RefCountBadAlloc/)
("Insufficient space in the reference count segment …").
- With `rcSegmentSize = 0`, the transport does not create the segment. `Copy()` then puts the
reference count into the managed segment of the device that makes the copy.
## Linger
When you destroy the region object, the creator stops the acknowledgement threads. The ack receiver
reads the queue for `linger` ms more (default 100 ms) and calls the callback for these blocks. Then
it stops. Acknowledgements that come later do not reach the callback.
Set the time with `RegionConfig::linger`, or with
[`SetLinger()`](/api/fair/mq/UnmanagedRegion/#SetLinger) on the region. The test of the region
example uses `--region-linger 500`.
The callback can run while you destroy the region. All objects that the callback uses must stay
valid until the region is destroyed. This test checks that a callback can call the transport at
this time:
<Snippet file="test/region/_region.cxx" start="void RegionCallbackCallsTransportDuringDestruction(" />
Destroy the region in `ResetTask()` at the latest, before the device destroys its transports. The
sampler calls `fRegion.reset()` there.
## Regions with the zeromq transport
The zeromq transport has the same interface, with a different behavior:
- The region is normal memory of the process (`malloc()`). A failure of `lock` writes an error to
the log, but does not throw.
- A region message copies the data into a ZeroMQ message. The transport calls the callback at once,
in `NewMessage()`.
- `path`, `creationFlags`, `id`, `removeOnDestruction` and `rcSegmentSize` have no effect. The IDs
start at 1 for each transport.
- `linger` has no effect. `GetLinger()` returns 0.
- The event callback first gets one event `local_only`. Then it gets the events of the regions of
this transport only.
## Related pages
- [How shared memory works](/shmem/how-it-works/): messages in the managed segment.
- [Sessions and segments](/shmem/sessions/): the names of the region objects.
- [Out-of-band buffers](/shmem/side-channel/): send a reference to a region block on your own channel.
- [Region example](/examples/region/): the sampler, processor and sink of this page.
- [Messages and multipart](/concepts/messages/): the message interface.

View File

@@ -0,0 +1,247 @@
---
title: 'Sessions and segments'
description: 'Sessions, managed segments, and the names of the shared memory objects.'
sidebar:
order: 2
code: [fairmq/shmem/Common.h, fairmq/shmem/Common.cxx, fairmq/shmem/Manager.h, fairmq/shmem/Segment.h]
---
import SessionMap from '../../../components/diagrams/SessionMap.astro';
import Snippet from '../../../components/Snippet.astro';
A session is a group of devices that use the same shared memory. The session name and the user ID
give the shmId. The shmId is part of the name of each shared memory object of the session.
<SessionMap />
## The session name
Each device has the option `--session` (default `default`). All devices of a topology that use the
shmem transport must have the same session name. They must also run on the same host and as the
same user.
```sh
fairmq-ex-1-1-sampler --id sampler1 --transport shmem --session run42 --rate 1 \
--channel-config name=data,type=push,method=bind,address=ipc:///tmp/fmq-run42-data
fairmq-ex-1-1-sink --id sink1 --transport shmem --session run42 \
--channel-config name=data,type=pull,method=connect,address=ipc:///tmp/fmq-run42-data
```
The device reads the session name when it creates its shmem transport. This occurs in the state
`INITIALIZING DEVICE`. See [Device states](/concepts/states/).
## The shmId
The transport does not use the session name in the object names. It makes a short ID, the shmId
([Common.cxx](/source/fairmq/shmem/Common.cxx/#L22-L53)):
1. Write the effective user ID of the process as a decimal number, for example `1000`.
2. Append the session name: `1000default`.
3. Calculate the SHA-256 hash of this string.
4. Write the first 4 bytes of the hash as 8 hexadecimal digits: `eca859e3`.
The shmId has only 8 characters, because some systems (for example macOS) limit the length of
the names. The device writes the shmId to the log at the severity `debug`:
```txt
Generated shmid 'eca859e3' out of session id 'default'.
```
To get the shmId of a session without a device, use [`fairmq-shmmonitor`](/tools/shmmonitor/):
```sh
fairmq-shmmonitor --get-shmid --session default
fairmq-shmmonitor --get-shmid --session default --user-id 1001
```
The output contains the shmId:
```txt
shmem id for session 'default' and current user id 1000 is: eca859e3
shmem id for session 'default' and user id 1001 is: 293bdc57
```
In C++ code, use [`fair::mq::shmem::makeShmIdStr(sessionName)`](/api/fair/mq/shmem/#makeShmIdStr-2)
from `<fairmq/shmem/Common.h>`. An [overload](/api/fair/mq/shmem/#makeShmIdStr) takes the user ID as
a second string argument.
### Set the shmId directly
The option `--shmid` sets the shmId directly. It is marked as experimental. The value is an unsigned
64-bit integer in decimal notation. The device writes it as a hexadecimal number with at least 8
digits: `--shmid 1` gives the shmId `00000001`. The session name then has no effect on the object
names.
The `--shmid` option of `fairmq-shmmonitor` is a string. Give it the hexadecimal form:
```sh
fairmq-shmmonitor --shmid 00000001
```
The example [`region-advanced-external`](/examples/region/) uses `--shmid 1` for all devices, so
that a separate program can create the memory before the devices start.
## The shared memory objects
The function [`MakeShmName()`](/api/fair/mq/shmem/#MakeShmName) makes all names from the shmId
([Common.h](/source/fairmq/shmem/Common.h/#L48-L54)). On Linux, Boost.Interprocess keeps each object
as a file in `/dev/shm`.
| Name | Object | Created by | Content |
| --- | --- | --- | --- |
| `fmq_<shmId>_mng` | Management segment, 6553600 bytes (6.25 MiB) | The first shmem transport of the session | Data that all devices share. See the next section. |
| `fmq_<shmId>_m_<id>` | Managed segment, default 2 GiB | The first device with `--shm-segment-id <id>` | The blocks of the messages. |
| `fmq_<shmId>_rg_<id>` | Unmanaged region | The device that creates the region | The data of the region. |
| `fmq_<shmId>_rgq_<id>` | Message queue | The creator of the region, or the first device that uses it | The acknowledgements of region blocks. |
| `fmq_<shmId>_rrc_<id>` | Reference count segment, `rcSegmentSize` bytes (default 100000000) | The creator of the region, if `rcSegmentSize` is not 0 | The reference counts of copied region messages. |
| `sem.fmq_<shmId>_ms` | Named mutex | `fairmq-shmmonitor` in the monitor mode or the interactive mode, without `-v` | Shows that a monitor runs for the session. |
A region with a file path is a file at `<path>fmq_<shmId>_rg_<id>`, not an object in `/dev/shm`. See
[Unmanaged regions](/shmem/regions/#file-backed-regions).
### The management segment
The first shmem transport of a session creates `fmq_<shmId>_mng`. All other transports open it. It
holds:
- The session info: the session name and the user ID of the creator.
- The device counter. See [The device counter and cleanup](#the-device-counter-and-cleanup).
- The heartbeat. Each transport increments it every 100 ms. The monitor uses it.
- The list of the managed segments, with their allocation algorithms.
- The list of the regions, with their path, flags, size, reference count segment size and a flag
`destroyed`.
- The event counter, the region counter and a mutex.
- In debug mode: the list of the messages and the message counters. See
[Tune and debug](/shmem/tuning/#debug-mode).
## Managed segments
Each device creates its messages in one managed segment. The option `--shm-segment-id` selects it
(default `0`). The option is marked as experimental.
- The first device with a segment ID creates the segment. It uses its `--shm-segment-size` and its
`--shm-allocation`. Then it registers the segment in the management segment.
- The other devices with this ID open the segment. Boost.Interprocess opens an existing segment with
its size and ignores the `--shm-segment-size` of the device, so the sizes do not have to match.
- If the allocation algorithm of a device is different, the device writes a warning and uses the
algorithm of the segment.
- A device can receive messages from all segments of the session. It opens a segment when it first
uses a message from that segment, for example in `GetData()`.
The device writes the result to the log at the severity `debug`, with the real size:
```txt
Created managed shared memory segment fmq_eca859e3_m_0. Size: 2147483648 bytes. Available: <free> bytes. Allocation algorithm: rbtree_best_fit
```
The warning for a different allocation algorithm is:
```txt
Allocation algorithm of the opened segment is rbtree_best_fit, but requested is simple_seq_fit. Ignoring requested setting.
```
Use several segments to separate groups of devices. The start script
`fairmq-start-ex-region-advanced.sh` gives `processor1` and its sinks the segment 1, and `processor2`
the segment 2. The messages of one group then do not use the memory of the other group.
### Create segments before the devices start
A separate program can create the segments and regions of a session before the devices start.
[`fair::mq::shmem::Segment`](/api/fair/mq/shmem/Segment/) creates or opens a managed segment and
registers it. [`Lock()`](/api/fair/mq/shmem/Segment/#Lock) locks its memory in RAM, and
[`Zero()`](/api/fair/mq/shmem/Segment/#Zero) writes zeros to its free memory. This test creates two
segments and two regions:
<Snippet file="test/region/_creation.cxx" start="void Preallocate()" />
The devices then open these objects. Start the devices with `--shm-no-cleanup true` if the objects
must stay after the devices stop.
## The device counter and cleanup
The device counter in the management segment counts the shmem transports of the session. In normal
use, each device has one shmem transport.
1. A new transport increments the counter.
2. When the device destroys the transport, the transport decrements the counter. The device does
this in the state `RESETTING DEVICE`.
3. When the counter is 0, the last transport removes all objects of the session
([Manager.h](/source/fairmq/shmem/Manager.h/#L773-L798)): the regions, their queues and
reference count segments, the managed segments and the management segment.
The last transport does not remove `sem.fmq_<shmId>_ms`. The monitor owns this mutex.
With `--shm-no-cleanup true`, the last transport does not remove the objects. You must remove them
yourself. If a device crashes, it does not decrement the counter. Then the counter does not reach 0,
and the objects stay. See [Monitor and clean up](/shmem/monitor/).
The log messages at the severity `debug` show the decision:
```txt
Other segment users present (2), skipping removal.
Last segment user, removing segment.
Last segment user, skipping removal (--shm-no-cleanup is true).
```
## Keep two topologies apart
Two topologies on the same host must use different session names. Each session then has its own
objects, and the devices of one session do not see the memory of the other.
- Give each run a unique session name. The tests of the examples use the output of
[`fairmq-uuid-gen -h`](/reference/tools/#fairmq-uuid-gen), a hash of a new UUID.
[Test your devices](/guides/test-devices/) shows a test script that does this.
- Do not connect the channels of two different sessions. The `MetaHeader` does not contain the
session. The receiver looks up the segment ID and the handle in its own session. This gives wrong
data or an error.
If a receiver cannot find a region of a message, it writes an error to the log:
```txt
Could not get remote region with id '1024'. Does the region creator run with the same session id?
```
## Users and permissions
The user ID is part of the hash. Two users with the same session name get two different shmIds, so
their devices do not share memory. A device cannot open the session of another user with
`--session`.
To find the shmId of a session of another user, give the user ID to `fairmq-shmmonitor`:
`fairmq-shmmonitor --get-shmid --session <name> --user-id <id>`.
## Containers
Devices of one session can run in different containers on the same host. Three conditions apply:
1. **The same `/dev/shm`.** The objects of the session are files in `/dev/shm` (see
[The shared memory objects](#the-shared-memory-objects)). All containers must see the same
files. With Docker, `--ipc=host` gives a container the IPC namespace and the `/dev/shm` of the
host. `--ipc=shareable` on one container and `--ipc=container:<name>` on the others give all of
them the IPC namespace and the `/dev/shm` of the first container. This is Docker behavior.
2. **The same effective user ID.** The shmId is the hash of the effective user ID and the session
name ([Common.cxx](/source/fairmq/shmem/Common.cxx/#L32-L35)). Two images often run as different
users, for example `root` (0) and `1000`. Then the devices get different shmIds with the same
session name and do not share memory. Give the containers the same user, for example with
`docker run --user 1000`.
3. **An endpoint that both sides reach.** The shmem transport sends the metadata through ZeroMQ
sockets. Use a `tcp://` address on the network of the containers, or an `ipc://` file in a
directory that both containers mount.
To check the second condition, run `fairmq-shmmonitor --get-shmid --session <name>` in each
container. The two outputs must show the same shmId. Devices with different shmIds do not see an
error at the start. Their transfers give wrong data or errors, as for
[two sessions](#keep-two-topologies-apart).
The size of `/dev/shm` in a container is often small. Docker gives a container 64 MB by default.
With `--ipc=container:<name>`, the size is that of the first container, and with `--ipc=host`, that
of the host. This is Docker behavior. All segments and regions of the session must fit into it. See
[Space in /dev/shm](/shmem/tuning/#space-in-devshm).
## Related pages
- [How shared memory works](/shmem/how-it-works/): the path of one message.
- [Unmanaged regions](/shmem/regions/): the region objects of a session.
- [Monitor and clean up](/shmem/monitor/): find and remove the objects of a session.
- [fairmq-shmmonitor](/tools/shmmonitor/): all options of the monitor.
- [Command-line options](/reference/options/): `--session` and the shared memory options.

View File

@@ -0,0 +1,157 @@
---
title: 'Out-of-band buffers'
description: 'Send a reference to a shmem buffer through your own channel with the side-channel metadata API.'
sidebar:
order: 5
code: [fairmq/shmem/Common.h, fairmq/shmem/Message.h, fairmq/shmem/Manager.h, fairmq/shmem/Manager.cxx, fairmq/shmem/TransportFactory.h]
since: v1.11
---
import Snippet from '../../../components/Snippet.astro';
import { Steps } from '@astrojs/starlight/components';
The side-channel API gives the metadata of a shmem message to your code. Your code sends this
metadata in its own format. A device of the same session then gets the address of the data, without
a FairMQ receive.
## The use case
`Send()` gives the block of a message to one receiver. Some applications need a different model:
- A producer device creates shmem messages and keeps them. It does not send them.
- It writes the metadata of each message into its own data, for example into a table, and sends this
data on a normal channel.
- Consumer devices read the payloads in place, in shared memory. They do not own the blocks.
The `MetaHeader` is the metadata that the shmem transport sends for each message. See
[How shared memory works](/shmem/how-it-works/#send-a-message). The side-channel API exposes it
since FairMQ v1.11.
## The API
| Function | Header | What it does |
| --- | --- | --- |
| [`shmem::Message::GetMeta()`](/api/fair/mq/shmem/Message/#GetMeta) | `<fairmq/shmem/Message.h>` | Returns the [`MetaHeader`](/api/fair/mq/shmem/MetaHeader/) of a shmem message. |
| [`shmem::GetDataAddressFromHandle(TransportFactory&, const MetaHeader&)`](/api/fair/mq/shmem/#GetDataAddressFromHandle) | `<fairmq/shmem/Common.h>` | Returns the address of the data in this process as `char*` ([Common.h](/source/fairmq/shmem/Common.h/#L345-L348)). |
| [`shmem::TransportFactory::GetDataAddressFromHandle()`](/api/fair/mq/shmem/TransportFactory/#GetDataAddressFromHandle) | `<fairmq/shmem/TransportFactory.h>` | The same, for code that has the shmem transport type. |
The free function takes the interface `fair::mq::TransportFactory`. It needs only `Common.h`, so
your code does not include `Socket.h` or `zmq.h` for it.
`GetDataAddressFromHandle()` uses the transport that you give:
- For a message in a managed segment, it opens the segment if necessary. It returns the address of
the payload.
- For a message in a region, it opens the region if necessary. It returns the start of the region
plus the handle.
- For a message in a managed segment with the size 0, it returns `nullptr`.
It throws [`SharedMemoryError`](/api/fair/mq/shmem/SharedMemoryError/) in these cases:
| Cause | Text |
| --- | --- |
| The transport is not shmem. | `GetDataAddressFromHandle called on a non-shmem transport` |
| The segment ID is not in the session. | `GetDataAddressFromHandle: cannot open segment with id <id>` |
| The region ID is not in the session. | `GetDataAddressFromHandle: cannot get unmanaged region with id <id>` |
## Send a reference, step by step
<Steps>
1. In the producer, create a message with the shmem transport and write the payload.
2. Make sure that it is a shmem message: `msg->GetType()` must be `fair::mq::Transport::SHM`.
3. Get the metadata: `static_cast<const fair::mq::shmem::Message&>(*msg).GetMeta()`.
4. Keep the message in the producer. Do not send it, and do not destroy it.
5. Send the `MetaHeader` on your own channel. You can send the 40 bytes or the seven fields.
6. In the consumer, make the `MetaHeader` again from the bytes or the fields.
7. Call `fair::mq::shmem::GetDataAddressFromHandle()` with a shmem transport of the same session.
8. Read `meta.fSize` bytes at the address.
9. Tell the producer on your own channel when the consumer no longer needs the data. Then the
producer destroys the message.
</Steps>
This sample sends the 40 bytes of the `MetaHeader` in a message on the channel `meta`. Both devices
run with `--transport shmem` and the same session:
```cpp title="producer"
#include <fairmq/shmem/Message.h>
#include <cstring>
auto msg = NewMessage(size);
// write the payload into msg->GetData()
const fair::mq::shmem::MetaHeader meta = static_cast<const fair::mq::shmem::Message&>(*msg).GetMeta();
auto metaMsg = NewMessageFor("meta", 0, sizeof(meta));
std::memcpy(metaMsg->GetData(), &meta, sizeof(meta));
Send(metaMsg, "meta");
fCache.push_back(std::move(msg)); // the producer keeps the buffer
```
```cpp title="consumer"
#include <fairmq/shmem/Common.h>
#include <cstring>
auto metaMsg = NewMessageFor("meta", 0);
if (Receive(metaMsg, "meta") > 0) {
fair::mq::shmem::MetaHeader meta{};
std::memcpy(&meta, metaMsg->GetData(), sizeof(meta));
char* data = fair::mq::shmem::GetDataAddressFromHandle(*Transport(), meta);
// read meta.fSize bytes at data
}
```
`fCache` is a member of the producer, for example a `std::vector<fair::mq::MessagePtr>`.
### The tests
This test makes the round trip for a message in a managed segment. The consumer uses a second
transport of the same session, as a second device does:
<Snippet file="test/message/_message.cxx" start="auto SideChannel(bool" />
The same for a message in a region:
<Snippet file="test/message/_message.cxx" start="auto SideChannelUnmanaged()" />
This test shows the errors:
<Snippet file="test/message/_message.cxx" start="auto SideChannelErrors()" />
## Lifetime rules
FairMQ does not count the consumers of an out-of-band buffer. The comment in `Common.h` says: the
caller must keep the buffer alive, and FairMQ gives no reference count protection for this path.
- The producer must keep the message while a consumer uses the address.
- When the producer destroys the message, the transport frees the block, or it sends the
acknowledgement for a region block. After that, the address is not valid.
- Use the API for messages that you do not send. After `Send()`, the receiver owns the block.
- The address is valid only in the process that called `GetDataAddressFromHandle()`. Do not send it
to other processes.
- The consumer must keep its transport while it uses the address. The transport holds the mapping of
the segment or region.
- Do not write into the data in a consumer. Other consumers can read it at the same time.
- The producer and the consumers must use the same session, on the same host. See
[Sessions and segments](/shmem/sessions/).
The fields of the `MetaHeader` are in a fixed order: `fSize`, `fHint`, `fHandle`, `fShared`,
`fRegionId`, `fSegmentId`, `fManaged`. Code can make a `MetaHeader` with aggregate initialization in
this order. The tests `Footprint` and `MetaHeaderLayout` check the size of 40 bytes and the offsets
on 64-bit systems.
## Related pages
- [How shared memory works](/shmem/how-it-works/): the `MetaHeader` in a normal send.
- [Unmanaged regions](/shmem/regions/): blocks that the producer manages itself.
- [Sessions and segments](/shmem/sessions/): the session of the producer and the consumers.
- [Messages and multipart](/concepts/messages/): the message interface.

View File

@@ -0,0 +1,264 @@
---
title: 'Tune and debug'
description: 'Segment size, allocation algorithm, memory locking, bad allocations and debug output.'
sidebar:
order: 6
code: [fairmq/shmem/Manager.h, fairmq/shmem/TransportFactory.h, fairmq/shmem/Common.h, fairmq/shmem/Socket.h, fairmq/plugins/config/Config.cxx]
---
import Snippet from '../../../components/Snippet.astro';
import OptionsTable from '../../../components/OptionsTable.astro';
The shmem transport has options for the size and the behavior of the managed segment. This page
tells you how to set them, what occurs when the segment is full, and how to find messages that use
the memory.
## Set the segment size
`--shm-segment-size` sets the size of the managed segment in bytes. The default is 2147483648
(2 GiB). Only the device that creates the segment sets its size. Boost.Interprocess opens an existing
segment with its size, so the value of the other devices has no effect. See
[Managed segments](/shmem/sessions/#managed-segments).
The segment must hold all messages that exist at the same time:
- The messages that your devices hold.
- The messages in the queues of the sockets. Each queue holds up to `sndBufSize` or `rcvBufSize`
ZeroMQ messages (default 1000). A multipart message counts as one.
- The messages in the kernel buffers of the sockets.
Each block needs more memory than the payload. The block also holds a header of 8 bytes and space
for the alignment ([Common.h](/source/fairmq/shmem/Common.h/#L103-L136)).
To check the free memory, use `fairmq-shmmonitor --session <name>`, or
[`Monitor::GetFreeMemory()`](/api/fair/mq/shmem/Monitor/#GetFreeMemory) in code. See
[Monitor and clean up](/shmem/monitor/#find-the-shared-memory).
### Space in /dev/shm
On Linux, each object of a session, except a file-backed region, is a file in `/dev/shm`. This is
a `tmpfs` file system with a size limit. FairMQ creates the segment with `open_or_create` and does
not check the free space of `/dev/shm` ([Manager.h](/source/fairmq/shmem/Manager.h/#L158-L178)).
Thus `/dev/shm` must hold all objects of all sessions on the host:
- the management segment of each session, 6553600 bytes (6.25 MiB),
- each managed segment, by default 2 GiB,
- each region, its acknowledgement queue (1024 messages of 256 blocks, more than 6 MiB) and its
reference count segment (`rcSegmentSize`, default 100000000 bytes).
Use `df -h /dev/shm` to see the size and the free space. Old sessions that stay after a crash also
use this space. See [Monitor and clean up](/shmem/monitor/).
A container often has a small `/dev/shm`. Docker gives a container 64 MB by default (Docker
behavior). The default segment of 2 GiB then does not fit. Give the container more space, for
example with `docker run --shm-size=4g`, or set a smaller `--shm-segment-size`. With `--ipc=host`,
the container uses the `/dev/shm` of the host (Docker behavior).
[Containers](/shmem/sessions/#containers) tells how devices in different containers share a
session.
What occurs when `/dev/shm` is too small depends on the Boost version (Boost.Interprocess behavior):
- From Boost 1.76, Boost reserves the full size with `posix_fallocate()` when it creates the
segment. Each segment uses its full size in `/dev/shm` from the start. If the space is not
available, the transport throws, and the device goes to the state `ERROR`. From Boost 1.79, the
text ends with the reason of the system, for example
`Could not initialize shared memory transport: Failed to create/open shared memory segment 'fmq_eca859e3_m_0': No space left on device`.
Boost 1.76 to 1.78 read the reason from `errno`, which `posix_fallocate()` does not set. Then the
reason in the text can be wrong.
- Older versions only set the size of the file. Linux gives a page of the file when a process first
uses the page. If `tmpfs` has no free page, the process gets the signal `SIGBUS` and crashes
(Linux behavior). This can occur long after the start, when the segment fills.
With an older Boost, two kinds of options show the problem at the start, and not later in the run:
- `--shm-zero-segment` and `--shm-zero-segment-on-creation` write to all free pages of the segment
when the device opens or creates it. The device then crashes with `SIGBUS` at once.
- `--shm-mlock-segment` and `--shm-mlock-segment-on-creation` load all pages into RAM. If `tmpfs`
cannot give the pages, `mlock()` fails with "Cannot allocate memory" (Linux behavior). This is
the same text as for a too small `RLIMIT_MEMLOCK`.
## Select the allocation algorithm
`--shm-allocation` selects the allocation algorithm of Boost.Interprocess for the segment:
`rbtree_best_fit` (default) or `simple_seq_fit`. Another value throws
[`SharedMemoryError`](/api/fair/mq/shmem/SharedMemoryError/) when the device creates the transport:
```txt
Provided shared memory allocation algorithm 'best_fit' is not supported. Supported are 'rbtree_best_fit'/'simple_seq_fit'
```
The device that creates the segment sets the algorithm. If another device asks for a different
algorithm, it writes a warning and uses the algorithm of the segment.
## Lock and zero the segment
| Option | Default | Effect |
| --- | --- | --- |
| `--shm-mlock-segment` | `false` | Locks the segment in RAM with `mlock()` after the device opens or creates it. |
| `--shm-mlock-segment-on-creation` | `false` | Locks the segment only in the device that creates it. |
| `--shm-zero-segment` | `false` | Writes zeros to the free memory of the segment after the device opens or creates it. |
| `--shm-zero-segment-on-creation` | `false` | Writes zeros only in the device that creates it. |
For a region, use the fields `lock` and `zero` of `RegionConfig`. See
[Unmanaged regions](/shmem/regions/#the-region-configuration).
`mlock()` needs a large enough limit for locked memory (`RLIMIT_MEMLOCK`). If the limit is too
small, the device cannot create its transport. The error is:
```txt
Could not initialize shared memory transport: Could not lock the managed segment memory: Cannot allocate memory
```
Increase the limit for the shell that starts the devices. The CI of FairMQ does this before the
tests:
```sh
sudo prlimit --pid $$ --memlock=unlimited:unlimited
```
## Handle a full segment
If a message does not fit into the free memory of the segment, `NewMessage()` throws
[`MessageBadAlloc`](/api/fair/mq/MessageBadAlloc/). Three options change this behavior
([Manager.h](/source/fairmq/shmem/Manager.h/#L694-L748)):
| Option | Default | Effect |
| --- | --- | --- |
| `--shm-throw-bad-alloc` | `true` | `false`: try again until the allocation is successful. `--bad-alloc-max-attempts` then has no effect. |
| `--bad-alloc-max-attempts` | not set (1 attempt) | Number of attempts before `MessageBadAlloc`. `-1`: no limit. `0` has the same effect as `1`. |
| `--bad-alloc-attempt-interval` | `50` | Time between two attempts in ms. |
The text of the exception gives the free memory. For example:
```txt
shmem: could not create a message of size 100000, alignment: 16, free memory: 31984
```
With more than one attempt, the transport writes a warning after the first failure. For example,
with `--bad-alloc-max-attempts 4`: "… Will try 3 more times, in 50ms intervals". With no limit, it
writes no warning.
A state change of the device stops the wait. On each transition, the device interrupts its
transports, and `NewMessage()` throws `MessageBadAlloc`.
A message that is larger than the segment throws `MessageBadAlloc` at once, without more attempts.
For example, a message of 2000000 bytes in a segment of 1000000 bytes gives:
```txt
Requested message size (2000024) exceeds segment size (1000000)
```
The size in this text includes the header and the alignment. This test sets 4 attempts with 20 ms
between them:
<Snippet file="test/transport/_shm_allocation.cxx" start="TEST_P(ShmAllocation, MaxAttempts)" />
## Alignment
The payload of a shmem message starts at an address that is a multiple of
`alignof(std::max_align_t)`. To get a larger alignment, give an
[`Alignment`](/api/fair/mq/Alignment/) to `NewMessage()` or `Rebuild()`:
```cpp
auto msg = NewMessageFor("data", 0, size, fair::mq::Alignment{64});
```
The receiver gets the block that the sender allocated. With the shmem transport, the alignment of
an empty message for `Receive()` has no effect. The test `RunPushPullWithAlignment` checks an
alignment of 64 bytes for the sent and the received message.
## Set the size of the metadata message
For each send, the shmem transport sends one ZeroMQ message with the metadata: 40 bytes for a
single message, or 8 bytes plus 40 bytes for each part. `--shm-metadata-msg-size` makes this
message larger (default `0`). The transport fills the message with padding up to this size. A value
below the minimum gives the minimum ([Socket.h](/source/fairmq/shmem/Socket.h/#L135-L137)).
The queues of the sockets count ZeroMQ messages, and the kernel buffers of the sockets count bytes.
Small metadata messages fill the kernel buffers slowly, so more messages can wait in them. With
larger metadata messages, the kernel buffers hold fewer messages, and small values of `sndBufSize`
and `rcvBufSize` limit the number of messages more accurately. The option is available since FairMQ
v1.6.
The receiver reads the metadata from the start of the message, so the two ends do not need the same
value. Many tests run the shmem transport also with a metadata size of 2048 bytes.
## Debug mode
Compile FairMQ with the CMake option `FAIRMQ_DEBUG_MODE=ON` (default `OFF`) to get information about
the messages in shared memory. The CMake files give this definition to the FairMQ library, to
`fairmq-shmmonitor` and, as a public definition, to the targets that link FairMQ.
```sh
cmake -S . -B build -DFAIRMQ_DEBUG_MODE=ON
```
In debug mode, the shmem transport does these things:
- It records each message in the management segment: the segment, the offset, the size, the
process ID of the creator and the time of the creation.
- It counts the messages of each segment. The status of `fairmq-shmmonitor` shows the count in
`msgs`.
- When the device resets, it checks that the device destroyed all its messages.
Each allocation and each deallocation locks a mutex of the session for the record. The CMake option
says that debug mode can decrease the performance.
To see the messages, use `fairmq-shmmonitor --debug --session <name>`, or the key `b` in the
interactive mode. The output has this form (example values):
```txt
found 2 messages.
segment: 0, offset: 1072, size: 100, creator PID: 4711, at: 10:15:02.123456
segment: 0, offset: 1200, size: 200, creator PID: 4711, at: 10:15:02.123789
```
Without debug mode, the tool prints "FairMQ was not compiled in debug mode (FAIRMQ_DEBUG_MODE)".
The six digits after the seconds are not the fraction of the second: the code prints the
nanoseconds of the time stamp modulo 1000000.
### The message check at reset
In the state `RESETTING DEVICE`, the shmem transport compares the number of created and destroyed
message objects. If they are not equal, it throws [`MessageError`](/api/fair/mq/MessageError/), and
the device goes to the state `ERROR`:
```txt
Message counter during Reset expected to be 0, found: 3
```
Destroy all messages in `ResetTask()` at the latest. See [Device states](/concepts/states/).
:::caution[False errors after Rebuild() or Copy()]
Each call of `Rebuild()` counts one more destroyed message. `Copy()` does the same when the target
message holds a block or the source message is empty. The check can then fail, also when all
messages are destroyed.
:::
## Problems
| Message | Cause | What to do |
| --- | --- | --- |
| `MessageBadAlloc`: "Requested message size (…) exceeds segment size (…)" | The message is larger than the segment. | Increase `--shm-segment-size` of the device that creates the segment, or send smaller messages. |
| `MessageBadAlloc`: "shmem: could not create a message of size …" | The segment is full. | Increase the segment. Destroy messages earlier. Use `--bad-alloc-max-attempts`. |
| "Could not lock the managed segment memory: Cannot allocate memory" | The limit for locked memory is too small, or `/dev/shm` cannot give the pages. | Increase `RLIMIT_MEMLOCK`, or do not lock the segment. Check the free space of `/dev/shm`. |
| "Failed to create/open shared memory segment '…': No space left on device", or the device crashes with `SIGBUS` | `/dev/shm` has less free space than the segment, for example in a container. See [Space in /dev/shm](#space-in-devshm). | Give `/dev/shm` more space (Docker: `--shm-size`), or decrease `--shm-segment-size`. Remove old sessions with `fairmq-shmmonitor --cleanup`. |
| The segment has a different size than `--shm-segment-size`. | Another device created the segment, or old memory of the session exists. | Use the same value on all devices. Remove old memory with `fairmq-shmmonitor --cleanup`. |
| "Allocation algorithm of the opened segment is …, but requested is …" | The segment exists with another algorithm. | Use the same `--shm-allocation` on all devices. |
| `SocketError`: "Received message is not a valid FairMQ shared memory message" | The peer uses the zeromq transport. | Use the same transport on both ends of the channel. |
| `MessageError`: "Message counter during Reset expected to be 0, found: …" | Debug mode. Messages exist at the reset. | Destroy the messages in `ResetTask()`. |
## All shared memory options
<OptionsTable groups={['Shared memory']} id="shm" />
The option `--session` is in the group `Device`. See [Command-line options](/reference/options/).
## Related pages
- [Sessions and segments](/shmem/sessions/): who creates a segment and sets its size.
- [Monitor and clean up](/shmem/monitor/): free memory, the status of a session.
- [Unmanaged regions](/shmem/regions/): `lock`, `zero` and `rcSegmentSize` of a region.
- [Handle errors and timeouts](/guides/errors-timeouts/): exceptions and transfer codes.
- [CMake options and variables](/reference/cmake/): `FAIRMQ_DEBUG_MODE`.
- [Run a benchmark](/guides/benchmark/): measure the effect of the options on the throughput.

View File

@@ -0,0 +1,288 @@
---
title: Use FairMQ in a CMake project
description: 'Find an installed FairMQ with find_package(), link your programs to FairMQ::FairMQ, and use the variables and functions of the package.'
sidebar:
order: 4
---
import { FileTree } from '@astrojs/starlight/components';
FairMQ installs a CMake package. Your project finds it with `find_package(FairMQ)` and links its programs to the imported target `FairMQ::FairMQ`. This page shows a complete project, the targets and the variables of the package, and the problems that can occur.
## A minimal project
This project builds one device program. Make a folder with two files:
<FileTree>
- hello/
- CMakeLists.txt
- hello.cxx
</FileTree>
```cmake title="CMakeLists.txt"
cmake_minimum_required(VERSION 3.15)
project(Hello LANGUAGES CXX)
find_package(FairMQ 1.11 REQUIRED)
# FairMQConfig.cmake does not find the dependencies of FairMQ. Find them here.
foreach(dep IN LISTS FairMQ_PACKAGE_DEPENDENCIES)
find_package(${dep} ${FairMQ_${dep}_VERSION} REQUIRED COMPONENTS ${FairMQ_${dep}_COMPONENTS})
endforeach()
add_executable(hello hello.cxx)
target_link_libraries(hello PRIVATE FairMQ::FairMQ)
```
```cpp title="hello.cxx"
#include <fairmq/Device.h>
#include <fairmq/runDevice.h>
#include <memory>
struct Hello : fair::mq::Device
{
bool ConditionalRun() override
{
LOG(info) << "Hello from " << GetId();
return false;
}
};
void addCustomOptions(boost::program_options::options_description&) {}
std::unique_ptr<fair::mq::Device> getDevice(fair::mq::ProgOptions&)
{
return std::make_unique<Hello>();
}
```
Configure and build the project, and run the program:
```sh
cmake -S hello -B hello/build -DCMAKE_PREFIX_PATH="$HOME/fairmq_install"
cmake --build hello/build
hello/build/hello --id hello1 --control static
```
The device logs `Hello from hello1`. Then [`ConditionalRun()`](/api/fair/mq/Device/#ConditionalRun) returns `false`, and the device leaves the state `RUNNING`. In the control mode `static`, the device then goes to `EXITING`, and the program ends. The device has no channels, so it also logs the warning `No channels created after finishing initialization`.
[Your first device](/start/first-device/) explains the code of a device.
## Find the package
```cmake
find_package(FairMQ 1.11 REQUIRED)
```
The version is a minimum. The package accepts each installed version that is equal to it or newer, also a newer major version. You can also omit the version.
The package is in the folder `lib/cmake/FairMQ-<version>/` of the installation prefix. On some systems, the folder is `lib64/` instead of `lib/`. The folder contains `FairMQConfig.cmake`, `FairMQConfigVersion.cmake` and the files `FairMQTargets*.cmake`, which define the imported targets.
## Point CMake to the installation
If FairMQ is not in a system directory, tell CMake where it is. Use one of these ways:
- `-DCMAKE_PREFIX_PATH=<prefix>` gives the installation prefix. For more prefixes, separate them with `;`.
- The environment variable `CMAKE_PREFIX_PATH` also gives prefixes. On Linux, separate them with `:`. `spack load fairmq` and an active Spack environment set this variable.
- `-DFairMQ_ROOT=<prefix>` gives the prefix of FairMQ only.
- `-DFairMQ_DIR=<prefix>/lib/cmake/FairMQ-1.11.0` gives the folder that contains `FairMQConfig.cmake`.
- In your `CMakeLists.txt`, add a prefix with `list(PREPEND CMAKE_PREFIX_PATH /path/to/fairmq_install)` before `find_package()`.
## Find the dependencies of FairMQ
`FairMQConfig.cmake` does not find the dependencies of FairMQ. But the target `FairMQ::FairMQ` refers to targets of its dependencies, for example `FairLogger::FairLogger` and `Boost::program_options`. Your project must find these packages, or CMake stops with an error (see [Problems that can occur](/start/cmake/#problems-that-can-occur)).
The package gives the list of the dependencies, with the minimum versions and the components:
- `FairMQ_PACKAGE_DEPENDENCIES` is the list, for example `Threads FairLogger Boost`. It can also contain the dependencies of FairLogger, for example `fmt`.
- `FairMQ_<dep>_VERSION` is the minimum version of the dependency `<dep>`, for example `FairMQ_Boost_VERSION`.
- `FairMQ_<dep>_COMPONENTS` is the list of the components of `<dep>`, for example `FairMQ_Boost_COMPONENTS`.
The loop in the [minimal project](/start/cmake/#a-minimal-project) finds each dependency with these values. Put the loop after `find_package(FairMQ)`. Use the installations of the dependencies that FairMQ was built with.
### With FairCMakeModules
If your project uses [FairCMakeModules](https://github.com/FairRootGroup/FairCMakeModules), its module [`FairFindPackage2`](https://fairrootgroup.github.io/FairCMakeModules/latest/module/FairFindPackage2.html) can do the same work:
```cmake
find_package(FairCMakeModules 0.2 REQUIRED)
include(FairFindPackage2)
find_package2(PRIVATE FairMQ VERSION 1.11 REQUIRED)
find_package2_implicit_dependencies()
```
`find_package2_implicit_dependencies()` finds the dependencies of all packages that your project found with `find_package2()`. This way needs an installed FairCMakeModules. The bundled copy that the FairMQ build uses is not part of the FairMQ installation.
## Imported targets
| Target | What it is |
| --- | --- |
| `FairMQ::FairMQ` | The library `libfairmq`. Link your programs to this target. |
| `FairMQ::fairmq-bsampler`, `FairMQ::fairmq-merger`, `FairMQ::fairmq-multiplier`, `FairMQ::fairmq-proxy`, `FairMQ::fairmq-sink`, `FairMQ::fairmq-splitter` | The [built-in devices](/tools/builtin-devices/). |
| `FairMQ::fairmq-shmmonitor` | The tool [`fairmq-shmmonitor`](/tools/shmmonitor/). |
| `FairMQ::fairmq-uuid-gen` | The tool [`fairmq-uuid-gen`](/reference/tools/#fairmq-uuid-gen). |
| `FairMQ::fairmq-tidy` | The tool [`fairmq-tidy`](/tools/fairmq-tidy/). Only in an installation that was built with `BUILD_TIDY_TOOL=ON`. |
Use the targets of the programs in custom commands and tests. For example, `$<TARGET_FILE:FairMQ::fairmq-sink>` gives the path of `fairmq-sink`.
### What `FairMQ::FairMQ` gives your target
- **Include directories.** `<prefix>/include` and `<prefix>/include/fairmq`. Include the headers as `fairmq/<Name>.h`, for example `#include <fairmq/Device.h>`.
- **C++17.** The target has the compile feature `cxx_std_17`. CMake compiles your target with C++17 or a later standard.
- **Compile definitions.** `BOOST_ERROR_CODE_HEADER_ONLY`, `BOOST_ASIO_HAS_HAS_STD_CHRONO`, and `FAIRMQ_HAS_STD_FILESYSTEM` and `FAIRMQ_HAS_STD_PMR` with the value `0` or `1`. An installation with `FAIRMQ_DEBUG_MODE=ON` adds `FAIRMQ_DEBUG_MODE`. An installation with `FAIRMQ_CHANNEL_DEFAULT_AUTOBIND` adds `FAIRMQ_CHANNEL_DEFAULT_AUTOBIND` with the value `true` or `false`.
- **Libraries.** `FairLogger::FairLogger`, `Boost::boost`, `Boost::container`, `Boost::program_options`, `Boost::filesystem`, `Boost::regex`, `Threads::Threads`, `dl`, and `rt` on Linux.
ZeroMQ and PicoSHA2 are private dependencies of `libfairmq`. Your project does not find or link them.
## Package variables
After `find_package(FairMQ)`, these variables are set:
| Variable | Value |
| --- | --- |
| `FairMQ_VERSION` | The version, for example `1.11.0`. |
| `FairMQ_GIT_VERSION` | The output of `git describe --tags --dirty --match "v*"` at build time, without the `v`. For example `1.11.0`, or `1.11.0-4-g1a2b3c4` for a commit after the tag. |
| `FairMQ_GIT_DATE` | The date of the last commit at build time (`git log -1 --format=%cd`). The value is a CMake list: CMake splits the date at the spaces. |
| `FairMQ_VERSION_HOTFIX` | Empty for a version with three numbers, for example `1.11.0`. |
| `FairMQ_PREFIX` | The installation prefix. |
| `FairMQ_BINDIR` | The folder of the programs, `<prefix>/bin`. |
| `FairMQ_INCDIR` | The folder of the headers, `<prefix>/include`. |
| `FairMQ_LIBDIR` | The folder of the library, for example `<prefix>/lib`. |
| `FairMQ_DATADIR` | `<prefix>/share/fairmq`. |
| `FairMQ_CMAKEMODDIR` | `<prefix>/share/fairmq/cmake`, the folder of `FindZeroMQ.cmake`, and of `FairMQTidy.cmake` if the build had `BUILD_TIDY_TOOL=ON`. |
| `FairMQ_BUILD_TYPE` | The `CMAKE_BUILD_TYPE` of the FairMQ build, for example `Release`. |
| `FairMQ_BUILD_TYPE_UPPER` | The same value in upper case, for example `RELEASE`. |
| `FairMQ_CXX_FLAGS` | The `CMAKE_CXX_FLAGS` and `CMAKE_CXX_FLAGS_<BUILD_TYPE>` of the FairMQ build, as a CMake list. |
| `FairMQ_PACKAGE_DEPENDENCIES` | The public dependencies, see [Find the dependencies of FairMQ](/start/cmake/#find-the-dependencies-of-fairmq). |
| `FairMQ_<dep>_VERSION` | The minimum version of the dependency `<dep>`. |
| `FairMQ_<dep>_COMPONENTS` | The components of the dependency `<dep>`. |
| `FairMQ_<component>_FOUND` | `TRUE` for each component that the FairMQ build had. See [Components](/start/cmake/#components). |
`find_package(FairMQ)` also puts `FairMQ_CMAKEMODDIR` at the front of `CMAKE_MODULE_PATH`. Then `include(FairMQTidy)` finds the module of FairMQ.
:::note
The variable `FairMQ_PACKAGE_COMPONENTS` is empty in this version of FairMQ. Use the variables `FairMQ_<component>_FOUND`.
:::
For all build options of FairMQ, see [CMake options and variables](/reference/cmake/).
## Components
The package has these components. A component is present only if the FairMQ build had it:
| Component | Build option of FairMQ | What it contains |
| --- | --- | --- |
| `fairmq` | `BUILD_FAIRMQ` (default `ON`) | The library, the built-in devices and the tools. |
| `tests` | `BUILD_TESTING` (default `OFF`) | The tests. They are not installed. |
| `examples` | `BUILD_EXAMPLES` (default `ON`) | The examples and their start scripts. |
| `tidy_tool` | `BUILD_TIDY_TOOL` (default `OFF`) | The tool `fairmq-tidy` and the module `FairMQTidy.cmake`. |
To require a component, give it to `find_package()`:
```cmake
find_package(FairMQ 1.11 REQUIRED COMPONENTS tidy_tool)
```
If the component is missing, CMake stops. The message says that `FairMQConfig.cmake` set `FairMQ_FOUND` to `FALSE`.
## Check your code with fairmq-tidy
An installation with the component `tidy_tool` gives the CMake function `fairmq_target_tidy()`. It runs `fairmq-tidy` on the source files of a target:
```cmake title="CMakeLists.txt"
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
find_package(FairMQ 1.11 REQUIRED COMPONENTS tidy_tool)
# ... the loop over FairMQ_PACKAGE_DEPENDENCIES, add_executable(hello hello.cxx) ...
include(FairMQTidy)
fairmq_target_tidy(TARGET hello)
```
The function adds the target `fairmq-tidy-hello` to the default build. After CMake builds `hello`, it runs `fairmq-tidy` on each `.cxx` and `.cpp` file of `hello`. `fairmq-tidy` reads the compile commands from `compile_commands.json` in the build directory.
| Argument | What it does |
| --- | --- |
| `TARGET <target>` | The target to check. Required. |
| `EXTRA_ARGS <arg>` | One more argument for `fairmq-tidy`. With GCC, do not use it: the function adds its own argument, and two arguments break the command. This is a known defect. |
| `CLANG_EXECUTABLE <clang>` | The program `clang`. If your compiler is GCC, the function runs `clang -print-resource-dir` to find the Clang headers. Without this argument, it uses the target `clang` if it exists, or `clang` from `PATH`. |
The function needs `CMAKE_EXPORT_COMPILE_COMMANDS` set to `ON`. If it is not `ON`, the function writes a warning and adds no target. See [Check code with fairmq-tidy](/guides/fairmq-tidy/) for the checks and the output.
## Other ways to add FairMQ
The supported way is the one on this page: build FairMQ, install it, and find the installation with `find_package(FairMQ)`. The CMake code of FairMQ does not support a build tree, `add_subdirectory()` or `FetchContent`.
| Way | Works | Reason |
| --- | --- | --- |
| `find_package(FairMQ)` of an installation | Yes | The installation contains the targets file. |
| `find_package(FairMQ)` of a build tree | No | The build tree has no targets file. See [The build tree](#the-build-tree). |
| `add_subdirectory()` of a FairMQ source tree | No | FairMQ must be the top-level project. See [add_subdirectory() and FetchContent](#add_subdirectory-and-fetchcontent). |
| `FetchContent` | No | `FetchContent_MakeAvailable()` calls `add_subdirectory()`. |
| `ExternalProject_Add()` | Yes, in two steps | FairMQ is the top-level project of its own CMake run. See [ExternalProject](#externalproject). |
### The build tree
The configure step writes `FairMQConfig.cmake` and `FairMQConfigVersion.cmake` to the top of the build directory. But no CMake file of FairMQ calls `export()`, so the build directory has no `FairMQTargets.cmake`. `FairMQConfig.cmake` includes this file with a path for the layout of an installation, relative to its own folder. For a build directory, this path does not exist.
If `FairMQ_DIR` or `CMAKE_PREFIX_PATH` points to a build directory, `find_package(FairMQ)` stops with `include could not find requested file` and the path of `FairMQTargets.cmake`. Install FairMQ into a prefix (see [Install](/start/install/)), and give this prefix to your project.
### add_subdirectory() and FetchContent
The CMake code of FairMQ uses `CMAKE_SOURCE_DIR` and `CMAKE_BINARY_DIR` for its own source and build directories. These variables always give the directories of the top-level project. When your project adds FairMQ with `add_subdirectory()`, they give the directories of your project. The configure step stops at the first use, in line 14 of the top-level `CMakeLists.txt` of FairMQ. For a FairMQ source in the folder `fairmq/` of your project, the error is:
```txt
CMake Error at fairmq/CMakeLists.txt:14 (include):
include could not find requested file:
GitHelper
```
`CMakeLists.txt` looks for its modules in `${CMAKE_SOURCE_DIR}/cmake`. If your project adds this folder to `CMAKE_MODULE_PATH`, the configure step stops at a later use. These uses also depend on the top-level directories:
- `cmake/GitHelper.cmake` reads the version with `git describe` in `CMAKE_SOURCE_DIR`, and only if `${CMAKE_SOURCE_DIR}/.git` exists. The version then comes from the Git repository of your project, or it is `0.0.0.0`.
- `cmake/FairMQBundlePackageHelper.cmake` looks for the bundled packages in `${CMAKE_SOURCE_DIR}/extern/`.
- `cmake/FairMQPackage.cmake` reads `${CMAKE_SOURCE_DIR}/cmake/FairMQConfig.cmake.in`.
- `fairmq/CMakeLists.txt` writes `Version.h` to `${CMAKE_BINARY_DIR}/fairmq/`, and adds `CMAKE_SOURCE_DIR` and `CMAKE_BINARY_DIR` to the include directories of the library.
- The tests and the examples look for the programs of FairMQ in `${CMAKE_BINARY_DIR}/fairmq/`.
The build also has no target `FairMQ::FairMQ`. The library target is `FairMQ`. Only the installed package gives it the namespace `FairMQ::`.
`FetchContent_MakeAvailable(FairMQ)` adds the downloaded source with `add_subdirectory()`. Thus it stops with the same error. This is true for a Git clone (`GIT_REPOSITORY`) and for a release archive (`URL`). In your build directory, the error names the file `_deps/fairmq-src/CMakeLists.txt`.
A release archive from GitHub has no `.git` folder, and the folders of the Git submodules in `extern/` are empty. A standalone build of such an archive gets the version `0.0.0.0`. If FairCMakeModules is not installed, its configure step stops when it tries to build the bundled copy: `git submodule update` fails with `fatal: not a git repository`. The log is `extern/FairCMakeModules/build.log` in the build directory. Use a Git clone with the tags (see [Install](/start/install/#problems-that-can-occur)).
### ExternalProject
`ExternalProject_Add()` configures, builds and installs FairMQ at the build time of your project, in a CMake run of its own. FairMQ is then the top-level project, and a Git clone gets the version from its tags:
```cmake title="CMakeLists.txt"
include(ExternalProject)
ExternalProject_Add(FairMQ
GIT_REPOSITORY https://github.com/FairRootGroup/FairMQ
GIT_TAG v1.11.0
CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/fairmq_install
)
```
Give the options of the FairMQ build in `CMAKE_ARGS`, for example the prefixes of the dependencies (see [Dependencies in other directories](/start/install/#dependencies-in-other-directories)).
The installation exists only after the build step. `find_package()` runs at configure time, so the same CMake run cannot find this installation (CMake behavior). Put the programs that use FairMQ into a separate CMake project. Configure it after the install step, for example as a second `ExternalProject_Add()` with `DEPENDS FairMQ`. Give it the prefix of the installation in `CMAKE_PREFIX_PATH`.
## Problems that can occur
- **`Could not find a package configuration file provided by "FairMQ"`.** CMake does not find the installation. Give the installation prefix with `CMAKE_PREFIX_PATH`, or the package folder with `FairMQ_DIR`.
- **`Could not find a configuration file for package "FairMQ" that is compatible with requested version`.** The installed version is older than the version in `find_package()`. The message shows each package that CMake found, with its version. The version `0.0.0.0` comes from a FairMQ build without the git tags (see [Install](/start/install/#problems-that-can-occur)).
- **`The link interface of target "FairMQ::FairMQ" contains: … but the target was not found.`** Your project did not find the dependencies of FairMQ. The message names a target of a dependency, for example `FairLogger::FairLogger`. Add the loop over `FairMQ_PACKAGE_DEPENDENCIES` after `find_package(FairMQ)`.
- **CMake does not find a dependency in the loop.** Add the installation prefix of the dependency to `CMAKE_PREFIX_PATH`.
- **`include could not find requested file:` with the path of `FairMQTargets.cmake`.** `FairMQ_DIR` or `CMAKE_PREFIX_PATH` points to a build directory of FairMQ. Give the installation prefix. See [The build tree](#the-build-tree).
- **`include could not find requested file: GitHelper`.** Your project adds FairMQ with `add_subdirectory()` or `FetchContent`. FairMQ must be a top-level project. See [Other ways to add FairMQ](#other-ways-to-add-fairmq).
- **`CMAKE_EXPORT_COMPILE_COMMANDS is not enabled. Skipping.`** Set `CMAKE_EXPORT_COMPILE_COMMANDS` to `ON` before you call `fairmq_target_tidy()`.
## Related pages
- [Install](/start/install/): build and install FairMQ.
- [Your first device](/start/first-device/): a project with two devices.
- [CMake options and variables](/reference/cmake/): the build options of FairMQ.
- [Check code with fairmq-tidy](/guides/fairmq-tidy/): use the static analyzer.

View File

@@ -0,0 +1,218 @@
---
title: Your first device
description: Write a sampler and a sink, build them against an installed FairMQ, and run them in two terminals.
sidebar:
order: 3
code: [fairmq/runDevice.h, fairmq/DeviceRunner.cxx, fairmq/Device.h, fairmq/plugins/control/Control.cxx, fairmq/StateMachine.cxx]
---
import Snippet from '../../../components/Snippet.astro';
import { Steps, FileTree } from '@astrojs/starlight/components';
In this tutorial, you write two devices and run them in two terminals. The sampler sends the text `Hello` once per second, and the sink receives it. The code is the code of [example 1-1](/examples/1-1/).
You need an installed FairMQ (see [Install](/start/install/)), CMake 3.15 or later, and a C++17 compiler.
## The topology
| Device | Channel | Type | Method | Address |
| --- | --- | --- | --- | --- |
| sampler | `data` | `push` | `bind` | `tcp://*:5555` |
| sink | `data` | `pull` | `connect` | `tcp://localhost:5555` |
The sampler binds its channel to the port 5555 on all network interfaces. The sink connects to this port on the same host. Both devices use the default transport `zeromq`.
## Create the project
Make a folder with three files:
<FileTree>
- first-device/
- CMakeLists.txt
- sampler.cxx
- sink.cxx
</FileTree>
## Write the sampler
Write this code into `sampler.cxx`:
<Snippet file="examples/1-1/sampler.cxx" title="sampler.cxx" />
The parts of the sampler:
- `struct Sampler : fair::mq::Device` makes the sampler a [device](/api/fair/mq/Device/).
- The device calls [`InitTask()`](/api/fair/mq/Device/#InitTask) in the state `INITIALIZING TASK`. The sampler reads its options there with [`fConfig->GetProperty<T>()`](/api/fair/mq/ProgOptions/#GetProperty).
- In the state `RUNNING`, the device calls [`ConditionalRun()`](/api/fair/mq/Device/#ConditionalRun) again and again. Return `true` to get the next call. Return `false` to go to the state `READY`.
- [`NewMessage()`](/api/fair/mq/Device/#NewMessage) makes a message from an existing buffer. FairMQ calls the lambda when it does not need the buffer any more. The lambda deletes the string.
- [`Send()`](/api/fair/mq/Device/#Send) sends the message on the channel `data`. It returns the number of bytes, or a negative [transfer code](/api/fair/mq/TransferCode/), for example when a state change interrupts it.
- `addCustomOptions()` adds the options `--text` (default `Hello`) and `--max-iterations` (default `0`, no limit).
- `getDevice()` makes the device object.
## Write the sink
Write this code into `sink.cxx`:
<Snippet file="examples/1-1/sink.cxx" title="sink.cxx" />
The parts of the sink:
- The constructor calls [`OnData()`](/api/fair/mq/Device/#OnData). Then the device calls `HandleData()` for each message that arrives on the channel `data`. A device with a data callback does not call `ConditionalRun()` or `Run()`.
- `HandleData()` returns `true` to wait for the next message, or `false` to go to the state `READY`.
- [`GetData()`](/api/fair/mq/Message/#GetData) and [`GetSize()`](/api/fair/mq/Message/#GetSize) give the buffer of the message and its size in bytes.
## The main function
Both files include `fairmq/runDevice.h`. This header defines the function `main()`. Your code must define the two functions that the header declares:
<Snippet file="fairmq/runDevice.h" start="// to be implemented by the user to return" end="void addCustomOptions" />
The function `main()` makes a [`fair::mq::DeviceRunner`](/api/fair/mq/DeviceRunner/) and calls its [`Run()`](/api/fair/mq/DeviceRunner/#Run). `Run()` does these steps (see [DeviceRunner.cxx](/source/fairmq/DeviceRunner.cxx/#L108-L194)):
1. It loads the built-in plugins `config` and `control`.
2. It calls `addCustomOptions()`. Your options show in `--help` in the group `Custom options`.
3. It parses the command line. For `--help`, it prints the options and stops.
4. It calls `getDevice()` to get your device.
5. It starts the plugins. The plugin `control` requests the state transitions of the device.
6. It runs the state machine of the device until the device is in the state `EXITING`.
Include `fairmq/runDevice.h` in only one source file of each program, because it defines `main()`.
:::tip
Older code includes `fairmq/runFairMQDevice.h`. In that header, `getDevice()` returns a raw pointer. See [Move from the FairMQ* names](/guides/migrate-names/).
:::
## Write the CMake file
Write this code into `CMakeLists.txt`:
```cmake title="CMakeLists.txt"
cmake_minimum_required(VERSION 3.15)
project(FirstDevice LANGUAGES CXX)
find_package(FairMQ 1.11 REQUIRED)
# FairMQConfig.cmake does not find the dependencies of FairMQ. Find them here.
foreach(dep IN LISTS FairMQ_PACKAGE_DEPENDENCIES)
find_package(${dep} ${FairMQ_${dep}_VERSION} REQUIRED COMPONENTS ${FairMQ_${dep}_COMPONENTS})
endforeach()
add_executable(sampler sampler.cxx)
target_link_libraries(sampler PRIVATE FairMQ::FairMQ)
add_executable(sink sink.cxx)
target_link_libraries(sink PRIVATE FairMQ::FairMQ)
```
The target `FairMQ::FairMQ` gives your programs the include directories, the C++17 requirement and the libraries. [Use FairMQ in a CMake project](/start/cmake/) tells more.
## Build the devices
```sh
cmake -S first-device -B first-device/build -DCMAKE_PREFIX_PATH="$HOME/fairmq_install"
cmake --build first-device/build
```
Set `CMAKE_PREFIX_PATH` to the installation prefix of FairMQ. If you use `spack load fairmq`, omit this option, because Spack sets the variable.
## Run the devices
<Steps>
1. In a terminal, start the sampler:
```sh
first-device/build/sampler --id sampler1 --rate 1 \
--channel-config "name=data,type=push,method=bind,address=tcp://*:5555,rateLogging=0"
```
2. In a second terminal, start the sink:
```sh
first-device/build/sink --id sink1 \
--channel-config "name=data,type=pull,method=connect,address=tcp://localhost:5555,rateLogging=0"
```
</Steps>
These command lines come from the start script [`fairmq-start-ex-1-1.sh.in`](https://github.com/FairRootGroup/FairMQ/blob/dev/examples/1-1/fairmq-start-ex-1-1.sh.in) of example 1-1. The options:
| Option | What it does |
| --- | --- |
| `--id` | Sets the ID of the device. The plugin `config` needs the ID to read `--channel-config`. |
| `--rate 1` | Calls `ConditionalRun()` at most once per second. The unit is Hz. The default `0` sets no limit. |
| `--channel-config` | Configures one channel with comma-separated `key=value` pairs. `rateLogging=0` switches off the log of the transfer rates, which a channel writes each second by default. |
## The output
Each log line starts with the time and the severity, for example `[14:02:31][STATE]`. The output below does not show the time. Before these lines, each device prints the FairMQ logo with the version.
The sampler goes through the states to `RUNNING` and sends the first message. It waits in `Send()` until the sink connects:
```txt title="Terminal 1: sampler"
[STATE] Starting FairMQ state machine --> IDLE
[STATE] IDLE ---> INITIALIZING DEVICE
[STATE] INITIALIZING DEVICE ---> INITIALIZED
[STATE] INITIALIZED ---> BINDING
[STATE] BINDING ---> BOUND
[STATE] BOUND ---> CONNECTING
[STATE] CONNECTING ---> DEVICE READY
[STATE] DEVICE READY ---> INITIALIZING TASK
[STATE] INITIALIZING TASK ---> READY
[STATE] READY ---> RUNNING
[INFO] fair::mq::Device running...
[INFO] Sending "Hello"
[INFO] Sending "Hello"
[INFO] Sending "Hello"
```
The sink goes through the same states. Then it logs each message:
```txt title="Terminal 2: sink"
[STATE] READY ---> RUNNING
[INFO] fair::mq::Device running...
[INFO] Received: "Hello"
[INFO] Received: "Hello"
```
In the state `RUNNING`, the plugin `control` also prints a list of keys. With the default control mode `--control dynamic`, you can control the device with these keys. For example, `h` shows the help and `q` stops the device.
## Stop the devices
Press Ctrl+C in each terminal. The plugin `control` catches the signal `SIGINT`. It moves the device through the reset states to `EXITING` (see [Control.cxx](/source/fairmq/plugins/control/Control.cxx/#L439-L469)):
```txt
[INFO] Received device shutdown request (signal 2).
[INFO] Waiting for graceful device shutdown. Hit Ctrl-C again to abort immediately.
[STATE] RUNNING ---> READY
[STATE] READY ---> RESETTING TASK
[STATE] RESETTING TASK ---> DEVICE READY
[STATE] DEVICE READY ---> RESETTING DEVICE
[STATE] RESETTING DEVICE ---> IDLE
[STATE] IDLE ---> EXITING
```
A second Ctrl+C stops the process at once with `std::abort()`. The signal `SIGTERM` also starts the shutdown, but a second `SIGTERM` has no effect. The option `--catch-signals 0` switches off this signal handling.
## Things to try
- Add `--max-iterations 5 --control static` to both commands. Each device leaves the state `RUNNING` after 5 messages. In the control mode `static`, the device then goes to `EXITING`, and the program ends.
- Add `--text "Hello FairMQ"` to the sampler command to send a different text.
- Add `--transport shmem` to both commands. Then the devices use shared memory for the data. See [Transports](/concepts/transports/).
- Add `--severity debug` to see more log lines, for example the address that each channel uses.
- Run `first-device/build/sampler --help`. The output shows all options, and your options in the group `Custom options`.
## Problems that can occur
- **The sink receives nothing.** Another program uses the port 5555. Then the sampler binds to a random port from 22000 to 23000, because the channel property `autoBind` is `true` by default. The log shows this only at the severity `debug`. Use a free port in both commands. With `autoBind=0` in its `--channel-config`, the sampler goes to the state `ERROR` instead, and the program ends.
- **The log shows `No device ID or config-key provided for the configuration parser.`** The command has no `--id`. Without an ID, the plugin `config` does not read `--channel-config`, and the device has no channels. Add `--id` to the command.
- **CMake does not find FairMQ or its dependencies.** See [Problems that can occur](/start/cmake/#problems-that-can-occur) on the CMake page.
## Related pages
- [Devices](/concepts/devices/) and [Device states](/concepts/states/): the device and its hooks.
- [Channels and sockets](/concepts/channels/): types, methods and addresses.
- [Receive data with callbacks or loops](/guides/receive-data/): `OnData()`, `ConditionalRun()` and `Run()`.
- [Example 1-1](/examples/1-1/): the same devices, built in the FairMQ source tree.
- [Command-line options](/reference/options/): all options of a device.

View File

@@ -0,0 +1,236 @@
---
title: Install
description: Install FairMQ with Spack or build it from source with CMake, run the tests, and check the installation.
sidebar:
order: 2
---
import { Steps, Tabs, TabItem, FileTree } from '@astrojs/starlight/components';
Install FairMQ with the package manager Spack, or build it from source with CMake. Both ways give you the library `libfairmq` with its headers and its CMake package, the built-in devices and the tools.
## Requirements
The CI of FairMQ builds and tests FairMQ on Linux (Ubuntu 24.04) with GCC 12, 13, 14 and 15. The CI does not test other platforms.
| Dependency | Minimum version | Notes |
| --- | --- | --- |
| C++ compiler | C++17 | |
| [CMake](https://cmake.org/) | 3.15 | |
| [Boost](https://www.boost.org/) | 1.66 | With the libraries `container`, `program_options`, `filesystem`, `date_time` and `regex`. Boost 1.88 is not supported. |
| [FairLogger](https://github.com/FairRootGroup/FairLogger) | 1.6.0 | |
| [ZeroMQ](https://zeromq.org/) (`libzmq`) | 4.1.4 | The shared library `libzmq.so` and its headers. |
| [FairCMakeModules](https://github.com/FairRootGroup/FairCMakeModules) | 0.2 | If CMake does not find it, the build uses a bundled copy. |
| [PicoSHA2](https://github.com/okdshin/PicoSHA2) | — | The build always uses a bundled copy. |
| [GoogleTest](https://github.com/google/googletest) | — | Only for the tests. The build uses a bundled copy by default. |
| git | — | CMake reads the version of FairMQ from git and gets the bundled copies with git. |
| LLVM, Clang, [CLI11](https://github.com/CLIUtils/CLI11) | — | Only for the tool `fairmq-tidy`. |
The bundled copies are git submodules in the folder `extern/` of the repository. When CMake needs a bundled copy, it runs `git submodule update --init` for it.
## Install FairMQ
<Tabs>
<TabItem label="Spack">
[Spack](https://spack.readthedocs.io/en/latest/getting_started.html) installs FairMQ and all its dependencies.
<Steps>
1. Install Spack. See [Getting started](https://spack.readthedocs.io/en/latest/getting_started.html) in the Spack documentation.
2. Show the versions and the variants of the package:
```sh
spack info fairmq
```
3. Build and install FairMQ:
```sh
spack install fairmq
```
This command installs the latest packaged version with the default variants. For a different version, add it to the spec, for example `spack install fairmq@1.11.0`.
4. Load FairMQ into your shell:
```sh
spack load fairmq
```
This command adds the tools of FairMQ to `PATH` and the installation to `CMAKE_PREFIX_PATH`.
</Steps>
</TabItem>
<TabItem label="From source">
<Steps>
1. Clone the repository:
```sh
git clone https://github.com/FairRootGroup/FairMQ fairmq_source
```
For a release, add the tag, for example `git clone -b v1.11.0 …`. Do not make a shallow clone: CMake needs the tags.
2. Install the dependencies. To install them with Spack, use the file `spack.yaml` of the repository:
```sh
spack --env fairmq_source install
spack env activate fairmq_source
```
The active environment sets `CMAKE_PREFIX_PATH`. Then CMake finds the dependencies.
3. Configure the build:
```sh
cmake -S fairmq_source -B fairmq_build -G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX="$HOME/fairmq_install"
```
At the end, CMake prints a summary: the dependencies that it found, the components that it builds, and the install prefix. Remove `-G Ninja` to use the default generator.
4. Build FairMQ:
```sh
cmake --build fairmq_build
```
5. Install FairMQ:
```sh
cmake --install fairmq_build
```
</Steps>
</TabItem>
</Tabs>
### Dependencies in other directories
If a dependency is not in a system directory, give its installation prefix to CMake. Use one of these ways:
- `-DCMAKE_PREFIX_PATH="/opt/fairlogger;/opt/zeromq"` gives a list of prefixes for all dependencies.
- `-D<NAME>_ROOT=<prefix>` gives the prefix of one dependency. Write the package name in upper case, for example `-DFAIRLOGGER_ROOT=/opt/fairlogger` or `-DZEROMQ_ROOT=/opt/zeromq`. You can also set these variables in the environment.
## Build options
| Option | Default | What it does |
| --- | --- | --- |
| `CMAKE_BUILD_TYPE` | `RelWithDebInfo` | Sets the build type: `Debug`, `Release` or `RelWithDebInfo`. |
| `CMAKE_INSTALL_PREFIX` | `/usr/local` | Sets the installation directory. Set it when you configure, because the installed start scripts of the examples contain this path. |
| `BUILD_TESTING` | `OFF` | Builds the tests. |
| `BUILD_EXAMPLES` | `ON` | Builds the examples. `cmake --install` also installs them and their start scripts. |
| `BUILD_TIDY_TOOL` | `OFF` | Builds the experimental tool [`fairmq-tidy`](/tools/fairmq-tidy/). It needs LLVM, Clang and CLI11. |
| `FAIRMQ_CHANNEL_DEFAULT_AUTOBIND` | not set | Sets the default of the channel property `autoBind`. If the option is not set, the default is `true`. |
| `FAIRMQ_DEBUG_MODE` | `OFF` | The transport `shmem` records its messages, so that `fairmq-shmmonitor --debug` can list them. This can decrease the performance. |
| `USE_EXTERNAL_GTEST` | `OFF` | Uses an installed GoogleTest instead of the bundled copy. |
For all options and their effects, see [CMake options and variables](/reference/cmake/).
## Run the tests
Configure the build with `BUILD_TESTING=ON`, build it, and run the tests with CTest:
```sh
cmake -S fairmq_source -B fairmq_build -DBUILD_TESTING=ON
cmake --build fairmq_build
ctest --test-dir fairmq_build --output-on-failure -j "$(nproc)"
```
The option `--test-dir` needs CMake 3.20 or later. With an older CMake, run `ctest` in the build directory.
The name of each test starts with the name of its test suite. The test suites are `Channel`, `Device`, `EventManager`, `MemoryResources`, `Message`, `Parts`, `Plugins`, `PluginServices`, `PluginsPrelinked`, `Poller`, `Properties`, `Protocols`, `Region`, `StateMachine`, `Tools` and `Transport`. The tests of the examples have names like `Example.1-1.zeromq` and `Example.1-1.shmem`.
The tests have no labels. Select tests by name with `-R`, and exclude tests with `-E`:
```sh
ctest --test-dir fairmq_build --output-on-failure -R '^Example\.1-1\.'
```
## Check the installation
<Steps>
1. Add the tools to `PATH`. After `spack load fairmq`, skip this step.
```sh
export PATH="$HOME/fairmq_install/bin:$PATH"
```
2. Run the tool [`fairmq-uuid-gen`](/reference/tools/#fairmq-uuid-gen). It prints a random UUID. This shows that the tool finds the library `libfairmq`.
```sh
fairmq-uuid-gen
```
3. Show the options of the built-in device `fairmq-sink`:
```sh
fairmq-sink --help
```
4. Read the installed version from the header `fairmq/Version.h`. For a Spack installation, use the prefix that `spack location -i fairmq` prints.
```sh
grep FAIRMQ_GIT_VERSION "$HOME/fairmq_install/include/fairmq/Version.h"
```
```txt
#define FAIRMQ_GIT_VERSION "1.11.0"
```
</Steps>
:::note
The option `--version` of a device prints nothing in this version of FairMQ. This is a known defect. Read the version from `fairmq/Version.h`, or from the CMake variable `FairMQ_VERSION`.
:::
The installation directory contains these files:
<FileTree>
- fairmq_install/
- bin/
- fairmq-bsampler
- fairmq-merger
- fairmq-multiplier
- fairmq-proxy
- fairmq-shmmonitor
- fairmq-sink
- fairmq-splitter
- fairmq-uuid-gen
- fairmq-ex-1-1-sampler the examples, with `BUILD_EXAMPLES=ON`
- …
- include/
- fairmq/ the headers, for example `Device.h` and `runDevice.h`
- lib/ or `lib64/` on some systems
- libfairmq.so
- cmake/
- FairMQ-1.11.0/ the CMake package
- share/
- fairmq/
- cmake/ `FindZeroMQ.cmake`, and `FairMQTidy.cmake` with `BUILD_TIDY_TOOL=ON`
</FileTree>
## Problems that can occur
- **The version is `0.0.0.0`.** CMake reads the version from `git describe --tags`. A source tree without the git history or without the tags gets the version `0.0.0.0`, and `find_package(FairMQ 1.11)` does not accept it. Build from a full git clone. [Other ways to add FairMQ](/start/cmake/#other-ways-to-add-fairmq) tells what fails with a release archive or `FetchContent`.
- **CMake stops with `Boost version 1.88 is not supported`.** Use a Boost version before 1.88, or 1.89 or later.
- **CMake does not find ZeroMQ.** Install the shared library `libzmq.so` and the header `zmq.h`. Give their prefix with `-DZEROMQ_ROOT=<prefix>`.
- **CMake cannot get a bundled copy.** CMake runs `git submodule update --init`, which needs network access. Clone with `--recurse-submodules` to get all submodules at once.
- **Shared memory tests fail.** Some tests lock shared memory in RAM with `mlock()`, for example `Region.PreallocateInsideSession.shmem`. If the limit for locked memory is too low, these tests fail. Show the limit with `ulimit -l`. The CI of FairMQ sets the limit to `unlimited` before it runs the tests.
## Related pages
- [Your first device](/start/first-device/): write, build and run two devices.
- [Use FairMQ in a CMake project](/start/cmake/): find the installed package.
- [CMake options and variables](/reference/cmake/): all build options.
- [Example 1-1](/examples/1-1/): run the example from the build directory.

View File

@@ -0,0 +1,79 @@
---
title: Overview
description: What FairMQ is, its building blocks and how they fit together, what FairMQ does not do, and where to go next.
sidebar:
order: 1
code: [fairmq/Device.h, fairmq/Channel.h, fairmq/TransportFactory.h, fairmq/Parts.h, fairmq/Plugin.h]
---
FairMQ is a C++17 library and framework for message queuing in data processing pipelines. Programs called devices send messages to each other through channels. FairMQ moves the messages with ZeroMQ, or through shared memory without a copy on one host.
## What FairMQ is
FairMQ comes from the [FairRoot](https://github.com/FairRootGroup/FairRoot) project at GSI. It helps to build the large data processing workflows of particle physics experiments. FairMQ has two parts:
- **A library.** It gives a message passing API with the communication patterns of ZeroMQ, for example `push`/`pull`, `pub`/`sub` and `req`/`rep`. Different transports implement this API. You can [use channels without a device](/guides/channels-without-device/).
- **A framework.** You write devices. A device is a class that sends and receives messages. Each device has a state machine and a plugin system for configuration and control.
FairMQ does not look at the content of a message, so your data can have any format. A device can use different transports on different channels at the same time.
## The building blocks
| Building block | What it does | Page |
| --- | --- | --- |
| Device | Runs your code. You derive a class from [`fair::mq::Device`](/api/fair/mq/Device/) and override its hooks. The header `fairmq/runDevice.h` runs one device in one process. | [Devices](/concepts/devices/) |
| Channel, sub-channel, socket | A [channel](/api/fair/mq/Channel/) is a named connection point of a device, for example `data`. A channel has one or more sub-channels. Each sub-channel has one socket with a type (for example `push`), a method (`bind` or `connect`) and an address. | [Channels and sockets](/concepts/channels/) |
| Transport | Makes the messages, sockets, pollers and regions of a channel ([`fair::mq::TransportFactory`](/api/fair/mq/TransportFactory/)). `zeromq` is the default transport. `shmem` moves the data through shared memory between devices on one host. | [Transports](/concepts/transports/) |
| Message and multipart | A [message](/api/fair/mq/Message/) holds one buffer of bytes. A multipart message ([`fair::mq::Parts`](/api/fair/mq/Parts/)) holds several parts that a channel sends and receives as one unit. | [Messages and multipart](/concepts/messages/) |
| State machine and hooks | Each device has a state machine with [states](/api/fair/mq/State/) such as `IDLE`, `READY` and `RUNNING`. In some states, the device calls its hooks, for example [`InitTask()`](/api/fair/mq/Device/#InitTask) and [`ConditionalRun()`](/api/fair/mq/Device/#ConditionalRun). | [Device states](/concepts/states/) |
| Configuration | Each device has a store of properties ([`fair::mq::ProgOptions`](/api/fair/mq/ProgOptions/)). Command-line options, `--channel-config`, JSON files (`--mq-config`) and plugins set the properties. Your code reads them with [`GetProperty()`](/api/fair/mq/ProgOptions/#GetProperty). | [Configuration and properties](/concepts/configuration/) |
| Plugins and controllers | [Plugins](/api/fair/mq/Plugin/) add functions to a device at run time. A controller is a plugin that changes the state of the device. The built-in plugin `control` is the default controller. | [Plugins and control](/concepts/plugins/) |
FairMQ has more parts for special tasks. A poller waits for data on several channels (see [Poll several channels](/guides/poll-channels/)). An unmanaged region is a buffer that your code manages, and messages can point into it (see [Unmanaged regions](/shmem/regions/)).
## How the parts fit together
A set of devices and the channels between them is a topology. The topology of [example 1-1](/examples/1-1/) has two devices. The sampler sends messages, and the sink receives them. The two devices work like this:
1. You start each device as a process. The command line gives the device ID and the channel configuration, for example `--id sampler1 --channel-config name=data,type=push,method=bind,address=tcp://*:5555`.
2. The built-in plugin `config` reads the channel configuration into the properties of the device.
3. The built-in plugin `control` requests the transitions of the state machine. The device goes from `IDLE` through the initialization states to `RUNNING`.
4. In the states `BINDING` and `CONNECTING`, the device makes the sockets of its channels with the transport `zeromq`. The sampler binds its `push` socket. The sink connects its `pull` socket.
5. In the state `RUNNING`, the sampler makes a message in `ConditionalRun()` and sends it on the channel `data`. The sink receives each message in a data callback, which it registered with [`OnData()`](/api/fair/mq/Device/#OnData).
6. When you press Ctrl+C, the plugin `control` stops the device. The device goes through the reset states to `EXITING`.
[Your first device](/start/first-device/) shows these steps with the code of example 1-1. [Threads in a device](/concepts/threads/) tells which thread runs each hook and callback. For the devices and channels of your own topology, see [Design a topology](/guides/design-topology/).
## What the installation contains
- The library `libfairmq` and its headers in `include/fairmq/`.
- The CMake package `FairMQ` with the imported target `FairMQ::FairMQ`. See [Use FairMQ in a CMake project](/start/cmake/).
- The header `fairmq/runDevice.h`. It gives the `main()` function of a device program.
- The built-in devices `fairmq-bsampler`, `fairmq-merger`, `fairmq-multiplier`, `fairmq-proxy`, `fairmq-sink` and `fairmq-splitter`. See [Built-in devices](/tools/builtin-devices/).
- The tool [`fairmq-shmmonitor`](/tools/shmmonitor/), which monitors and cleans up shared memory, and the tool `fairmq-uuid-gen`, which prints a UUID.
- The examples and their start scripts (CMake option `BUILD_EXAMPLES`, default `ON`).
- Optional: the static analyzer [`fairmq-tidy`](/tools/fairmq-tidy/) (CMake option `BUILD_TIDY_TOOL`, default `OFF`).
## What FairMQ does not do
- **Deployment.** FairMQ does not start devices on hosts. You start each device as a process, for example with a shell script like the start scripts of the examples. For a topology on many hosts, use a deployment system, for example [DDS](https://github.com/FairRootGroup/DDS). [ODC](https://github.com/FairRootGroup/ODC) controls a topology of FairMQ devices through DDS. The example [dds](/examples/dds/) describes a topology for DDS.
- **Serialization.** A message is a buffer of bytes. FairMQ does not serialize your data. Your code defines the data format.
- **A broker or storage.** FairMQ has no broker. The devices connect directly to each other. FairMQ does not write messages to disk.
- **Security.** FairMQ does not encrypt or authenticate the connections between devices.
- **Shared memory between hosts.** The transport `shmem` works only between devices on one host. Between hosts, use the transport `zeromq`.
:::note[Removed components]
FairMQ 1.5.0 removed the `ofi` transport, the SDK, and the plugins for DDS and PMIx. The last release with these components is v1.4.56. The DDS plugin (`-P dds`), the SDK and the tool `fairmq-dds-command-ui` moved to the [ODC](https://github.com/FairRootGroup/ODC) project.
:::
## Where to go next
- [Install](/start/install/) FairMQ with Spack or from source.
- Write, build and run [your first device](/start/first-device/).
- [Use FairMQ in a CMake project](/start/cmake/).
- Run the [examples](/examples/1-1/). Each example shows one feature.
- Read the [concepts](/concepts/devices/), starting with devices.
- [Design a topology](/guides/design-topology/): the patterns, the binding devices and the transports.
- [Test your devices](/guides/test-devices/) with CTest.
- Measure the throughput of the transports with a [benchmark](/guides/benchmark/).
- Look up a class in the [API reference](/api/), or read the code in the [source browser](/source/).

View File

@@ -0,0 +1,261 @@
---
title: 'Built-in devices'
description: 'The ready-made devices of FairMQ: benchmark sampler, sink, splitter, merger, multiplier and proxy, with their channels, options and commands.'
sidebar:
order: 2
code: [fairmq/devices/BenchmarkSampler.h, fairmq/devices/Sink.h, fairmq/devices/Splitter.h, fairmq/devices/Merger.h, fairmq/devices/Multiplier.h]
---
import OptionsTable from '../../../components/OptionsTable.astro';
import Snippet from '../../../components/Snippet.astro';
FairMQ builds six ready-made devices as executables. Use them to make test traffic, to measure the throughput of a transport, and to move messages between your own devices without new code.
| Executable | Class | What it does | Channels (default names) | `--multipart` |
| --- | --- | --- | --- | --- |
| [`fairmq-bsampler`](#fairmq-bsampler) | `fair::mq::BenchmarkSampler` | Sends messages of a fixed size, at full speed or at a fixed rate. | output `data` | `false` |
| [`fairmq-sink`](#fairmq-sink) | `fair::mq::Sink` | Receives messages. Discards them or writes them to a file. | input `data` | `false` |
| [`fairmq-splitter`](#fairmq-splitter) | `fair::mq::Splitter` | Sends each message to the next sub-channel of the output channel (round robin). | input `data-in`, output `data-out` | `true` |
| [`fairmq-merger`](#fairmq-merger) | `fair::mq::Merger` | Receives from all sub-channels of the input channel and sends on one output channel. | input `data-in`, output `data-out` | `true` |
| [`fairmq-multiplier`](#fairmq-multiplier) | `fair::mq::Multiplier` | Sends each message to all sub-channels of all output channels. | input `data-in`, outputs from `--out-channel` (no default) | `true` |
| [`fairmq-proxy`](#fairmq-proxy) | `fair::mq::Proxy` | Receives on the input channel and sends on the output channel. | input `data-in`, output `data-out` | `true` |
The last column shows the default value of the option `--multipart`.
## Find the executables
CMake builds the devices together with the FairMQ library (option `BUILD_FAIRMQ`, default `ON`).
- In the build directory, the executables are in `<build>/fairmq/`, for example `build/fairmq/fairmq-sink`.
- An installation puts them into the `bin` directory of the install prefix (`CMAKE_INSTALL_BINDIR`).
- The CMake package exports each executable as an imported target, for example `FairMQ::fairmq-sink`.
The sources are in [`fairmq/devices/`](https://github.com/FairRootGroup/FairMQ/tree/dev/fairmq/devices). Each device is a class in a header, for example `Sink.h`, and a short `run*.cxx` file adds its options. The headers are private: an installation does not include them. To change the behavior of a device, [write your own device](/start/first-device/).
## Common behavior
- Each `run*.cxx` file includes `<fairmq/runDevice.h>`. So each executable has all [device options](/reference/options/), for example `--id`, `--transport`, `--channel-config`, `--control` and `--severity`.
- The device reads its own options in `InitTask()`.
- Configure the channels with `--channel-config` or `--mq-config`. See [Configure channels](/guides/configure-channels/). The channel names must be the names that `--in-channel` and `--out-channel` give. If a channel does not exist, the device goes to the state `ERROR`.
- Each `address` in a `--channel-config` value makes one sub-channel. For example, `name=data-out,type=push,method=bind,address=tcp://*:5556,address=tcp://*:5557` makes the sub-channels `data-out[0]` and `data-out[1]`.
- Both controllers move the device to `RUNNING`. Then the default controller (`--control dynamic`) waits for keys in the terminal. With `--control static`, the device stops and the process ends when the device leaves `RUNNING` on its own.
- Each channel logs its message rate and data rate every second (channel property `rateLogging`, default `1`). See [Run a benchmark](/guides/benchmark/#read-the-rate-lines).
:::caution[Use the same `--multipart` value in a chain]
The default of `--multipart` is `false` for the sampler and the sink, and `true` for the other devices. Give all devices that exchange messages the same value. The `shmem` transport sends single messages and multipart messages in two different metadata formats. A receiver with the wrong value cannot read the metadata.
:::
## fairmq-bsampler
The class [`fair::mq::BenchmarkSampler`](/source/fairmq/devices/BenchmarkSampler.h/#L29-L109) makes traffic for benchmarks. Its `Run()` loop does these steps until the state changes:
- It makes a message of `--msg-size` bytes with the transport of the output channel. With `--multipart true`, it makes a multipart message of `--num-parts` parts. Each part has `--msg-size` bytes.
- With `--memset true`, it writes zeros into each buffer. Otherwise it does not write into the buffers.
- It sends the message on sub-channel 0 of `--out-channel`. With the default send timeout (`sndTimeoutMs` -1), the send waits until the socket accepts the message.
- With `--msg-rate` above 0, a [`fair::mq::tools::RateLimiter`](/api/fair/mq/tools/RateLimiter/) limits the number of messages per second. See [RateLimit.h](/reference/tools/#ratelimith).
<OptionsTable
file="fairmq/devices/runBenchmarkSampler.cxx"
id="bsampler"
texts={{
'out-channel': 'Name of the output channel. The sampler sends on its sub-channel 0.',
multipart: 'Send multipart messages of <code>--num-parts</code> parts. <code>false</code>: send single messages.',
memset: 'Write zeros into each buffer before the send.',
'num-parts': 'Number of parts of each multipart message. Only with <code>--multipart true</code>.',
'msg-size': 'Size of each message in bytes. In a multipart message, the size of each part.',
'msg-alignment': 'Alignment of the buffers in bytes. 0: the default alignment of the transport.',
'max-iterations': 'Number of messages to send. 0: no limit. See the note below.',
'msg-rate': 'Maximum number of messages per second. 0: no limit.',
}}
/>
:::note[Number of messages]
The sampler counts each successful send. With `--max-iterations` n, it stops at the first send after the count is n. So it sends n + 1 messages and logs `Done n iterations`. The sink counts in the same way. A sampler and a sink with the same value stop after the same number of messages.
:::
The sampler logs these lines at the start and at the end of `Run()`:
```txt
Starting the benchmark with message size of <bytes> and <n> iterations.
Done <n> iterations in <t>ms.
```
Send messages of 10000 bytes, 100 messages per second:
```sh
fairmq-bsampler --id bsampler1 --msg-size 10000 --msg-rate 100 \
--channel-config name=data,type=push,method=bind,address=tcp://*:5555
```
## fairmq-sink
The class [`fair::mq::Sink`](/source/fairmq/devices/Sink.h/#L24-L130) receives messages on sub-channel 0 of `--in-channel` in its `Run()` loop. It discards the messages. With `--out-filename`, it writes the data of each message, or of each part, to the file. The sink leaves `RUNNING` on its own in two cases:
- It received the number of messages of `--max-iterations` (it counts like the sampler).
- The file has `--max-file-size` bytes or more. The sink checks the size after each message.
<OptionsTable
file="fairmq/devices/runSink.cxx"
id="sink"
texts={{
'in-channel': 'Name of the input channel. The sink receives on its sub-channel 0.',
'out-filename': 'Write the data of the received messages to this file (binary). Empty: discard the messages.',
'max-file-size': 'Leave <code>RUNNING</code> when the file has this number of bytes. 0: no limit. Only with <code>--out-filename</code>.',
'max-iterations': 'Number of messages to receive. 0: no limit.',
multipart: 'Receive multipart messages. Use the value of the sender.',
}}
/>
The sink logs these lines. The line `Closed …` comes only with `--out-filename`.
```txt
Starting sink and expecting to receive <n> messages.
Received <n> messages in <t>ms.
Closed '<file>' after writing <bytes> bytes.(<rate> MB/s)
Leaving RUNNING state.
```
When the sink stops on its own, it first logs `Configured maximum number of iterations reached.` or `Written <bytes> bytes, stopping...`.
If the sink cannot open or write the file, it throws an exception and goes to the state `ERROR`.
Write 100 MB of received data to a file:
```sh
fairmq-sink --id sink1 --out-filename /tmp/data.bin --max-file-size 100000000 \
--channel-config name=data,type=pull,method=connect,address=tcp://localhost:5555
```
## fairmq-splitter
The class [`fair::mq::Splitter`](/source/fairmq/devices/Splitter.h/#L19-L54) registers a data callback for `--in-channel` with [`OnData()`](/api/fair/mq/Device/#OnData). The callback sends each message to the next sub-channel of `--out-channel`: 0, 1, …, n − 1, then 0 again. It does not check the result of the send.
<Snippet file="fairmq/devices/Splitter.h" start="template<typename T>" />
If `--in-channel` has more than one sub-channel, the device receives from all of them.
<OptionsTable
file="fairmq/devices/runSplitter.cxx"
id="splitter"
texts={{
'in-channel': 'Name of the input channel.',
'out-channel': 'Name of the output channel. The splitter sends to its sub-channels in turn.',
multipart: 'Receive and send multipart messages. <code>false</code>: single messages.',
}}
/>
Send the messages from port 5555 alternately to port 5556 and port 5557:
```sh
fairmq-splitter --id splitter1 \
--channel-config name=data-in,type=pull,method=bind,address=tcp://*:5555 \
name=data-out,type=push,method=bind,address=tcp://*:5556,address=tcp://*:5557
```
## fairmq-merger
The class [`fair::mq::Merger`](/source/fairmq/devices/Merger.h/#L22-L102) makes a [poller](/guides/poll-channels/) for all sub-channels of `--in-channel`. In its `Run()` loop, it waits up to 100 ms for data. Then it receives from each sub-channel that has data and sends the message on sub-channel 0 of `--out-channel`.
<OptionsTable
file="fairmq/devices/runMerger.cxx"
id="merger"
texts={{
'in-channel': 'Name of the input channel. The merger receives from all its sub-channels.',
'out-channel': 'Name of the output channel. The merger sends on its sub-channel 0.',
multipart: 'Receive and send multipart messages. <code>false</code>: single messages.',
}}
/>
Receive on port 5556 and port 5557, and send everything to port 5558:
```sh
fairmq-merger --id merger1 \
--channel-config name=data-in,type=pull,method=bind,address=tcp://*:5556,address=tcp://*:5557 \
name=data-out,type=push,method=connect,address=tcp://localhost:5558
```
## fairmq-multiplier
The class [`fair::mq::Multiplier`](/source/fairmq/devices/Multiplier.h/#L20-L102) reads a list of channel names from `--out-channel`. This option has no default. Without it, `InitTask()` throws an exception and the device goes to the state `ERROR`.
The data callback of `--in-channel` sends each message to all sub-channels of all output channels. The last sub-channel of the last channel gets the original message. Each other sub-channel gets a copy that the device makes with [`Copy()`](/api/fair/mq/Message/#Copy). The copy shares the buffer with the original, so the device does not copy the data.
<OptionsTable
file="fairmq/devices/runMultiplier.cxx"
id="multiplier"
texts={{
'in-channel': 'Name of the input channel.',
'out-channel': 'Names of the output channels. Give one or more names. Required.',
multipart: 'Receive and send multipart messages. <code>false</code>: single messages.',
}}
/>
Send each message to two output channels:
```sh
fairmq-multiplier --id multiplier1 --out-channel data-out1 data-out2 \
--channel-config name=data-in,type=pull,method=connect,address=tcp://localhost:5555 \
name=data-out1,type=push,method=bind,address=tcp://*:5556 \
name=data-out2,type=push,method=bind,address=tcp://*:5557
```
## fairmq-proxy
The class [`fair::mq::Proxy`](/source/fairmq/devices/Proxy.h/#L19-L63) receives on sub-channel 0 of `--in-channel` and sends on sub-channel 0 of `--out-channel`. It leaves `RUNNING` when the state changes or when a transfer fails. The two channels can have different socket types and different transports. See [Use several transports](/guides/several-transports/).
<OptionsTable
file="fairmq/devices/runProxy.cxx"
id="proxy"
texts={{
'in-channel': 'Name of the input channel. The proxy receives on its sub-channel 0.',
'out-channel': 'Name of the output channel. The proxy sends on its sub-channel 0.',
multipart: 'Receive and send multipart messages. <code>false</code>: single messages.',
}}
/>
Receive on a `pull` channel and publish the messages on a `pub` channel:
```sh
fairmq-proxy --id proxy1 \
--channel-config name=data-in,type=pull,method=bind,address=tcp://*:5555 \
name=data-out,type=pub,method=bind,address=tcp://*:5556
```
## The script startMQBenchmark.sh
CMake makes the script `<build>/fairmq/startMQBenchmark.sh` from [`fairmq/devices/startMQBenchmark.sh.in`](https://github.com/FairRootGroup/FairMQ/blob/dev/fairmq/devices/startMQBenchmark.sh.in). An installation does not include it. The script starts `fairmq-bsampler` and `fairmq-sink` from the build directory, each in its own `xterm` window. So it needs `xterm` and a display.
The script takes six positional parameters. A parameter that does not match the accepted characters keeps its default.
| Position | Parameter | Default | Accepted value |
| --- | --- | --- | --- |
| 1 | Message size in bytes (`--msg-size`) | `1000000` | digits |
| 2 | Number of iterations (`--max-iterations`) | `0` (no limit) | digits |
| 3 | Transport (`--transport`) | `zeromq` | lowercase letters: `zeromq` or `shmem` |
| 4 | Affinity | `false` | `true`: run the sampler with `taskset -c 0` and the sink with `taskset -c 1` |
| 5 | Multipart (`--multipart`) | `false` | lowercase letters: `true` or `false` |
| 6 | Number of parts (`--num-parts`) | `1` | digits |
The usage line that the script prints names only the first four parameters. The script gives these options to the two devices:
<Snippet file="fairmq/devices/startMQBenchmark.sh.in" start='SAMPLER="fairmq-bsampler"' end="xterm -geometry 90x50+550+0" />
The two devices connect with a `pair` channel `data` on `tcp://127.0.0.1:5555`. With the `shmem` transport and `--shm-monitor true`, a device starts `fairmq-shmmonitor` if no monitor runs for the session. The device looks for the monitor in `$FAIRMQ_PATH` and then in `$PATH`. The script sets `FAIRMQ_PATH` to the build directory. The option `--shm-throw-bad-alloc false` makes the sampler wait for free memory in a full segment.
Run the benchmark with 1 MB messages and the `shmem` transport, without an iteration limit:
```sh
cd build/fairmq
./startMQBenchmark.sh 1000000 0 shmem
```
The windows stay open after the devices end (`xterm -hold`).
## Related pages
- [Run a benchmark](/guides/benchmark/): measure throughput with the sampler and the sink.
- [Example: built-in devices](/examples/builtin-devices/): all six devices in one topology.
- [Command-line options](/reference/options/): the options that all devices have.
- [Channel properties](/reference/channel-properties/): `sndBufSize`, `rateLogging` and the other properties.
- [Monitor and clean up](/shmem/monitor/): `fairmq-shmmonitor` and the option `--shm-monitor`.
- [Design a topology](/guides/design-topology/#fan-out-and-fan-in): fan-out and fan-in with the splitter, the merger and the multiplier.

View File

@@ -0,0 +1,219 @@
---
title: 'fairmq-tidy'
description: 'A Clang tool that finds the deprecated FairMQ* type names in your code. Its check, build, command line, exit codes and CMake function.'
sidebar:
order: 3
code: [fairmq/tidy/Tool.h, fairmq/tidy/ModernizeNonNamespacedTypes.h]
---
import Snippet from '../../../components/Snippet.astro';
`fairmq-tidy` is a static analysis tool for code that uses FairMQ. It parses your source files with the Clang libraries, finds the deprecated `FairMQ*` type aliases, and shows the `fair::mq::` type that replaces each one.
:::note
The CMake summary of FairMQ marks the tool as experimental. CMake does not build it by default.
:::
For a step-by-step procedure, see [Check code with fairmq-tidy](/guides/fairmq-tidy/). This page is the reference.
## How the tool works
`fairmq-tidy` is a program that uses Clang LibTooling. [`runTool.cpp`](https://github.com/FairRootGroup/FairMQ/blob/dev/fairmq/tidy/runTool.cpp) parses the command line. Then [`Tool::run()`](/source/fairmq/tidy/Tool.h/#L48-L81) processes each source file in these steps:
1. It gets the compile command of the file from the compilation database.
2. It adds `-std=c++17` if the command has no `-std=` option.
3. It appends `-Wno-everything`. This turns off the compiler warnings, so that the output shows the findings of the check.
4. It parses the file and runs the check on the syntax tree.
<Snippet file="fairmq/tidy/Tool.h" start="tool.appendArgumentsAdjuster" />
## The check fairmq-modernize-nonnamespaced-types
The tool has one check, `fairmq-modernize-nonnamespaced-types` ([ModernizeNonNamespacedTypes.h](/source/fairmq/tidy/ModernizeNonNamespacedTypes.h/#L20-L69)). It finds each place in the code that names a type through a `using` alias with these two properties:
- The qualified name of the alias contains `::FairMQ`. This is true for a global alias like `FairMQDevice`, and for an alias in a namespace or a class.
- The aliased type, as Clang prints it, starts with `fair::mq::`.
<Snippet file="fairmq/tidy/ModernizeNonNamespacedTypes.h" start="finder.addMatcher(" end="&fCallback);" />
For each place, the check prints a warning with a fix-it hint. The hint replaces the alias with the aliased type, for example `FairMQDevice` with `fair::mq::Device`. The check does not find `typedef` declarations, only `using` aliases. The tool does not change your files.
### Names that the check finds
With Clang 18, the check finds these aliases of the FairMQ headers. The second column is the text of the fix-it hint.
| Alias | Fix-it replacement | Declared in |
| --- | --- | --- |
| `FairMQChannel` | `fair::mq::Channel` | `Channel.h` |
| `FairMQChannelMap` | `fair::mq::ChannelMap` | `Device.h` |
| `FairMQDevice` | `fair::mq::Device` | `Device.h` |
| `FairMQMessage` | `fair::mq::Message` | `Message.h` |
| `FairMQMessagePtr` | `fair::mq::MessagePtr` | `Message.h` |
| `FairMQParts` | `fair::mq::Parts` | `Parts.h` |
| `FairMQPoller` | `fair::mq::Poller` | `Poller.h` |
| `FairMQPollerPtr` | `fair::mq::PollerPtr` | `Poller.h` |
| `FairMQProgOptions` | `fair::mq::ProgOptions` | `ProgOptionsFwd.h` |
| `FairMQSocket` | `fair::mq::Socket` | `Socket.h` |
| `FairMQSocketPtr` | `fair::mq::SocketPtr` | `Socket.h` |
| `FairMQTransportFactory` | `fair::mq::TransportFactory` | `TransportFactory.h` |
| `FairMQTransportFactoryError` | `fair::mq::TransportFactoryError` | `TransportFactory.h` |
| `FairMQRegionEvent` | `fair::mq::RegionEvent` | `UnmanagedRegion.h` |
| `FairMQRegionInfo` | `fair::mq::RegionInfo` | `UnmanagedRegion.h` |
| `FairMQRegionBlock` | `fair::mq::RegionBlock` | `UnmanagedRegion.h` |
| `FairMQRegionCallback` | `fair::mq::RegionCallback` | `UnmanagedRegion.h` |
| `FairMQRegionBulkCallback` | `fair::mq::RegionBulkCallback` | `UnmanagedRegion.h` |
| `FairMQRegionEventCallback` | `fair::mq::RegionEventCallback` | `UnmanagedRegion.h` |
| `FairMQUnmanagedRegion` | `fair::mq::UnmanagedRegion` | `UnmanagedRegion.h` |
| `FairMQUnmanagedRegionPtr` | `fair::mq::UnmanagedRegionPtr` | `UnmanagedRegion.h` |
| `FairMQRegionConfig` | `fair::mq::RegionConfig` | `UnmanagedRegion.h` |
| `FairMQDevicePtr` | `fair::mq::Device *` | `runFairMQDevice.h` |
`FairMQDevicePtr` is not deprecated, but the check finds it. The fix-it gives a raw pointer. The new `getDevice()` of `<fairmq/runDevice.h>` returns a `std::unique_ptr` instead. See [Replace runFairMQDevice.h](/guides/migrate-names/#replace-runfairmqdeviceh).
### Names that the check does not find
Replace these deprecated names by hand. The compiler warns for them. See [Move from the FairMQ* names](/guides/migrate-names/).
| Name | Replacement | Why the check does not find it |
| --- | --- | --- |
| `fairmq_free_fn` | `fair::mq::FreeFn` | The name does not contain `FairMQ`. |
| `InputMsgCallback` | `fair::mq::InputMsgCallback` | The name does not contain `FairMQ`. |
| `InputMultipartCallback` | `fair::mq::InputMultipartCallback` | The name does not contain `FairMQ`. |
| `fair::mq::FairMQMemoryResource` | `fair::mq::MemoryResource` | The alias is written as `MemoryResource`, without `fair::mq::`. Clang 18 does not print the namespace. |
| `<FairMQDevice.h>` and the other old headers | `<fairmq/Device.h>` and so on | The check looks at types, not at `#include` lines. |
| Deprecated functions, for example `Parts::AtRef()` | See the migration guide | The check looks at type names only. |
### Output
The tool writes its output to the standard error stream. Each finding has a warning line, the source line, a marker under the alias, and the fix-it hint:
```txt
src/mydevice.cxx:3:25: warning: Modernize non-namespaced type 'FairMQDevice' with 'fair::mq::Device'. [fairmq-modernize-nonnamespaced-types]
3 | class MyDevice : public FairMQDevice
| ^~~~~~~~~~~~
| fair::mq::Device
```
- For an alias of a template type, the message adds the full type, for example `'fair::mq::MessagePtr' (aka 'unique_ptr<Message>')`.
- With Clang 18, the tool prints most findings two times at the same location. A name before `::`, for example `FairMQDevice::Foo()`, appears one time.
- A finding in a header shows the path of the header. The tool reports it for each source file that includes the header, also for headers in system include directories.
- The last line counts the warnings, for example `10 warnings generated.`
- With `--extra-arg=-fdiagnostics-parseable-fixits`, Clang adds a machine-readable line for each fix-it:
```txt
fix-it:"src/mydevice.cxx":{3:25-3:37}:"fair::mq::Device"
```
The line gives the file, the range to replace (`line:column-line:column`, the end column is after the last character), and the new text.
## Build fairmq-tidy
Set the CMake option `BUILD_TIDY_TOOL` (default `OFF`) when you configure FairMQ:
```sh
cmake -S FairMQ -B build -DBUILD_TIDY_TOOL=ON
cmake --build build
```
The option needs these packages ([FairMQDependencies.cmake](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/FairMQDependencies.cmake)):
| Package | Why |
| --- | --- |
| LLVM | `find_package(LLVM)`. The tool links the shared library target `LLVM`. |
| Clang | `find_package(Clang)`. The tool links the shared library target `clang-cpp`. |
| CLI11 | `find_package(CLI11)` is required. The tool does not use it yet. |
| FairLogger 1.6.0 or newer, Boost 1.66 or newer (not 1.88) | CMake looks for them for `BUILD_FAIRMQ` or `BUILD_TIDY_TOOL`. |
If CMake does not find LLVM or Clang, add their installation prefix to `CMAKE_PREFIX_PATH`. The [fairmq/tidy/CMakeLists.txt](https://github.com/FairRootGroup/FairMQ/blob/dev/fairmq/tidy/CMakeLists.txt) builds the executable `fairmq-tidy` with C++17.
With `BUILD_TIDY_TOOL=ON`, the installation also contains:
- `bin/fairmq-tidy`, exported as the imported target `FairMQ::fairmq-tidy`. CMake installs the exported targets only with `BUILD_FAIRMQ=ON` (the default).
- `share/fairmq/cmake/FairMQTidy.cmake`, the CMake module with [`fairmq_target_tidy()`](#the-cmake-function-fairmq_target_tidy). The directory is `${CMAKE_INSTALL_DATADIR}/fairmq/cmake`.
- The package component `tidy_tool`.
To check the code of FairMQ itself, also set `-DRUN_FAIRMQ_TIDY=ON`. FairMQ then calls `fairmq_target_tidy()` for its library, its executables and its tests.
## Command line
```txt
fairmq-tidy [options] <source0> [... <sourceN>]
```
| Option | Description |
| --- | --- |
| `-p <build-path>` | The directory that contains `compile_commands.json`, for example the CMake build directory. Without `-p`, the tool looks for the file in all parent directories of the first source file. |
| `--extra-arg=<string>` | Append an argument to the compile command. Give the option several times for several arguments. |
| `--extra-arg-before=<string>` | Add an argument at the start of the compile command. |
| `--help`, `--help-list` | Print the options and stop. |
| `--version` | Print the version of LLVM and stop. |
The positional arguments are the source files to check. The tool looks each file up in the compilation database. An absolute path must point into the source tree of the build. A relative path must be relative to the current directory, and the current directory must be in the source tree. Without a source file, the tool does nothing.
If the tool finds no compilation database, it prints an error, then `Running without flags.`, and checks the files without compile flags. Then include paths are missing, and the tool can fail on the first `#include`.
## Exit codes
| Code | Meaning |
| --- | --- |
| `0` | The tool processed all files. Findings are warnings: they do not change the exit code. |
| `1` | The command line is not valid, or Clang reported an error for a file, for example a missing header. The tool prints `Error while processing <file>.` |
| `2` | No error, but the tool skipped at least one file without a compile command. It prints `Skipping <file>. Compile command not found.` |
If the database does not list a file, for example a header, Clang 18 takes the compile command of a similar file from the database. Clang then reads the appended `-Wno-everything` as a file name and prints `error: no such file or directory: '-Wno-everything'`. The tool still checks the file, shows the compiler warnings too, and returns `0`. With Clang 18, `Skipping …` comes when the database has no similar file, for example an empty database.
`runTool.cpp` returns `EXIT_FAILURE` when it cannot parse the command line. Otherwise it returns the result of `clang::tooling::ClangTool::run()`.
<Snippet file="fairmq/tidy/runTool.cpp" start="int main" />
## The CMake function fairmq_target_tidy
The module [`cmake/FairMQTidy.cmake`](https://github.com/FairRootGroup/FairMQ/blob/dev/cmake/FairMQTidy.cmake) defines one function:
```cmake
fairmq_target_tidy(TARGET <target> [EXTRA_ARGS <args>] [CLANG_EXECUTABLE <clang>])
```
| Argument | Description |
| --- | --- |
| `TARGET` | Required. A library or executable target. The function checks its sources with the extension `.cpp` or `.cxx`. |
| `EXTRA_ARGS` | Optional. One argument for the command line of `fairmq-tidy`, for example `--extra-arg=-DMY_MACRO`. The keyword takes one value: the function ignores more values after it. See the caution below. |
| `CLANG_EXECUTABLE` | Optional. The `clang` executable that gives the resource directory when the compiler is GCC. Default: the target `clang` if it exists, otherwise `clang` from `PATH`. |
To use the module in your project, find FairMQ with the component and include the module. The package configuration adds `share/fairmq/cmake` to `CMAKE_MODULE_PATH`:
```cmake
find_package(FairMQ REQUIRED COMPONENTS tidy_tool)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
include(FairMQTidy)
add_executable(mydevice mydevice.cxx)
target_link_libraries(mydevice PRIVATE FairMQ::FairMQ)
fairmq_target_tidy(TARGET mydevice)
```
The function does these things:
- If `CMAKE_EXPORT_COMPILE_COMMANDS` is off, it prints the author warning `CMAKE_EXPORT_COMPILE_COMMANDS is not enabled. Skipping.` and does nothing. It also skips with a warning if `TARGET` is missing or is not a target.
- If `CMAKE_CXX_COMPILER_ID` is `GNU`, it runs `clang -print-resource-dir` one time and keeps the result in the cache variable `fairmq_tidy_clang_resource_dir`. Then it adds `--extra-arg-before=-I<resource-dir>/include`, which gives Clang its own header directory.
- For each source file, it adds a custom command: `fairmq-tidy -p=${CMAKE_BINARY_DIR} [extra arguments] <source>`. The command runs in `CMAKE_CURRENT_SOURCE_DIR`. It writes the stamp file `<target>-<source>.fairmq-tidy` into `CMAKE_CURRENT_BINARY_DIR`.
- It adds the custom target `fairmq-tidy-<target>` to `ALL` (each `:` in the target name becomes `-`). So the normal build runs the check after it builds the target, and again each time the target changes.
During the build, CMake prints one line for each file, then the output of the tool:
```txt
[ 80%] fairmq-tidy: Analyzing source file 'mydevice.cxx' of target 'mydevice'
```
Findings do not stop the build. If `fairmq-tidy` returns `1` or `2`, the build fails.
:::caution[EXTRA_ARGS with more than one argument]
The function puts the extra arguments into a generator expression without quotes. If the value is a list of two or more arguments, for example `"--extra-arg=-DA;--extra-arg=-DB"`, CMake splits the expression, the command line is broken, and the build fails. With GCC, the function always adds one argument to the list. So with GCC, any `EXTRA_ARGS` value breaks the command. With other compilers, give at most one argument in `EXTRA_ARGS`.
:::
## Related pages
- [Check code with fairmq-tidy](/guides/fairmq-tidy/): the procedure for your project and for CI.
- [Move from the FairMQ* names](/guides/migrate-names/): all old names and their replacements.
- [CMake options and variables](/reference/cmake/): `BUILD_TIDY_TOOL` and the other options.
- [Use FairMQ in a CMake project](/start/cmake/): `find_package(FairMQ)` and the targets.

View File

@@ -0,0 +1,270 @@
---
title: 'Logging'
description: 'Log severities, verbosity, color and log files of a device, and how to change them at run time.'
sidebar:
order: 4
code: [fairmq/DeviceRunner.cxx, fairmq/ProgOptions.cxx, fairmq/PluginServices.h, fairmq/FairMQLogger.h, fairmq/StateMachine.cxx]
---
import OptionsTable from '../../../components/OptionsTable.astro';
import Snippet from '../../../components/Snippet.astro';
FairMQ logs with the library [FairLogger](https://github.com/FairRootGroup/FairLogger). This page shows the log
macro, the severities that FairMQ uses, and the options that control the console log and the log file.
## Write a log line
FairMQ needs FairLogger 1.6.0 or newer (`cmake/FairMQDependencies.cmake`). Write a log line with the macro
`LOG(severity)` and the operator `<<`:
<Snippet file="examples/1-1/sampler.cxx" start="bool ConditionalRun()" />
- `<fairmq/Device.h>` includes `<fairlogger/Logger.h>`. Thus the code of a device can use `LOG()` without an
include.
- In other files, include `<fairlogger/Logger.h>`.
- The old header `<fairmq/FairMQLogger.h>` gives the compiler warning
`Deprecated header: Use <fairlogger/Logger.h> instead`. Replace it with `<fairlogger/Logger.h>`.
## Severities
The option `--severity` names these severities, from the most lines to the fewest:
| Severity | FairMQ uses it for | Example from the code |
| --- | --- | --- |
| `trace` | Internal steps of the device and of the plugins. | `device notified on new state: BINDING` |
| `debug` | Details of the setup: plugins, transports, channels and the configuration. | `Attached channel data[0] to tcp://*:5555 (bind) (push)` |
| `info` | Normal messages of FairMQ and of your device. | `fair::mq::Device running...` |
| `state` | State changes of the state machine. | `IDLE ---> INITIALIZING DEVICE` |
| `warn` | Problems that do not stop the device. | `No channels created after finishing initialization` |
| `error` | Errors, for example an exception that ends the device. | `Uncaught exception reached the top of main: …` |
| `fatal` | FairMQ does not use it. | |
A severity shows its own lines and the lines of all severities after it in the table. For example, `--severity debug`
shows all lines of the table except `trace`. The value `nolog` turns the console log off. FairLogger still prints the
`fatal` lines.
FairLogger knows more severities, for example `debug1` to `debug4`, `detail`, `important`, `alarm` and `critical`.
FairMQ does not use them. For a name that FairLogger does not know, it logs
`Unknown severity setting: '…', setting to default 'info'.` and uses `info`.
### The severity state
The state machine logs each change of state with the severity `state`
([StateMachine.cxx](/source/fairmq/StateMachine.cxx/#L191-L219)). The key `c` of the interactive control mode also
logs the current state with this severity. Thus `--severity state` shows the states, the warnings and the errors,
without the `info` lines. The state lines are in [Device states](/concepts/states/#log-lines).
## Set the log with options
`DeviceRunner` reads these options after it parses the command line. Thus they work for all devices that start with
`runDevice.h`.
<OptionsTable groups={['Logging']} id="log" />
- With `--severity ""` (default), the device does not set the console severity. The default of FairLogger then
applies.
- The environment variable `FAIRMQ_SEVERITY` replaces the value of `--severity`.
- `--verbosity` sets the fields of each log line. The help text names `veryhigh`, `high`, `medium` (default) and
`low`. See [The verbosity](#the-verbosity).
- `--color false` removes the colors from the console log.
- `--help` and `--print-options` print to the standard output, without the logger. The log options have no effect on
them.
This command starts the sink with the debug lines on the console:
```sh
FAIRMQ_SEVERITY=debug fairmq-sink --id sink1 \
--channel-config name=data,type=pull,method=bind,address=tcp://*:5555
```
### The verbosity
The verbosity sets the prefix of each log line. A space separates the prefix from the message.
| `--verbosity` | Prefix |
| --- | --- |
| `low` | `[SEVERITY]` |
| `medium` (default) | `[HH:MM:SS][SEVERITY]` |
| `high` | `[process][HH:MM:SS][SEVERITY]` |
| `veryhigh` | `[process][HH:MM:SS.uuuuuu][SEVERITY][file:line:function]` |
`process` is the name of the program, for example `fairmq-sink`. `uuuuuu` are the microseconds. The severity is in
upper case, for example `INFO` or `STATE`. With `medium`, a state line looks so:
```txt
[14:03:21][STATE] IDLE ---> INITIALIZING DEVICE
```
FairLogger also knows `verylow` (no prefix) and `user1` to `user4`. For a name that FairLogger does not know, it logs
`Unknown verbosity setting: '…', setting to default 'low'.` and uses `low`. The log file gets the same prefix as the
console, without colors.
## Write the log to a file
`--log-to-file <name>` starts a file log with the severity of `--file-severity` (default `debug`). The device gives
`<name>` to `fair::Logger::InitFileSink()`, and FairLogger creates the file.
With `--log-to-file`, the console log is off: the device sets the console severity to `nolog`. Thus `--severity`,
`FAIRMQ_SEVERITY` and `--color` have no effect.
```sh
fairmq-sink --id sink1 \
--channel-config name=data,type=pull,method=bind,address=tcp://*:5555 \
--log-to-file sink1 --file-severity trace
```
## Change the log at run time
`DeviceRunner` subscribes to the log properties ([DeviceRunner.cxx](/source/fairmq/DeviceRunner.cxx/#L82-L101)).
When a plugin or the device changes one of them, the new value applies at once:
| Property | Type | Effect of a change |
| --- | --- | --- |
| `severity` | `std::string` | Sets the console severity. |
| `file-severity` | `std::string` | Sets the severity of the log file. |
| `verbosity` | `std::string` | Sets the verbosity. |
| `color` | `bool` | Turns the console colors on or off. |
| `log-to-file` | `std::string` | Starts a file log with the value of `file-severity`. The console log stays on. |
Give the type to `SetProperty()`. The subscription gets only values of the type in the table:
```cpp
// In a plugin: show the debug lines from now on.
SetProperty<std::string>("severity", "debug");
```
`SetProperty("severity", "debug")` stores a `const char*`, and the severity does not change. See
[Read and change properties at run time](/guides/control-from-code/#read-and-change-properties-at-run-time).
### Keys and plugin functions
- In the interactive mode of the control plugin, the key `k` moves the console severity one step up, toward `fatal`.
The key `l` moves it one step down, toward `trace`. The steps include the severities that FairMQ does not use. At the
end of the list, the next step goes to the other end. The keys `n` and `m` move the verbosity one step up or
down in the same way. FairLogger prints the list of values and marks the new value with `<` and `>`. See
[Keys of the interactive mode](/concepts/plugins/#keys-of-the-interactive-mode).
- A plugin can call [`CycleLogConsoleSeverityUp()`](/api/fair/mq/Plugin/#CycleLogConsoleSeverityUp),
[`CycleLogConsoleSeverityDown()`](/api/fair/mq/Plugin/#CycleLogConsoleSeverityDown),
[`CycleLogVerbosityUp()`](/api/fair/mq/Plugin/#CycleLogVerbosityUp) and
[`CycleLogVerbosityDown()`](/api/fair/mq/Plugin/#CycleLogVerbosityDown). The keys call these functions.
- The keys and the `CycleLog` functions change FairLogger directly. The properties `severity` and `verbosity` keep
their old values.
### Set the log in your code
Your code can call the functions of FairLogger directly. The [custom-controller](/examples/custom-controller/)
example sets the console severity before the runner starts:
<Snippet file="examples/custom-controller/main.cxx" start="DeviceRunner runner(argc, argv);" end="fair::Logger::SetConsoleSeverity" />
With the default `--severity ""`, `DeviceRunner` keeps this value. A program without `DeviceRunner` reads no log
options and subscribes to no log properties. It must call these functions itself. FairMQ calls these functions of
`fair::Logger`:
| Function | FairMQ uses it for |
| --- | --- |
| `SetConsoleSeverity()` | `--severity`, `FAIRMQ_SEVERITY` and `nolog` for a log file. |
| `SetFileSeverity()` | A change of `file-severity` at run time. |
| `InitFileSink(severity, name)` | `--log-to-file`. |
| `SetVerbosity()` | `--verbosity`. |
| `SetConsoleColor()` | `--color`. |
| `CycleConsoleSeverityUp()`, `CycleConsoleSeverityDown()`, `CycleVerbosityUp()`, `CycleVerbosityDown()` | The `CycleLog` functions of the plugin API. |
### Add a sink
A custom sink is a function of your code that gets each log line, for example to send the lines to a log server.
FairLogger adds and removes sinks with static functions of `fair::Logger`. FairMQ does not call them. FairLogger is
not part of this repository: these declarations are from `logger/Logger.h` of FairLogger. They are the same in
FairLogger 1.6.0, the minimum version of FairMQ, and in the current source of
[FairLogger](https://github.com/FairRootGroup/FairLogger):
```cpp
static void AddCustomSink(const std::string& key, Severity severity,
std::function<void(const std::string& content, const LogMetaData& metadata)> sink);
static void AddCustomSink(const std::string& key, const std::string& severityStr,
std::function<void(const std::string& content, const LogMetaData& metadata)> sink);
static void RemoveCustomSink(const std::string& key);
```
- `key` is the name of the sink. `RemoveCustomSink()` takes the same name.
- The sink gets the lines of `severity` and of all more severe levels. It always gets the `fatal` lines. For a
severity name that FairLogger does not know, it logs `Unknown severity setting: '…', setting to default 'info'.`
and uses `info`.
- `content` is the text of the line, without the prefix of the verbosity.
- `metadata` is a `fair::LogMetaData` with the fields `timestamp` (`std::time_t`), `us` (the microseconds of the
second, `std::chrono::microseconds`), `process_name`, `file`, `line`, `func`, `severity_name` and `severity`
(`fair::Severity`). The text fields are `std::string` in FairLogger 1.6.0 and `std::string_view` in the current
source. Copy them into a `std::string` if your sink keeps them.
- The sink is independent of the console and of the log file. `--severity nolog` and `--log-to-file` do not change
it.
- For a key that exists, `AddCustomSink()` of the current FairLogger throws `std::runtime_error`. For a key that does
not exist, `RemoveCustomSink()` also throws `std::runtime_error`. FairLogger 1.6.0 prints a message to the standard
output instead and changes nothing.
This program adds a sink for the warnings and errors before the runner starts, and removes it after the runner is
destroyed. `MyDevice` is your device class:
```cpp
#include <fairlogger/Logger.h>
#include <fairmq/DeviceRunner.h>
#include <iostream>
#include <memory>
#include <string>
int main(int argc, char* argv[])
{
fair::Logger::AddCustomSink("my-sink", "warn",
[](const std::string& content, const fair::LogMetaData& metadata) {
std::cerr << "sink: " << metadata.severity_name << " " << content << '\n';
});
int result = 0;
{
fair::mq::DeviceRunner runner(argc, argv);
runner.AddHook<fair::mq::hooks::InstantiateDevice>([](fair::mq::DeviceRunner& r) {
r.fDevice = std::make_unique<MyDevice>();
});
result = runner.RunWithExceptionHandlers();
} // destroys the plugins and the device
fair::Logger::RemoveCustomSink("my-sink");
return result;
}
```
Rules for a sink:
- FairLogger calls the sink at the end of each `LOG()` statement, in the thread of the statement. It holds a global
mutex of the logger during the call. Thus only one sink call runs at a time. A slow sink also delays the other
threads that write to a sink or to the log file. Keep the sink short.
- Do not write log lines in the sink. A `LOG()` statement in the sink that goes to a sink or to the log file locks
the mutex again, and the thread waits forever.
- `AddCustomSink()` locks the mutex, but `RemoveCustomSink()` does not, and the `LOG()` statements read the list of
sinks without the mutex. Add and remove sinks only while no other thread logs. With `runDevice.h`, add the sink in
`getDevice()` or in `addCustomOptions()`. Both run in the main thread before the plugins and the state machine
start.
- A sink that stays until the end of the process must not use objects that are destroyed before, for example your
device.
- A sink with a low severity, for example `trace`, makes FairLogger prepare the lines of this severity for each
`LOG()` statement, also when the console does not show them.
## Other programs
- `fairmq-shmmonitor` has its own option `--severity` (default `info`), and no colors. See
[fairmq-shmmonitor](/tools/shmmonitor/).
- FairMQ prints the output of `--print-channels` and `--version` with `LOGV(info, verylow)`.
`LOGV(severity, verbosity)` is a log macro of FairLogger that also takes a verbosity.
:::caution[Known defect]
For `--print-channels` and `--version`, `DeviceRunner` sets the console severity to `nolog`. Thus both options print
nothing. See the disabled tests `DeviceRunner.DISABLED_PrintChannels` and `DeviceRunner.DISABLED_Version` in
`test/device/_runner.cxx`.
:::
## Related pages
- [Command-line options](/reference/options/): all options of a device.
- [Device states](/concepts/states/): the state machine and its log lines.
- [Plugins and control](/concepts/plugins/): the control plugin and its keys.
- [Control a device from code](/guides/control-from-code/): change properties at run time.

View File

@@ -0,0 +1,179 @@
---
title: 'fairmq-shmmonitor'
description: 'Monitor, inspect and clean up shared memory sessions.'
sidebar:
order: 1
code: [fairmq/shmem/runMonitor.cxx, fairmq/shmem/Monitor.h, fairmq/shmem/Monitor.cxx]
---
import OptionsTable from '../../../components/OptionsTable.astro';
`fairmq-shmmonitor` shows the status of the shared memory sessions of FairMQ, removes their
objects, and watches them. Devices with `--shm-monitor true` start it as a daemon, so that the
memory of a session is removed when all its devices stop.
The build makes `fairmq-shmmonitor` in the directory `fairmq` of the build tree. The installation
puts it into the `bin` directory. For the concepts, see [Monitor and clean up](/shmem/monitor/) and
[Sessions and segments](/shmem/sessions/).
## Common tasks
| Task | Command |
| --- | --- |
| Show the status of the session `default` | `fairmq-shmmonitor` |
| Show the status of a session | `fairmq-shmmonitor --session run42` |
| Show the status of all sessions in `/dev/shm/` | `fairmq-shmmonitor --list-all` |
| Show the shmId of a session | `fairmq-shmmonitor --get-shmid --session run42` |
| [Remove all objects of a session](/shmem/monitor/#clean-up-after-a-crash) | `fairmq-shmmonitor --cleanup --session run42` |
| Show the status every second, with keys | `fairmq-shmmonitor -i -v --session run42` |
| Watch a session and clean up after a crash | `fairmq-shmmonitor -m --session run42` |
| Show the messages (debug mode) | `fairmq-shmmonitor --debug --session run42` |
`--session` gives the shmId for the current user. To select the objects directly, give
`--shmid` with the hexadecimal shmId, for example `--shmid eca859e3`.
## Options
<OptionsTable file="fairmq/shmem/runMonitor.cxx" id="mon" />
Notes on the options:
- The bool options take a value, but they do not need it: `--cleanup` is the same as
`--cleanup true`.
- `--user-id` has an effect only with `--get-shmid`. The other commands use the user ID of the
process.
- `--interval` sets the time in ms between two status outputs in the interactive mode.
- `--timeout` is the heartbeat timeout in ms of the monitor mode.
- `--daemonize` has an effect only together with `--monitor`.
- `--verbose` has an effect only together with `--daemonize` and `--monitor`. The daemon then writes
its log at the severity `trace` to a file. The help text names the file
`fairmq-shmmonitor_<timestamp>`.
- `--severity` sets the severity of the console log (default `info`).
## How the tool selects the mode
The tool checks the options in this order and runs the first command that applies
([runMonitor.cxx](/source/fairmq/shmem/runMonitor.cxx/#L122-L189)):
| Order | Option | What the tool does |
| --- | --- | --- |
| 1 | `--help` | Prints the options and stops. |
| 2 | `--get-shmid` | Prints the shmId of `--session` and stops. |
| 3 | `--cleanup` | Removes all objects of the session, also the monitor mutex. Stops. |
| 4 | `--reset-content` | Experimental. Removes all allocations in the managed segments. Stops. |
| 5 | `--debug` | Prints the messages of the session. Needs a build with `FAIRMQ_DEBUG_MODE`. Stops. |
| 6 | `--list-all` | Prints the status of all sessions in `--list-all-path`. Stops. |
| 7 | `--view` without `--interactive`, or no mode option | Prints the status of the session one time and stops. |
| 8 | `--interactive` | Runs the interactive mode. |
| 9 | `--monitor` | Runs the monitor mode. |
All steps after step 2, except `--list-all`, use `--shmid` or the shmId of `--session`. With
`--view`, the interactive mode does not take the monitor mutex. `--view` together with `--monitor`
and without `--interactive` prints the status one time.
## Status output
The status of a session has this form. The tool writes a time stamp before the first line. The
sample shows it without the time stamp:
```txt
shm id: <shmId>, session: <name>, creator id: <user ID>, devices: <n>, managed segments:
[<segment ID>]: total: <bytes>, msgs: <n>, free: <bytes>, used: <bytes>
[m]: total: <bytes>, free: <bytes>, used: <bytes>
unmanaged regions:
[<region ID>]: alive, size: <bytes>, rcCountSegment size: <bytes>, free: <bytes>, used: <bytes>
```
The lines `unmanaged regions` show only if the session has regions. If the session does not exist,
the tool prints `No segments found.` See [Monitor and clean up](/shmem/monitor/#one-session) for
the meaning of the fields.
`--list-all` prints `Found shmid '<shmId>':` before the status of each session. For each file in the
directory that does not belong to FairMQ, it prints "The file '…' does not belong to FairMQ,
skipping...". For an empty directory, it prints `directory "/dev/shm/" is empty.`
`--get-shmid` prints one of these lines:
```txt
shmem id for session 'run42' and current user id 1000 is: 65d285cd
shmem id for session 'run42' and user id 1001 is: <shmId>
```
## Interactive mode
`fairmq-shmmonitor -i` prints the list of keys, then the status of the session every `--interval`
ms (default 1000 ms) and after each key. The keys work without Enter. The tool switches off the
echo of the terminal while it runs.
| Key | What it does |
| --- | --- |
| `x` | Removes the objects of the session. In view mode (`-i -v`), the tool prints "cannot close because in view only mode". |
| `b` | Prints the messages of the session. Needs a build with `FAIRMQ_DEBUG_MODE`. |
| `h` | Prints the list of keys. |
| `q` | Stops the tool. |
Other keys print `[<key>] --> invalid input.`
Without `-v`, the interactive mode takes the monitor mutex `sem.fmq_<shmId>_ms`. Then devices with
`--shm-monitor true` do not start a daemon for the session. The interactive mode does not remove
memory after a heartbeat timeout. Use `-i -v` to look at a session that a daemon watches.
## Monitor mode
`fairmq-shmmonitor -m` watches one session. It takes the monitor mutex `sem.fmq_<shmId>_ms`, so that
only one monitor runs for each session.
- It reads the heartbeat of the devices every 200 ms, and it looks for the management segment
every 100 ms.
- If the heartbeat does not change for more than `--timeout` ms (default 5000), it removes all
objects of the session.
- With `--self-destruct` (`-x`), it stops after the session is gone. It also stops if it finds no
session within 2 × `--timeout` after its start.
- Without `-x`, it runs until it receives `SIGINT` or `SIGTERM`.
- With `--clean-on-exit` (`-e`), it removes the objects of the session when it stops.
- When it stops, it removes its mutex.
The log shows the start and the cleanup:
```txt
Starting shared memory monitor for session: "run42" (shm id: 65d285cd)...
no heartbeats since over 5000 milliseconds, cleaning...
Cleaning up for shared memory id '65d285cd'...
```
If a monitor runs already for the shmId, the tool writes an error and stops with the exit code 0:
```txt
fairmq-shmmonitor for shm id 65d285cd is already running. Try `fairmq-shmmonitor --cleanup --shmid 65d285cd`
```
In the interactive mode, the text ends with `, or run in view-only mode (-v)`.
### The daemon of the devices
A device with `--shm-monitor true` starts the tool with these options, if no monitor runs for the
session:
```sh
fairmq-shmmonitor -x -m --shmid <shmId> -d -t 2000
```
`-d` makes the process a daemon: it forks, the first process stops with the exit code 0, and the
daemon writes its console output to `/dev/null`. See
[Automatic cleanup with `--shm-monitor`](/shmem/monitor/#automatic-cleanup-with---shm-monitor).
## Exit codes
| Code | When |
| --- | --- |
| `0` | The command is complete, or the tool stopped normally. Also when a monitor runs already for the shmId. |
| `1` | The daemon cannot fork, cannot start a new session, or cannot change to the directory `/`. |
| `2` | An exception, for example an unknown option. The tool prints "Unhandled Exception reached the top of main: …, application will now exit". |
## Related pages
- [Monitor and clean up](/shmem/monitor/): when memory stays and how to remove it.
- [Sessions and segments](/shmem/sessions/): the shmId and the objects of a session.
- [Tune and debug](/shmem/tuning/#debug-mode): debug mode and the list of messages.
- [Command-line options](/reference/options/): `--shm-monitor` of the devices.
- [Test your devices](/guides/test-devices/): a test script that removes the shared memory of each run.

View File

@@ -0,0 +1,55 @@
// Descriptions of the command-line options in ASD-STE100 style.
// Names, types and default values come from the code (scripts/options.mjs).
// The build fails if an entry here names an option that the code does not have.
export const deviceOptionTexts = {
help: 'Print the help and stop.',
version:
'Print the versions of FairMQ and of the device, and stop. Known defect: the output is empty, because the device sets the console severity to <code>nolog</code> first.',
severity:
'Console log severity: trace, debug, info, state, warn, error, fatal or nolog. Empty: keep the default of FairLogger. The environment variable <code>FAIRMQ_SEVERITY</code> overrides this option.',
'file-severity': 'Log severity for the log file of <code>--log-to-file</code>.',
verbosity: 'Log verbosity: veryhigh, high, medium or low. It sets the fields in each log line.',
color: 'Use colors in the console log.',
'log-to-file': 'Write the log to this file. The console log is then off.',
'print-options': 'Print all options in a machine-readable format (<code>option:value:type:description</code>) and stop.',
id: 'Device ID. A JSON configuration uses it as the key of the device, unless you set <code>--config-key</code>.',
'io-threads': 'Number of I/O threads of the ZeroMQ context. The zeromq and the shmem transports use it.',
transport: 'Default transport of the device: <code>zeromq</code> or <code>shmem</code>. A channel can set its own transport.',
'network-interface':
'Network interface for a bind sub-channel without an address, for example <code>eth0</code>. The device binds to the IP of this interface on an automatic port. <code>default</code>: the interface of the default route.',
'init-timeout':
'Time in seconds to connect all channels in the state CONNECTING. If an address is not valid yet, the device tries again every 50 ms and reads the address property again. After this time, the device goes to the state ERROR.',
'print-channels':
'Print the channels that the device registers with <code>RegisterChannelEndpoint()</code>, as <code>name:min:max</code> (the minimum and maximum number of sub-channels), and stop. Known defect: the output is empty, because the device sets the console severity to <code>nolog</code> first.',
'shm-segment-size': 'Size of the managed shared memory segment in bytes. The default is 2 GiB. Only the device that creates the segment sets its size.',
'shm-allocation': 'Allocation algorithm of the segment: <code>rbtree_best_fit</code> or <code>simple_seq_fit</code>. A device that opens an existing segment uses the algorithm of that segment and logs a warning if it differs.',
'shm-segment-id': 'Experimental. ID of the segment for new messages. Devices of one session can use several segments.',
shmid: 'Experimental. Use this shmId instead of the one that FairMQ makes from the session name and the user ID. The value is a decimal number. The object names contain it as a hexadecimal number with at least 8 digits: <code>--shmid 1</code> gives <code>00000001</code>.',
'shm-mlock-segment': 'Lock the segment in RAM after the device opens or creates it.',
'shm-mlock-segment-on-creation': 'Lock the segment in RAM only when this device creates it.',
'shm-zero-segment': 'Write zeros to the free memory of the segment after the device opens or creates it.',
'shm-zero-segment-on-creation': 'Write zeros to the free memory of the segment only when this device creates it.',
'shm-throw-bad-alloc':
'Throw <code>fair::mq::MessageBadAlloc</code> when an allocation in the segment fails. <code>false</code>: try again every <code>--bad-alloc-attempt-interval</code> ms, until the allocation succeeds or a transition interrupts the transport. <code>false</code> overrides <code>--bad-alloc-max-attempts</code>. A message that is larger than the segment always throws.',
'shm-metadata-msg-size':
'Size in bytes of the ZeroMQ message that carries the metadata. The transport pads the metadata to this size. A value below the size of the metadata (40 bytes for one message) has no effect.',
'bad-alloc-max-attempts':
'Number of allocation attempts before <code>MessageBadAlloc</code>. -1: no limit. The device always makes one attempt, so 0 and 1 have the same effect.',
'bad-alloc-attempt-interval': 'Time between two allocation attempts in ms.',
'shm-monitor': 'Start <code>fairmq-shmmonitor</code> for the session, if no monitor runs for it. The device looks for the executable in <code>FAIRMQ_PATH</code> and <code>PATH</code>.',
'shm-no-cleanup': 'Keep the shared memory when the last device of the session stops.',
rate: 'Maximum rate of the <code>ConditionalRun()</code> loop in Hz. 0: no limit.',
session: 'Session name. Devices of the same user with the same session use the same shared memory.',
'config-key': 'Key of the device in the JSON file. Use it instead of the device ID.',
'mq-config': 'JSON file with the configuration of the devices and their channels. If you also give <code>--channel-config</code>, the device uses only <code>--mq-config</code>.',
'channel-config':
'Channel configuration as a list of <code>key=value</code> pairs, separated by commas. Give one list for each channel. Each <code>address</code> in a list adds a sub-channel. Several lists can follow one <code>--channel-config</code>. A list can start with <code>&lt;name&gt;:</code> instead of <code>name=&lt;name&gt;</code>.',
control:
'Controller of the state machine: <code>static</code>, <code>dynamic</code> (also <code>interactive</code> and <code>external</code>), <code>gui</code> or <code>none</code>. An unknown value gives <code>static</code>, with an error in the log.',
'catch-signals': 'Handle SIGINT and SIGTERM: 1 (yes) or 0 (no). The first signal starts the shutdown sequence. A second SIGINT aborts the process.',
plugin:
'Load these plugins, in this sequence. For the file <code>libfairmq-plugin-example.so</code>, the name is <code>example</code>. Put <code>p:</code> before the name of a prelinked plugin.',
'plugin-search-path':
'Directories to search for plugins, in this order. Put <code>&lt;</code> before a path to put it at the start of the list, or <code>&gt;</code> to put it at the end. If a plugin is not in these directories, the device tries the system lookup of libraries (system directories, RUNPATH, <code>LD_LIBRARY_PATH</code>).',
};

20
docs/src/env.d.ts vendored Normal file
View File

@@ -0,0 +1,20 @@
declare module 'virtual:fairmq/data' {
/** Version and commit of the FairMQ checkout that the site is built from. */
export const build: {
commit: string;
commitShort: string;
date: string;
branch: string;
release: string;
ahead: number;
label: string;
unreleased: boolean;
repo: string;
};
/** Absolute paths, resolved when the site build starts. */
export const paths: {
docsDir: string;
repoRoot: string;
xmlDir: string;
};
}

33
docs/src/lib/families.mjs Normal file
View File

@@ -0,0 +1,33 @@
// Groups the members of a class by their name, for the filter on the API pages.
export const FAMILY_ORDER = [
'Construction',
'Types',
'Get',
'Set',
'Transfer',
'Create',
'Events',
'Other',
'Operators',
'Constants',
'Data',
'Friends',
];
export function family(m, owner) {
const n = m.name;
if (m.kind === 'friend') return 'Friends';
if (m.kind === 'typedef' || m.kind === 'enum') return 'Types';
if (m.kind === 'variable') return m.static ? 'Constants' : 'Data';
if (m.kind === 'function') {
if (n === owner.short || n === `~${owner.short}` || /^operator\s*=$/.test(n)) return 'Construction';
if (/^operator/.test(n)) return 'Operators';
if (/^(Get|Is|Has|Are|Can)[A-Z_]/.test(n)) return 'Get';
if (/^(Set|Update|Change|Reset|Add|Remove)[A-Z_]/.test(n)) return 'Set';
if (/^(Send|Receive)/.test(n)) return 'Transfer';
if (/^(New|Create|Make)[A-Z_]/.test(n)) return 'Create';
if (/^(Subscribe|Unsubscribe|On[A-Z])/.test(n)) return 'Events';
}
return 'Other';
}

93
docs/src/lib/model.mjs Normal file
View File

@@ -0,0 +1,93 @@
// Shared access to the API model for the generated pages.
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { paths, build } from 'virtual:fairmq/data';
import { getModel } from '../../scripts/api.mjs';
export const base = import.meta.env.BASE_URL.replace(/\/$/, '');
export function model() {
return getModel({ xmlDir: paths.xmlDir, repoRoot: paths.repoRoot, base });
}
let theme;
export function codeTheme() {
theme ??= JSON.parse(readFileSync(path.join(paths.docsDir, 'src/styles/code-theme.json'), 'utf8'));
return theme;
}
/** A path without the site base, for Starlight sidebar links (Starlight adds the base). */
export const noBase = (href) => (href.startsWith(base + '/') ? href.slice(base.length) : href);
/** GitHub link to a file and line at the commit of the build. */
export function githubUrl(file, line) {
const ref = build.commit && build.commit !== 'unknown' ? build.commit : 'dev';
return `${build.repo}/blob/${ref}/${file}${line ? `#L${line}` : ''}`;
}
const KIND_LETTER = { class: 'C', struct: 'S', union: 'U', enum: 'E', namespace: 'N' };
/** Sidebar for the API pages: one group per namespace with its types and enums. */
export function apiSidebar() {
const m = model();
const groups = [];
const namespaces = m.namespaces().sort((a, b) => a.name.localeCompare(b.name));
for (const ns of namespaces) {
const inNs = (t) =>
t.name.startsWith(ns.name + '::') &&
!namespaces.some((o) => o !== ns && o.name.length > ns.name.length && t.name.startsWith(o.name + '::'));
const entries = [
...m
.types()
.filter(inNs)
.map((t) => ({ rel: t.name.slice(ns.name.length + 2), link: noBase(t.url), kind: KIND_LETTER[t.kind] })),
...ns.visible.filter((e) => e.kind === 'enum').map((e) => ({ rel: e.name, link: noBase(e.page), kind: 'E' })),
];
// Nested types follow their parent, indented.
const key = (rel) => rel.split('::').map((s) => s.toLowerCase());
entries.sort((a, b) => {
const ka = key(a.rel);
const kb = key(b.rel);
for (let i = 0; i < Math.min(ka.length, kb.length); i++) if (ka[i] !== kb[i]) return ka[i] < kb[i] ? -1 : 1;
return ka.length - kb.length;
});
const items = entries.map((e) => {
const depth = e.rel.split('::').length - 1;
return {
label: e.rel.split('::').pop(),
link: e.link,
attrs: { 'data-kind': e.kind, class: depth ? 'fmq-mono fmq-nested' : 'fmq-mono', title: `${ns.name}::${e.rel}` },
};
});
groups.push({
label: ns.name,
collapsed: ns.name !== 'fair::mq',
items: [{ label: 'Namespace overview', link: noBase(ns.url), attrs: { 'data-kind': 'N' } }, ...items],
});
}
return [{ label: 'API reference', link: '/api/' }, ...groups];
}
/** Sidebar for the source pages: one group per directory. */
export function sourceSidebar() {
const m = model();
const dirs = new Map();
for (const f of m.sourceFiles) {
const dir = path.posix.dirname(f);
if (!dirs.has(dir)) dirs.set(dir, []);
dirs.get(dir).push({ label: path.posix.basename(f), link: `/source/${f}/`, attrs: { class: 'fmq-mono' } });
}
return [
{ label: 'Source browser', link: '/source/' },
...[...dirs].map(([dir, items]) => ({ label: `${dir}/`, collapsed: dir !== 'fairmq', items })),
];
}
/** Docs pages that name a file in their `code` front matter. A page that names Foo.cxx also
* describes Foo.h, and the other way round. */
export function guidesForFile(entries, file) {
const stem = (f) => f.replace(/\.(h|cxx)$/, '');
return entries
.filter((e) => (e.data.code ?? []).some((c) => c === file || stem(c) === stem(file)))
.map((e) => ({ label: e.data.title, link: `/${e.id}/` }));
}

41
docs/src/lib/nav.ts Normal file
View File

@@ -0,0 +1,41 @@
// Sections of the site, for the header and the page titles.
const labels: Record<string, string> = {
start: 'Start',
concepts: 'Concepts',
guides: 'Guides',
shmem: 'Shared memory',
tools: 'Tools',
reference: 'Reference',
examples: 'Examples',
project: 'Project',
};
/** The sidebar section of a docs page, from its id (for example "concepts/channels"). */
export function sectionLabel(id: string): string | undefined {
return labels[id.split('/')[0]];
}
const generated = /^\/(api|source|reference)\//;
export const sections = [
{
label: 'Docs',
href: '/start/overview/',
match: (path: string, base: string) => {
const p = path.slice(base.length);
return p !== '/' && p !== '' && !generated.test(p);
},
},
{
label: 'Reference',
href: '/reference/options/',
match: (path: string, base: string) => path.startsWith(`${base}/reference/`),
},
{ label: 'API', href: '/api/', match: (path: string, base: string) => path.startsWith(`${base}/api/`) },
{
label: 'Source',
href: '/source/',
match: (path: string, base: string) => path.startsWith(`${base}/source/`),
},
];

91
docs/src/pages/404.astro Normal file
View File

@@ -0,0 +1,91 @@
---
// Not found. The old site had Doxygen pages under /FairMQ/latest/ and /FairMQ/v1.x.y/. A script
// sends these URLs to the new API and source pages.
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import { model, base } from '../lib/model.mjs';
const m = model();
// Doxygen compound id (without the kind prefix) → new URL, without the base.
const types: Record<string, string> = {};
const strip = (u: string) => (u.startsWith(base + '/') ? u.slice(base.length) : u);
for (const t of m.types()) types[t.id.replace(/^(class|struct|union)/, '')] = strip(t.url);
for (const ns of m.namespaces()) types['ns:' + ns.id.replace(/^namespace/, '')] = strip(ns.url);
for (const { e } of m.namespaceEnums()) types[e.qualified.replace(/::/g, '_1_1')] = strip(e.page);
// The built-in devices had the names FairMQBenchmarkSampler, FairMQSink …
for (const d of ['BenchmarkSampler', 'Merger', 'Multiplier', 'Proxy', 'Sink', 'Splitter']) types['FairMQ' + d] = '/tools/builtin-devices/';
// Doxygen file id → source page.
const files: Record<string, string> = {};
for (const f of m.files.values()) if (m.sourceFiles.includes(f.path)) files[f.id] = `/source/${f.path}/`;
const data = JSON.stringify({ t: types, f: files });
---
<StarlightPage frontmatter={{ title: 'Page not found', description: 'This page does not exist.', pagefind: false, editUrl: false, lastUpdated: false, eyebrow: 'Error 404' }}>
<div data-moved hidden>
<p>This page moved. Your browser goes to the new page now.</p>
<p><a data-moved-link href="#">Go to the new page</a></p>
</div>
<div data-missing>
<p>The page does not exist. The documentation has a new structure: the old Doxygen pages are now the <a href={`${base}/api/`}>API reference</a> and the <a href={`${base}/source/`}>source browser</a>.</p>
<p>Use the search at the top of the page, or start from one of these pages:</p>
<ul>
<li><a href={`${base}/`}>Home</a></li>
<li><a href={`${base}/start/overview/`}>Overview</a></li>
<li><a href={`${base}/reference/options/`}>Command-line options</a></li>
<li><a href={`${base}/api/`}>API reference</a></li>
</ul>
</div>
<script type="application/json" id="fmq-moved" set:html={data} />
</StarlightPage>
<script>
// Old URLs: /FairMQ/latest/classfair_1_1mq_1_1Device.html, /FairMQ/v1.4.33/Device_8h_source.html …
const base = import.meta.env.BASE_URL.replace(/\/$/, '');
const { t, f } = JSON.parse(document.getElementById('fmq-moved')!.textContent!);
const target = (() => {
const rel = decodeURIComponent(location.pathname.slice(base.length)).replace(/^\/+/, '');
const m = /^(?:latest|v\d+(?:\.\d+)*)(?:\/(.*))?$/.exec(rel);
if (!m) return null;
const page = (m[1] ?? '').replace(/\.html$/, '');
if (page === '' || page === 'index' || page === 'pages') return '/';
if (/^(annotated|classes|hierarchy|inherits|namespaces|namespacemembers.*|functions.*|graph_legend)$/.test(page)) return '/api/';
if (page === 'files' || page.startsWith('dir_')) return '/source/';
const type = /^(?:class|struct|union)(.+?)(?:-members|__coll__graph|__inherit__graph)?$/.exec(page);
if (type) {
const id = type[1];
if (t[id]) return t[id];
// FairMQDevice → fair::mq::Device, FairMQChannel_1_1… → fair::mq::Channel::…
const legacy = /^FairMQ(.+)$/.exec(id);
if (legacy && t['fair_1_1mq_1_1' + legacy[1]]) return t['fair_1_1mq_1_1' + legacy[1]];
// A nested type that is gone: go to its parent.
const parts = id.split('_1_1');
while (parts.length > 1) {
parts.pop();
const p = parts.join('_1_1');
if (t[p]) return t[p];
}
return '/api/';
}
const ns = /^namespace(.+)$/.exec(page);
if (ns) return t['ns:' + ns[1]] ?? '/api/';
const file = /^(.+?)(?:_source|__incl|__dep__incl)?$/.exec(page)![1];
if (f[file]) return f[file];
// Match by file name if the directory changed: FairMQChannel_8h, ofi_2Context_8h …
const name = file.split('_2').pop()!;
const hit = Object.keys(f).find((k) => k === name || k.endsWith('_2' + name));
if (hit) return f[hit];
const legacy = /^FairMQ(.+)$/.exec(name);
if (legacy) {
const hit2 = Object.keys(f).find((k) => k === legacy[1] || k.endsWith('_2' + legacy[1]));
if (hit2) return f[hit2];
}
return '/source/';
})();
if (target) {
// The anchors of the Doxygen pages do not exist on the new pages.
const url = base + target;
document.querySelector<HTMLElement>('[data-moved]')!.hidden = false;
document.querySelector<HTMLElement>('[data-missing]')!.hidden = true;
document.querySelector<HTMLAnchorElement>('[data-moved-link]')!.href = url;
location.replace(url);
}
</script>

View File

@@ -0,0 +1,365 @@
---
// API pages: one page for each public class, struct, union, namespace and namespace enum.
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import { getCollection } from 'astro:content';
import Member from '../../components/api/Member.astro';
import CopyButton from '../../components/CopyButton.astro';
import { model, base, apiSidebar, githubUrl, guidesForFile, noBase } from '../../lib/model.mjs';
import { family, FAMILY_ORDER } from '../../lib/families.mjs';
import '../../styles/api.css';
export function getStaticPaths() {
const m = model();
const slug = (url: string) => noBase(url).replace(/^\/api\//, '').replace(/\/$/, '');
return [
...m.types().map((t: any) => ({ params: { slug: slug(t.url) }, props: { kind: 'type', id: t.id } })),
...m.namespaces().map((ns: any) => ({ params: { slug: slug(ns.url) }, props: { kind: 'namespace', id: ns.id } })),
...m.namespaceEnums().map(({ e }: any) => ({ params: { slug: slug(e.page) }, props: { kind: 'enum', id: e.id } })),
];
}
const { kind, id } = Astro.props;
const m = model();
const docs = await getCollection('docs');
const strip = (html: string) => html.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim();
const SECTION_ORDER: [string, string][] = [
['public-type', 'Types'],
['public-func', 'Functions'],
['public-static-func', 'Static functions'],
['public-static-attrib', 'Static data members'],
['public-attrib', 'Data members'],
['protected-type', 'Protected types'],
['protected-func', 'Protected functions'],
['protected-static-func', 'Protected static functions'],
['protected-static-attrib', 'Protected static data members'],
['protected-attrib', 'Protected data members'],
['friend', 'Friends'],
['related', 'Related functions'],
];
const NS_SECTIONS: [string, string][] = [
['typedef', 'Type aliases'],
['func', 'Functions'],
['var', 'Variables'],
];
const slugify = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
let page: any;
if (kind === 'type') {
const rec = m.compounds.get(id);
const sections = SECTION_ORDER.map(([key, label]) => ({
id: slugify(label),
label,
members: rec.visible.filter((x: any) => x.section === key),
})).filter((s) => s.members.length > 0);
const known = new Set(SECTION_ORDER.map(([k]) => k));
const otherMembers = rec.visible.filter((x: any) => !known.has(x.section));
if (otherMembers.length) sections.push({ id: 'other-members', label: 'Other members', members: otherMembers });
const nested = rec.inner.map((i: string) => m.compounds.get(i)).filter((c: any) => c && c.public);
const headings: any[] = [];
if (nested.length) headings.push({ depth: 2, slug: 'nested-types', text: 'Nested types' });
for (const s of sections) {
headings.push({ depth: 2, slug: s.id, text: s.label });
for (const x of s.members) if (x.overload === 1) headings.push({ depth: 3, slug: x.anchor, text: x.name });
}
const families = new Map<string, number>();
for (const x of rec.visible) {
const f = family(x, rec);
families.set(f, (families.get(f) ?? 0) + 1);
}
page = {
rec,
title: rec.short,
titleKind: rec.templ ? `${rec.kind} template` : rec.kind,
eyebrow: `API · ${rec.scope}`,
searchTitle: rec.name,
file: rec.file,
line: rec.line,
include: rec.include,
sections,
nested,
headings,
families: FAMILY_ORDER.filter((f) => families.has(f)).map((f) => [f, families.get(f)]),
total: rec.visible.length,
};
} else if (kind === 'namespace') {
const rec = m.compounds.get(id);
const types = m
.types()
.filter((t: any) => t.scope === rec.name)
.sort((a: any, b: any) => a.short.localeCompare(b.short, 'en', { sensitivity: 'base' }));
const enums = rec.visible.filter((x: any) => x.kind === 'enum');
const sections = NS_SECTIONS.map(([key, label]) => ({
id: slugify(label),
label,
members: rec.visible.filter((x: any) => x.section === key && x.kind !== 'enum'),
})).filter((s) => s.members.length > 0);
const subs = rec.innerNamespaces.map((i: string) => m.compounds.get(i)).filter((c: any) => c && c.public);
const headings: any[] = [];
if (subs.length) headings.push({ depth: 2, slug: 'namespaces', text: 'Namespaces' });
if (types.length) headings.push({ depth: 2, slug: 'types', text: 'Classes and structs' });
if (enums.length) headings.push({ depth: 2, slug: 'enums', text: 'Enums' });
for (const s of sections) {
headings.push({ depth: 2, slug: s.id, text: s.label });
for (const x of s.members) if (x.overload === 1) headings.push({ depth: 3, slug: x.anchor, text: x.name });
}
page = { rec, title: rec.name, titleKind: 'namespace', eyebrow: 'API', searchTitle: rec.name, types, enums, sections, subs, headings };
} else {
const e = m.members.get(id);
const ns = m.compounds.get(e.owner);
page = {
e,
ns,
title: e.name,
titleKind: e.strong ? 'enum class' : 'enum',
eyebrow: `API · ${ns.name}`,
searchTitle: e.qualified,
file: e.file,
line: e.line,
include: m.publicHeaders.has(e.file) ? e.file : null,
headings: [{ depth: 2, slug: 'values', text: 'Values' }],
};
}
const descRec = page.rec ?? page.e;
const description = strip(descRec.brief || '') || `${page.titleKind} ${page.searchTitle}`;
const guides = page.file ? guidesForFile(docs, page.file) : [];
const srcHref = page.file ? `${base}/source/${page.file}/#L${page.line}` : null;
---
<StarlightPage
frontmatter={{
title: page.title,
description,
eyebrow: page.eyebrow,
titleKind: page.titleKind,
searchTitle: page.searchTitle,
code: page.file ? [page.file] : [],
guides,
tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 3 },
}}
sidebar={apiSidebar()}
headings={page.headings}
>
{
page.file && (
<div class="api-meta">
{page.include && (
<span class="api-inc">
<code>#include &lt;{page.include}&gt;</code>
<CopyButton text={`#include <${page.include}>`} label="Copy the include line" />
</span>
)}
<a href={srcHref}>
{page.file}:{page.line}
</a>
<a href={githubUrl(page.file, page.line)}>GitHub ↗</a>
</div>
)
}
{
kind === 'type' && (
<>
{page.rec.templ && (
<pre class="mem-sig api-templ">
<code set:html={`${page.rec.templ}\n<span class="k">${page.rec.kind}</span> <b>${page.rec.short}</b>`} />
</pre>
)}
{(page.rec.bases.length > 0 || page.rec.derived.length > 0) && (
<dl class="api-rel">
{page.rec.bases.length > 0 && (
<>
<dt>Inherits from</dt>
<dd set:html={page.rec.bases.map((b: any) => `<code>${b.html}</code>`).join(', ')} />
</>
)}
{page.rec.derived.length > 0 && (
<>
<dt>Inherited by</dt>
<dd set:html={page.rec.derived.map((b: any) => `<code>${b.html}</code>`).join(', ')} />
</>
)}
</dl>
)}
{page.rec.brief && <p class="api-lead" set:html={page.rec.brief} />}
{page.rec.detail && <div class="api-detail" set:html={page.rec.detail} />}
{!page.rec.documented && <p class="mem-none">No comment in the header yet.</p>}
{page.nested.length > 0 && (
<>
<h2 id="nested-types">Nested types</h2>
<ul class="api-list">
{page.nested.map((c: any) => (
<li>
<a href={c.url}>
<code>{c.short}</code>
</a>
<span class="fmq-badge">{c.kind}</span>
{c.brief && <span class="api-list-brief" set:html={c.brief} />}
</li>
))}
</ul>
</>
)}
{page.total > 10 && (
<div class="api-filter" data-api-filter role="group" aria-label="Filter members">
<input type="search" placeholder="Filter members" aria-label="Filter members by name" />
<div class="api-chips">
<button type="button" aria-pressed="true" data-f="">
All <b>{page.total}</b>
</button>
{page.families.map(([f, n]: any) => (
<button type="button" aria-pressed="false" data-f={f}>
{f} <b>{n}</b>
</button>
))}
</div>
<p class="api-count" aria-live="polite" />
</div>
)}
{page.sections.map((s: any) => (
<section class="api-sec" data-sec>
<h2 id={s.id}>{s.label}</h2>
{s.members.map((x: any) => (
<Member m={x} owner={page.rec} />
))}
</section>
))}
</>
)
}
{
kind === 'namespace' && (
<>
{page.rec.brief && <p class="api-lead" set:html={page.rec.brief} />}
{page.rec.detail && <div class="api-detail" set:html={page.rec.detail} />}
{page.subs.length > 0 && (
<>
<h2 id="namespaces">Namespaces</h2>
<ul class="api-list">
{page.subs.map((c: any) => (
<li>
<a href={c.url}>
<code>{c.name}</code>
</a>
</li>
))}
</ul>
</>
)}
{page.types.length > 0 && (
<>
<h2 id="types">Classes and structs</h2>
<ul class="api-list">
{page.types.map((c: any) => (
<li>
<a href={c.url}>
<code>{c.short}</code>
</a>
<span class="fmq-badge">{c.kind}</span>
{c.brief && <span class="api-list-brief" set:html={c.brief} />}
</li>
))}
</ul>
</>
)}
{page.enums.length > 0 && (
<>
<h2 id="enums">Enums</h2>
<ul class="api-list">
{page.enums.map((e: any) => (
<li>
<a href={e.page}>
<code>{e.name}</code>
</a>
<span class="fmq-badge">{e.strong ? 'enum class' : 'enum'}</span>
{e.brief && <span class="api-list-brief" set:html={e.brief} />}
</li>
))}
</ul>
</>
)}
{page.sections.map((s: any) => (
<section class="api-sec">
<h2 id={s.id}>{s.label}</h2>
{s.members.map((x: any) => (
<Member m={x} />
))}
</section>
))}
</>
)
}
{
kind === 'enum' && (
<>
<pre class="mem-sig">
<code set:html={page.e.sigHtml} />
</pre>
{page.e.brief && <p class="api-lead" set:html={page.e.brief} />}
{page.e.detail && <div class="api-detail" set:html={page.e.detail} />}
<h2 id="values">Values</h2>
<div class="doc-table">
<table class="enum-values">
<thead>
<tr>
<th>Enumerator</th>
<th>Value</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{page.e.values.map((v: any) => (
<tr id={v.anchor}>
<td>
<code>{v.name}</code>
</td>
<td>{v.init ? <code>{v.init}</code> : <span class="muted">—</span>}</td>
<td set:html={v.html || '<span class="muted">—</span>'} />
</tr>
))}
</tbody>
</table>
</div>
</>
)
}
</StarlightPage>
<script>
// Member filter: by name family and by text.
for (const root of document.querySelectorAll<HTMLElement>('[data-api-filter]')) {
const input = root.querySelector('input')!;
const chips = [...root.querySelectorAll<HTMLButtonElement>('button[data-f]')];
const count = root.querySelector('.api-count')!;
const mems = [...document.querySelectorAll<HTMLElement>('.mem')];
let fam = '';
const apply = () => {
const q = input.value.trim().toLowerCase();
let shown = 0;
for (const el of mems) {
const ok = (!fam || el.dataset.family === fam) && (!q || (el.dataset.name ?? '').includes(q));
el.hidden = !ok;
if (ok) shown++;
}
for (const sec of document.querySelectorAll<HTMLElement>('[data-sec]')) {
sec.hidden = !sec.querySelector('.mem:not([hidden])');
}
count.textContent = fam || q ? `${shown} of ${mems.length} members` : '';
};
input.addEventListener('input', apply);
for (const c of chips) {
c.addEventListener('click', () => {
fam = c.dataset.f ?? '';
for (const o of chips) o.setAttribute('aria-pressed', String(o === c));
apply();
});
}
}
</script>

View File

@@ -0,0 +1,64 @@
---
// API overview: the public namespaces with their types and enums.
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import { model, base, apiSidebar } from '../../lib/model.mjs';
import '../../styles/api.css';
const m = model();
const namespaces = m.namespaces().sort((a: any, b: any) => a.name.localeCompare(b.name));
const groups = namespaces
.map((ns: any) => ({
ns,
id: ns.name.replace(/::/g, '-'),
types: m
.types()
.filter((t: any) => t.scope === ns.name)
.sort((a: any, b: any) => a.short.localeCompare(b.short, 'en', { sensitivity: 'base' })),
enums: ns.visible.filter((x: any) => x.kind === 'enum'),
}))
.filter((g: any) => g.types.length || g.enums.length);
const count = m.types().length;
---
<StarlightPage
frontmatter={{
title: 'API reference',
description: 'The public classes, structs, enums and functions of FairMQ, generated from the installed headers.',
tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 2 },
}}
sidebar={apiSidebar()}
headings={groups.map((g: any) => ({ depth: 2, slug: g.id, text: g.ns.name }))}
>
<p class="api-lead">
These pages show the {count} public types of FairMQ and their members. Doxygen reads the installed headers at each
build of this site, so the signatures are always current. The text comes from the comments in the headers.
</p>
<p>
Each member links to its line in the <a href={`${base}/source/`}>source browser</a>. Use the search (<kbd>Ctrl</kbd> <kbd>K</kbd>)
to find a class or a member by name.
</p>
{
groups.map((g: any) => (
<>
<h2 id={g.id}>
<a href={g.ns.url}>
<code>{g.ns.name}</code>
</a>
</h2>
<ul class="api-list">
{[...g.types, ...g.enums.map((e: any) => ({ ...e, short: e.name, url: e.page, kind: e.strong ? 'enum class' : 'enum' }))]
.sort((a: any, b: any) => a.short.localeCompare(b.short, 'en', { sensitivity: 'base' }))
.map((c: any) => (
<li>
<a href={c.url}>
<code>{c.short}</code>
</a>
<span class="fmq-badge">{c.kind}</span>
{c.brief ? <span class="api-list-brief" set:html={c.brief} /> : <span class="api-list-brief muted">No comment yet.</span>}
</li>
))}
</ul>
</>
))
}
</StarlightPage>

View File

@@ -0,0 +1,142 @@
---
// Source browser: one page for each C++ file in fairmq/.
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import { getCollection } from 'astro:content';
import { paths } from 'virtual:fairmq/data';
import { model, base, codeTheme, sourceSidebar, githubUrl, guidesForFile } from '../../lib/model.mjs';
import { renderSourceFile } from '../../../scripts/source.mjs';
import '../../styles/source.css';
export function getStaticPaths() {
return model().sourceFiles.map((f: string) => ({ params: { path: f } }));
}
const file = Astro.params.path as string;
const m = model();
const out = await renderSourceFile(m, file, { theme: codeTheme(), repoRoot: paths.repoRoot });
const fileRec = m.files.get(file);
const defined = (fileRec?.defines ?? []).filter((c: any) => c.public);
const isPublic = m.publicHeaders.has(file);
const docs = await getCollection('docs');
const guides = guidesForFile(docs, file);
const name = file.split('/').pop();
---
<StarlightPage
frontmatter={{
title: name,
description: `Source of ${file} in FairMQ.`,
eyebrow: `Source · ${file.split('/').slice(0, -1).join('/')}/`,
titleKind: file.endsWith('.h') ? (isPublic ? 'public header' : 'header') : 'source',
searchTitle: file,
tableOfContents: false,
guides,
}}
sidebar={sourceSidebar()}
headings={[]}
>
{
defined.length > 0 && (
<p class="src-defines">
Defines {defined.map((c: any) => `${c.kind} ${c.name}`).join(', ')}.
</p>
)
}
{
guides.length > 0 && (
<p class="src-guides">
Described in{' '}
{guides.map((g: any, i: number) => (
<>
{i > 0 && ', '}
<a href={`${base}${g.link}`}>{g.label}</a>
</>
))}
.
</p>
)
}
<div class="src-head not-content">
<span class="src-path">{file}</span>
<span class="src-info">{out.lines} lines · C++</span>
<span class="src-acts">
{
defined.map((c: any) => (
<a class="fmq-badge mark" href={c.url}>
API: {c.short}
</a>
))
}
<a class="fmq-badge" href={githubUrl(file)}>GitHub ↗</a>
</span>
</div>
<div class="src-code not-content" data-pagefind-ignore>
<pre><code set:html={out.html} /></pre>
<div class="src-card" role="tooltip" hidden></div>
</div>
<script type="application/json" id="src-symbols" set:html={JSON.stringify(out.symbols).replace(/</g, '\\u003c')} />
</StarlightPage>
<script>
// Line marks from the URL (#L10 or #L10-L20), shift-click to mark a range,
// and a card with the symbol on hover or focus.
const code = document.querySelector<HTMLElement>('.src-code');
if (code) {
const rows = () => code.querySelectorAll<HTMLElement>('.row.hl');
const mark = () => {
rows().forEach((r) => r.classList.remove('hl'));
const m = /^#L(\d+)(?:-L(\d+))?$/.exec(location.hash);
if (!m) return;
const a = Number(m[1]);
const b = Number(m[2] ?? m[1]);
for (let i = Math.min(a, b); i <= Math.max(a, b); i++) document.getElementById(`L${i}`)?.classList.add('hl');
};
mark();
addEventListener('hashchange', mark);
code.addEventListener('click', (e) => {
const ln = (e.target as HTMLElement).closest<HTMLAnchorElement>('a.ln');
if (!ln || !e.shiftKey) return;
const cur = /^#L(\d+)/.exec(location.hash);
if (!cur) return;
e.preventDefault();
const to = ln.getAttribute('href')!.slice(2);
history.replaceState(null, '', `#L${cur[1]}-L${to}`);
mark();
});
const symbols = JSON.parse(document.getElementById('src-symbols')?.textContent ?? '[]');
const card = code.querySelector<HTMLElement>('.src-card')!;
let timer: number | undefined;
const esc = (s: string) => s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!);
const show = (a: HTMLElement) => {
const s = symbols[Number(a.dataset.s)];
if (!s) return;
clearTimeout(timer);
card.innerHTML = `<span class="k">${esc(s.k)}</span><b>${esc(s.n)}</b>${s.s && s.s !== s.n ? `<code>${esc(s.s)}</code>` : ''}<span class="l">${esc(s.l)}</span>`;
card.hidden = false;
const box = code.getBoundingClientRect();
const r = a.getBoundingClientRect();
const left = Math.max(8, Math.min(r.left - box.left, box.width - card.offsetWidth - 8));
card.style.left = `${left}px`;
card.style.top = `${r.bottom - box.top + code.scrollTop + 6}px`;
};
const hide = () => {
timer = window.setTimeout(() => (card.hidden = true), 120);
};
code.addEventListener('pointerover', (e) => {
const a = (e.target as HTMLElement).closest<HTMLElement>('a.sym');
if (a) show(a);
});
code.addEventListener('pointerout', (e) => {
if ((e.target as HTMLElement).closest('a.sym')) hide();
});
code.addEventListener('focusin', (e) => {
const a = (e.target as HTMLElement).closest<HTMLElement>('a.sym');
if (a) show(a);
});
code.addEventListener('focusout', hide);
addEventListener('keydown', (e) => {
if (e.key === 'Escape') card.hidden = true;
});
}
</script>

View File

@@ -0,0 +1,67 @@
---
// Source browser overview: all C++ files in fairmq/, by directory.
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { paths } from 'virtual:fairmq/data';
import { model, base, sourceSidebar } from '../../lib/model.mjs';
import '../../styles/source.css';
const m = model();
const dirs = new Map<string, any[]>();
let total = 0;
for (const f of m.sourceFiles) {
const dir = path.posix.dirname(f);
const lines = readFileSync(path.join(paths.repoRoot, f), 'utf8').replace(/\n$/, '').split('\n').length;
total += lines;
const defined = (m.files.get(f)?.defines ?? []).filter((c: any) => c.public);
if (!dirs.has(dir)) dirs.set(dir, []);
dirs.get(dir)!.push({ f, name: path.posix.basename(f), lines, defined, pub: m.publicHeaders.has(f) });
}
const id = (d: string) => d.replace(/\//g, '-');
---
<StarlightPage
frontmatter={{
title: 'Source browser',
description: 'All C++ files of the FairMQ library, with line anchors and links to the API pages.',
tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 2 },
}}
sidebar={sourceSidebar()}
headings={[...dirs.keys()].map((d) => ({ depth: 2, slug: id(d), text: `${d}/` }))}
>
<p class="api-lead">
Every C++ file of <code>fairmq/</code> as a page: {m.sourceFiles.length} files with {total.toLocaleString('en')} lines.
Doxygen finds the symbols. A symbol links to its API page, or to the line where it is defined.
</p>
<p>
Each line has an anchor, for example <a href={`${base}/source/fairmq/Channel.h/#L36`}><code>Channel.h/#L36</code></a>. Shift-click a
second line number to mark a range. A <span class="fmq-badge mark">public</span> header is installed with FairMQ.
</p>
{
[...dirs].map(([dir, list]) => (
<>
<h2 id={id(dir)}>
<code>{dir}/</code>
</h2>
<ul class="src-list">
{list.map((x) => (
<li>
<a href={`${base}/source/${x.f}/`}>
<code>{x.name}</code>
</a>
<span class="src-lines">{x.lines}</span>
<span class="src-meta">
{x.pub && <span class="fmq-badge mark">public</span>}
{x.defined.slice(0, 4).map((c: any) => (
<a href={c.url}>{c.short}</a>
))}
{x.defined.length > 4 && <span class="muted">+{x.defined.length - 4}</span>}
</span>
</li>
))}
</ul>
</>
))
}
</StarlightPage>

323
docs/src/styles/api.css Normal file
View File

@@ -0,0 +1,323 @@
/* API reference pages. */
.api-meta {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 1.25rem;
font: 500 0.8125rem/1.4 var(--fmq-font-mono);
margin-top: 0.25rem;
}
.api-meta a {
color: var(--fmq-link);
}
.api-inc {
display: inline-flex;
align-items: center;
gap: 0.5rem;
border: 1px solid var(--fmq-rule);
background: var(--fmq-paper-2);
border-radius: 4px;
padding: 0.2rem 0.25rem 0.2rem 0.6rem;
}
.sl-markdown-content .api-inc code {
background: none;
border: 0;
padding: 0;
font-size: 0.8125rem;
color: var(--fmq-ink);
}
.sl-markdown-content .api-lead {
font-size: 1.125rem;
line-height: 1.55;
color: var(--fmq-ink-2);
max-width: 64ch;
}
.api-rel {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: 0.25rem 1rem;
font-size: 0.9375rem;
}
.sl-markdown-content .api-rel dt {
font: 600 0.7rem/1.9 var(--fmq-font-body);
font-stretch: 88%;
letter-spacing: 0.1em;
text-transform: uppercase;
color: var(--fmq-ink-3);
}
.sl-markdown-content .api-rel dd {
margin: 0;
padding: 0;
}
.sl-markdown-content .api-rel :is(dt, dd) {
margin-top: 0 !important;
}
/* Filter */
.api-filter {
position: sticky;
top: calc(var(--sl-nav-height) + var(--sl-mobile-toc-height));
z-index: 2;
background: var(--fmq-paper);
border-bottom: 1px solid var(--fmq-rule);
padding: 0.75rem 0 0.6rem;
margin-top: 1.5rem;
}
.api-filter input {
width: min(100%, 20rem);
font: 400 0.9375rem var(--fmq-font-body);
color: var(--fmq-ink);
background: var(--fmq-paper-2);
border: 1px solid var(--fmq-rule-strong);
border-radius: 4px;
padding: 0.4rem 0.6rem;
}
.api-chips {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
margin-top: 0.5rem !important;
}
.api-chips button {
font: 500 0.8125rem/1 var(--fmq-font-body);
border: 1px solid var(--fmq-rule-strong);
border-radius: 3px;
background: var(--fmq-paper);
color: var(--fmq-ink-2);
padding: 0.35rem 0.55rem;
cursor: pointer;
}
.api-chips button b {
font: 500 0.75rem var(--fmq-font-mono);
color: var(--fmq-ink-3);
margin-inline-start: 0.2rem;
}
.api-chips button:hover {
border-color: var(--fmq-ink-3);
color: var(--fmq-ink);
}
.api-chips button[aria-pressed='true'] {
background: var(--fmq-saffron-tint);
border-color: var(--fmq-bar);
color: var(--fmq-ink);
}
.api-count {
font-size: 0.8125rem;
color: var(--fmq-ink-3);
min-height: 1.2em;
margin: 0.4rem 0 0 !important;
}
/* Sections and members */
.sl-markdown-content .api-sec > h2 {
font-size: 1.375rem;
margin-top: 2.25rem;
padding-bottom: 0.4rem;
border-bottom: 1px solid var(--fmq-rule-strong);
}
.mem {
border-bottom: 1px solid var(--fmq-rule);
padding: 1rem 0 1.1rem;
scroll-margin-top: 9rem;
}
.sl-markdown-content .mem > * + * {
margin-top: 0.55rem;
}
.mem-h {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.35rem 0.6rem;
}
.sl-markdown-content .mem-name {
font: 700 1.0625rem/1.3 var(--fmq-font-mono);
margin: 0;
letter-spacing: -0.01em;
scroll-margin-top: 10rem;
}
.sl-markdown-content .mem-name a {
color: var(--fmq-ink);
text-decoration: none;
}
.sl-markdown-content .mem-name a:hover {
text-decoration: underline;
}
.mem-src {
margin-inline-start: auto;
font: 500 0.75rem var(--fmq-font-mono);
}
.sl-markdown-content a.mem-src {
color: var(--fmq-ink-3);
}
.sl-markdown-content a.mem-src:hover {
color: var(--fmq-link);
}
.sl-markdown-content pre.mem-sig {
margin: 0.5rem 0 0;
padding: 0.6rem 0.85rem;
border: 1px solid var(--fmq-rule);
border-radius: 4px;
background: var(--fmq-paper-2);
font: 400 0.8125rem/1.6 var(--fmq-font-mono);
color: var(--fmq-ink);
white-space: pre-wrap;
overflow-wrap: anywhere;
overflow-x: auto;
}
.sl-markdown-content pre.mem-sig code {
all: unset;
font: inherit;
}
.mem-sig .k {
color: var(--fmq-accent-ink);
}
.mem-sig b {
font-weight: 700;
color: var(--fmq-ink);
}
.mem-sig a {
color: var(--fmq-link);
text-decoration: none;
}
.mem-sig a:hover {
text-decoration: underline;
}
.api-templ {
margin-top: 0.75rem !important;
}
.mem-brief,
.mem-detail p {
max-width: 70ch;
}
.sl-markdown-content .mem-params {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: 0.3rem 1rem;
font-size: 0.9375rem;
border-inline-start: 2px solid var(--fmq-rule);
padding-inline-start: 0.9rem;
}
.sl-markdown-content .mem-params dt,
.sl-markdown-content .mem-params dd {
margin: 0 !important;
padding: 0;
/* Long words like MessagePtr/Parts/vector<MessagePtr> must wrap on phones. */
overflow-wrap: anywhere;
}
.sl-markdown-content .mem-params dt {
font-weight: 500;
}
.mem-params dt.mem-ret {
font: 600 0.7rem/2 var(--fmq-font-body);
font-stretch: 88%;
letter-spacing: 0.1em;
text-transform: uppercase;
color: var(--fmq-ink-3);
}
.mem-pk {
font: 500 0.6875rem var(--fmq-font-body);
color: var(--fmq-ink-3);
margin-inline-start: 0.35rem;
}
.mem-none {
font-size: 0.875rem;
color: var(--fmq-ink-3);
font-style: italic;
}
.mem-see {
font-size: 0.9375rem;
}
.muted {
color: var(--fmq-ink-3);
}
/* Lists of types */
.sl-markdown-content ul.api-list {
list-style: none;
padding: 0;
border-top: 1px solid var(--fmq-rule);
}
.sl-markdown-content ul.api-list > li {
display: grid;
grid-template-columns: minmax(10rem, max-content) max-content minmax(0, 1fr);
gap: 0.25rem 0.75rem;
align-items: baseline;
padding: 0.5rem 0;
border-bottom: 1px solid var(--fmq-rule);
margin: 0 !important;
}
.sl-markdown-content ul.api-list > li::before {
display: none;
}
.sl-markdown-content ul.api-list code {
background: none;
border: 0;
padding: 0;
font-size: 0.875rem;
font-weight: 600;
}
.api-list-brief {
font-size: 0.9375rem;
color: var(--fmq-ink-2);
}
@media (max-width: 40rem) {
.sl-markdown-content ul.api-list > li {
grid-template-columns: max-content minmax(0, 1fr);
}
.api-list-brief {
grid-column: 1 / -1;
}
}
/* Tables and asides from header comments */
.doc-table {
overflow-x: auto;
}
.sl-markdown-content .enum-values td:first-child code {
font-weight: 600;
}
.sl-markdown-content .enum-values tr:target {
background: var(--fmq-saffron-tint);
}
.doc-aside {
border: 1px solid var(--fmq-rule);
border-inline-start: 3px solid var(--fmq-sky);
background: var(--fmq-paper-2);
border-radius: 4px;
padding: 0.6rem 0.85rem;
font-size: 0.9375rem;
}
.doc-aside.caution {
border-inline-start-color: var(--fmq-ruby);
}
.doc-aside > b {
display: block;
font: 600 0.7rem/1.4 var(--fmq-font-body);
font-stretch: 88%;
letter-spacing: 0.12em;
text-transform: uppercase;
color: var(--fmq-ink-2);
margin-bottom: 0.25rem;
}
.doc-aside > p {
margin: 0;
}
.sl-markdown-content pre.doc-code {
background: var(--fmq-code-bg);
color: var(--fmq-code-ink);
border: 1px solid var(--fmq-code-rule);
border-radius: 4px;
padding: 0.6rem 0.85rem;
font: 400 0.8125rem/1.6 var(--fmq-font-mono);
overflow-x: auto;
}
.doc-h {
font-weight: 650;
}
.mem[hidden],
.api-sec[hidden] {
display: none;
}

View File

@@ -0,0 +1,39 @@
{
"name": "fairmq-night",
"type": "dark",
"colors": {
"editor.background": "#22262d",
"editor.foreground": "#e6e8ec",
"editorLineNumber.foreground": "#7d8594",
"editorLineNumber.activeForeground": "#fabe5d",
"editor.selectionBackground": "#3a4150",
"editorGroupHeader.tabsBackground": "#22262d",
"tab.activeBackground": "#22262d",
"tab.activeForeground": "#e6e8ec",
"tab.inactiveForeground": "#9aa1ad",
"tab.activeBorderTop": "#fabe5d",
"titleBar.activeBackground": "#22262d",
"titleBar.activeForeground": "#e6e8ec",
"titleBar.border": "#353a44",
"panel.border": "#353a44"
},
"tokenColors": [
{ "scope": ["source", "variable", "variable.other", "variable.parameter", "meta.block", "meta.function-call"], "settings": { "foreground": "#e6e8ec" } },
{ "scope": ["comment", "punctuation.definition.comment", "comment.block.documentation"], "settings": { "foreground": "#8d96a5", "fontStyle": "italic" } },
{ "scope": ["keyword", "keyword.control", "keyword.other", "storage", "storage.type", "storage.modifier", "keyword.operator.new", "keyword.operator.delete", "keyword.operator.sizeof", "keyword.operator.cast", "keyword.operator.alignof", "keyword.operator.noexcept", "constant.language.this", "variable.language.this"], "settings": { "foreground": "#fabe5d" } },
{ "scope": ["entity.name.type", "entity.name.class", "entity.name.struct", "entity.name.namespace", "entity.name.scope-resolution", "support.type", "support.class", "entity.other.inherited-class", "storage.type.class.std", "entity.name.type.template", "support.type.property-name.json", "support.type.property-name"], "settings": { "foreground": "#8cc8ef" } },
{ "scope": ["entity.name.function", "support.function", "meta.function-call entity.name.function", "entity.name.function.preprocessor"], "settings": { "foreground": "#ffffff", "fontStyle": "bold" } },
{ "scope": ["string", "string.quoted", "punctuation.definition.string", "string.unquoted"], "settings": { "foreground": "#a8d99b" } },
{ "scope": ["constant.numeric", "constant.language", "constant.character", "constant.other", "keyword.other.unit"], "settings": { "foreground": "#f4a597" } },
{ "scope": ["meta.preprocessor", "keyword.control.directive", "punctuation.definition.directive", "meta.preprocessor.include", "keyword.control.import"], "settings": { "foreground": "#e5b3d3" } },
{ "scope": ["meta.preprocessor.include string", "string.quoted.other.lt-gt.include"], "settings": { "foreground": "#a8d99b" } },
{ "scope": ["punctuation", "keyword.operator", "meta.brace", "punctuation.separator", "punctuation.terminator"], "settings": { "foreground": "#c3c8d1" } },
{ "scope": ["support.function.builtin.shell", "entity.name.command.shell", "support.function.builtin"], "settings": { "foreground": "#ffffff", "fontStyle": "bold" } },
{ "scope": ["variable.other.normal.shell", "variable.other.special.shell", "punctuation.definition.variable.shell"], "settings": { "foreground": "#f4a597" } },
{ "scope": ["constant.other.option", "constant.other.option.dash.shell"], "settings": { "foreground": "#8cc8ef" } },
{ "scope": ["markup.heading", "entity.name.section"], "settings": { "foreground": "#fabe5d", "fontStyle": "bold" } },
{ "scope": ["markup.bold"], "settings": { "fontStyle": "bold" } },
{ "scope": ["markup.italic"], "settings": { "fontStyle": "italic" } },
{ "scope": ["invalid"], "settings": { "foreground": "#f4a597" } }
]
}

201
docs/src/styles/source.css Normal file
View File

@@ -0,0 +1,201 @@
/* Source browser pages. */
.src-head {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.4rem 1rem;
margin-top: 0.5rem;
padding: 0.55rem 0.75rem;
border: 1px solid var(--fmq-code-rule);
border-bottom: 0;
border-radius: 6px 6px 0 0;
background: var(--fmq-code-bg);
color: var(--fmq-code-ink);
font: 500 0.8125rem/1.3 var(--fmq-font-mono);
}
.src-path {
color: var(--fmq-code-ink);
font-weight: 600;
}
.src-info {
color: var(--fmq-code-dim);
}
.src-acts {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
margin-inline-start: auto;
}
.src-head .fmq-badge {
color: var(--fmq-code-ink);
border-color: var(--fmq-stage-line);
}
.src-head .fmq-badge.mark {
color: var(--fmq-saffron);
border-color: var(--fmq-saffron);
}
.src-head .fmq-badge:hover {
border-color: var(--fmq-code-ink);
}
.src-defines,
.src-guides {
font-size: 0.875rem;
color: var(--fmq-ink-2);
}
.sl-markdown-content .src-head + .src-code,
.src-head + .src-code {
margin-top: 0 !important;
}
.src-code {
position: relative;
border: 1px solid var(--fmq-code-rule);
border-radius: 0 0 6px 6px;
background: var(--fmq-code-bg);
overflow-x: auto;
margin-top: 0 !important;
}
.src-code pre {
margin: 0;
padding: 0.6rem 0;
font: 400 0.8125rem/1.6 var(--fmq-font-mono);
color: var(--fmq-code-ink);
tab-size: 4;
background: none;
border: 0;
min-width: max-content;
}
.src-code code {
font: inherit;
background: none;
border: 0;
padding: 0;
}
.src-code .row {
display: block;
padding-inline-end: 1rem;
scroll-margin-top: 8rem;
}
.src-code .row:target,
.src-code .row.hl {
background: rgb(250 190 93 / 0.14);
box-shadow: inset 3px 0 0 var(--fmq-saffron);
}
.src-code .ln {
display: inline-block;
width: 4.5ch;
margin-inline-end: 1.25ch;
padding-inline-end: 0.5ch;
text-align: end;
color: #6b7380;
text-decoration: none;
user-select: none;
}
.src-code .ln:hover {
color: var(--fmq-saffron);
}
.src-code .lc {
white-space: pre;
}
.src-code .t-k { color: var(--fmq-c-kw); }
.src-code .t-t { color: var(--fmq-c-type); }
.src-code .t-f { color: var(--fmq-c-fn); font-weight: 600; }
.src-code .t-s { color: var(--fmq-c-str); }
.src-code .t-n { color: var(--fmq-c-num); }
.src-code .t-c { color: var(--fmq-c-com); font-style: italic; }
.src-code .t-p { color: var(--fmq-c-pre); }
.src-code .t-o { color: var(--fmq-c-op); }
.src-code a.sym {
color: inherit;
text-decoration: underline;
text-decoration-color: rgb(140 200 239 / 0.45);
text-decoration-thickness: 1px;
text-underline-offset: 3px;
}
.src-code a.sym:hover,
.src-code a.sym:focus-visible {
text-decoration-color: var(--fmq-saffron);
background: rgb(250 190 93 / 0.12);
outline: none;
}
.src-card {
position: absolute;
z-index: 5;
max-width: min(36rem, calc(100% - 16px));
display: grid;
gap: 0.2rem;
padding: 0.6rem 0.75rem;
border: 1px solid var(--fmq-stage-line);
border-radius: 4px;
background: var(--fmq-stage-2);
color: var(--fmq-stage-ink);
box-shadow: 0 10px 30px -12px rgb(0 0 0 / 0.7);
font: 400 0.75rem/1.45 var(--fmq-font-mono);
pointer-events: none;
}
.src-card .k {
font: 600 0.625rem/1.2 var(--fmq-font-body);
letter-spacing: 0.1em;
text-transform: uppercase;
color: var(--fmq-stage-dim);
}
.src-card b {
font-weight: 700;
color: #fff;
overflow-wrap: anywhere;
}
.src-card code {
color: var(--fmq-c-type);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.src-card .l {
color: var(--fmq-saffron);
}
/* Overview */
.sl-markdown-content ul.src-list {
list-style: none;
padding: 0;
border-top: 1px solid var(--fmq-rule);
}
.sl-markdown-content ul.src-list > li {
display: grid;
grid-template-columns: minmax(12rem, max-content) 4rem minmax(0, 1fr);
gap: 0.25rem 1rem;
align-items: baseline;
padding: 0.4rem 0;
border-bottom: 1px solid var(--fmq-rule);
margin: 0 !important;
}
.sl-markdown-content ul.src-list > li::before {
display: none;
}
.sl-markdown-content ul.src-list code {
background: none;
border: 0;
padding: 0;
font-size: 0.875rem;
}
.src-lines {
font: 500 0.75rem var(--fmq-font-mono);
color: var(--fmq-ink-3);
text-align: end;
font-variant-numeric: tabular-nums;
}
.src-meta {
display: flex;
flex-wrap: wrap;
gap: 0.2rem 0.6rem;
font-size: 0.875rem;
}
@media (max-width: 40rem) {
.sl-markdown-content ul.src-list > li {
grid-template-columns: minmax(0, 1fr) max-content;
}
.src-meta {
grid-column: 1 / -1;
}
}

668
docs/src/styles/theme.css Normal file
View File

@@ -0,0 +1,668 @@
/*
* FairMQ theme for Starlight.
* Tokens for the light and dark theme, the type, and the styles that all pages share.
* Starlight sets data-theme="dark" or data-theme="light" on <html>. Dark is the base.
*/
:root {
--fmq-paper: #15171c;
--fmq-paper-2: #1b1e24;
--fmq-paper-3: #23272f;
--fmq-rule: #2f343e;
--fmq-rule-strong: #444a56;
--fmq-ink: #eceef2;
--fmq-ink-2: #b8bec9;
--fmq-ink-3: #9198a5;
--fmq-saffron: #fabe5d;
--fmq-saffron-tint: #3a3121;
--fmq-accent-ink: #fabe5d;
--fmq-bar: #fabe5d;
--fmq-on-saffron: #1a1a1a;
--fmq-link: #7ab8ec;
--fmq-link-tint: #16293b;
--fmq-teal: #4cc3a5;
--fmq-ruby: #f07aa8;
--fmq-ruby-tint: #3a1d2a;
--fmq-sky: #5cc0dd;
--fmq-sky-tint: #15303a;
--fmq-shadow: 0 1px 2px rgb(0 0 0 / 0.5), 0 14px 36px -16px rgb(0 0 0 / 0.75);
--fmq-scrim: rgb(0 0 0 / 0.55);
/* Code, terminal and explainer stage are dark in both themes. */
--fmq-code-bg: #0f1115;
--fmq-code-rule: #2a2f38;
--fmq-code-ink: #e6e8ec;
--fmq-code-dim: #9aa1ad;
--fmq-c-kw: #fabe5d;
--fmq-c-type: #8cc8ef;
--fmq-c-fn: #ffffff;
--fmq-c-str: #a8d99b;
--fmq-c-num: #f4a597;
--fmq-c-com: #8d96a5;
--fmq-c-pre: #e5b3d3;
--fmq-c-op: #c3c8d1;
--fmq-stage: #111318;
--fmq-stage-2: #1a1d24;
--fmq-stage-line: #4a515d;
--fmq-stage-cell: #262b34;
--fmq-stage-ink: #eceef2;
--fmq-stage-dim: #9aa1ad;
--fmq-stage-rule: #2a2e37;
--fmq-sky-bright: #62c6e6;
--fmq-mint: #5fd0ac;
--fmq-font-body: 'Archivo Variable', 'Helvetica Neue', Helvetica, Arial, sans-serif;
--fmq-font-mono: 'JetBrains Mono Variable', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
/* Starlight */
--sl-font: var(--fmq-font-body);
--sl-font-mono: var(--fmq-font-mono);
--sl-color-white: var(--fmq-ink);
--sl-color-gray-1: #dde1e7;
--sl-color-gray-2: var(--fmq-ink-2);
--sl-color-gray-3: var(--fmq-ink-3);
--sl-color-gray-4: #6b7280;
--sl-color-gray-5: var(--fmq-rule-strong);
--sl-color-gray-6: var(--fmq-paper-2);
--sl-color-gray-7: var(--fmq-paper-2);
--sl-color-black: var(--fmq-paper);
--sl-color-accent-low: var(--fmq-link-tint);
--sl-color-accent: #3d8fd6;
--sl-color-accent-high: var(--fmq-link);
--sl-color-text: var(--fmq-ink);
--sl-color-text-accent: var(--fmq-link);
--sl-color-text-invert: var(--fmq-paper);
--sl-color-bg: var(--fmq-paper);
--sl-color-bg-nav: var(--fmq-paper);
--sl-color-bg-sidebar: var(--fmq-paper);
--sl-color-bg-inline-code: var(--fmq-paper-3);
--sl-color-bg-accent: var(--fmq-link);
--sl-color-hairline-light: var(--fmq-rule);
--sl-color-hairline: var(--fmq-rule);
--sl-color-hairline-shade: var(--fmq-rule);
--sl-color-backdrop-overlay: var(--fmq-scrim);
--sl-text-body: 1.0625rem;
--sl-text-code: 0.86rem;
--sl-text-code-sm: 0.86em;
--sl-line-height: 1.65;
--sl-line-height-headings: 1.15;
--sl-content-width: 46rem;
--sl-sidebar-width: 17.5rem;
--sl-nav-height: 3.5rem;
color-scheme: dark;
}
:root[data-theme='light'] {
--fmq-paper: #ffffff;
--fmq-paper-2: #f5f6f8;
--fmq-paper-3: #eceef2;
--fmq-rule: #dcdfe5;
--fmq-rule-strong: #c3c8d1;
--fmq-ink: #1a1a1a;
--fmq-ink-2: #464c57;
--fmq-ink-3: #646b78;
--fmq-saffron-tint: #fdf0d3;
--fmq-accent-ink: #8a5a00;
--fmq-bar: #b97800;
--fmq-link: #005ea8;
--fmq-link-tint: #e5eff8;
--fmq-teal: #00775f;
--fmq-ruby: #b10057;
--fmq-ruby-tint: #fbe7ef;
--fmq-sky: #0e8bae;
--fmq-sky-tint: #e3f3f8;
--fmq-shadow: 0 1px 2px rgb(20 24 33 / 0.06), 0 12px 32px -16px rgb(20 24 33 / 0.24);
--fmq-scrim: rgb(21 23 28 / 0.36);
--fmq-code-bg: #22262d;
--fmq-code-rule: #353a44;
--sl-color-gray-1: #2b2f36;
--sl-color-gray-4: #8b919c;
--sl-color-gray-6: var(--fmq-paper-3);
--sl-color-gray-7: var(--fmq-paper-2);
--sl-color-accent: #005ea8;
--sl-color-accent-high: #004a85;
--sl-color-text-invert: #ffffff;
color-scheme: light;
}
@media (min-width: 50em) {
:root {
--sl-nav-height: 3.75rem;
--sl-text-h1: 2.625rem;
--sl-text-h2: 1.75rem;
--sl-text-h3: 1.3125rem;
--sl-text-h4: 1.125rem;
}
}
/* ---------- Base ---------- */
body {
font-stretch: 100%;
}
/* No ligatures: code must show the characters that are in the file. The font shorthand
resets font-variant-ligatures, so the rule must be important. */
*,
*::before,
*::after {
font-variant-ligatures: none !important;
}
code,
kbd,
pre,
samp {
font-family: var(--fmq-font-mono);
}
:focus-visible {
outline: 2px solid var(--fmq-link);
outline-offset: 2px;
}
::selection {
background: color-mix(in srgb, var(--fmq-saffron) 45%, transparent);
}
.fmq-label {
font: 600 0.75rem/1.2 var(--fmq-font-body);
font-stretch: 88%;
letter-spacing: 0.12em;
text-transform: uppercase;
color: var(--fmq-ink-3);
margin: 0;
}
/* Eyebrow above the page title: label, then a short saffron bar. */
.fmq-eyebrow {
font: 600 0.75rem/1.2 var(--fmq-font-body);
font-stretch: 88%;
letter-spacing: 0.12em;
text-transform: uppercase;
color: var(--fmq-ink-3);
margin: 1.25rem 0 0;
}
.fmq-eyebrow::after {
content: '';
display: block;
width: 1.75rem;
height: 3px;
background: var(--fmq-saffron);
margin: 0.6rem 0 0;
}
/* ---------- Content ---------- */
.sl-markdown-content {
color: var(--fmq-ink);
}
.sl-markdown-content :is(h1, h2, h3, h4, h5, h6):not(:where(.not-content *)) {
color: var(--fmq-ink);
text-wrap: balance;
}
.sl-markdown-content h2:not(:where(.not-content *)) {
font-weight: 750;
font-stretch: 108%;
letter-spacing: -0.012em;
margin-top: 2.25em;
}
.sl-markdown-content h3:not(:where(.not-content *)) {
font-weight: 700;
font-stretch: 104%;
margin-top: 1.75em;
}
.sl-markdown-content h4:not(:where(.not-content *)) {
font-weight: 650;
}
/* The first paragraph of a page is its lead. */
.sl-markdown-content > p:first-child {
font-size: 1.1875rem;
line-height: 1.55;
color: var(--fmq-ink-2);
max-width: 62ch;
}
.sl-markdown-content a:not(:where(.not-content *)) {
color: var(--fmq-link);
text-decoration-thickness: 1px;
text-underline-offset: 2px;
}
.sl-markdown-content a:hover:not(:where(.not-content *)) {
color: var(--fmq-ink);
}
.sl-markdown-content :not(pre) > code:not(:where(.not-content *)),
.fmq-code-inline {
font-size: 0.86em;
background: var(--fmq-paper-3);
border: 1px solid var(--fmq-rule);
border-radius: 3px;
padding: 0.05em 0.35em;
overflow-wrap: anywhere;
}
/* Short inline code does not break at a hyphen (scripts/nowrap-code.mjs). */
.sl-markdown-content code.nw {
white-space: nowrap;
}
.sl-markdown-content :is(h1, h2, h3, h4, h5, h6) code {
font-size: 0.9em;
border: 0;
background: none;
padding: 0;
}
/* Square bullets. */
.sl-markdown-content ul:not(:where(.not-content *)) {
list-style: none;
padding-inline-start: 1.25rem;
}
.sl-markdown-content ul:not(:where(.not-content *)) > li {
position: relative;
}
.sl-markdown-content ul:not(:where(.not-content *)) > li::before {
content: '';
position: absolute;
inset-inline-start: -1.15rem;
top: 0.68em;
width: 6px;
height: 6px;
background: var(--fmq-saffron);
outline: 1px solid var(--fmq-bar);
outline-offset: -1px;
}
.sl-markdown-content ol:not(:where(.not-content *)) {
padding-inline-start: 1.5rem;
}
.sl-markdown-content ol:not(:where(.not-content *)) > li::marker {
font: 600 0.85em var(--fmq-font-mono);
color: var(--fmq-ink-3);
}
/* Tables */
.sl-markdown-content table:not(:where(.not-content *)) {
font-size: 0.9375rem;
border-collapse: collapse;
width: 100%;
}
.sl-markdown-content th:not(:where(.not-content *)) {
text-align: start;
font: 600 0.7rem/1.2 var(--fmq-font-body);
font-stretch: 88%;
letter-spacing: 0.1em;
text-transform: uppercase;
color: var(--fmq-ink-3);
border-bottom: 1px solid var(--fmq-rule-strong);
white-space: nowrap;
}
.sl-markdown-content :is(th, td):not(:where(.not-content *)) {
padding: 0.55rem 0.75rem;
border-bottom-color: var(--fmq-rule);
vertical-align: top;
}
.sl-markdown-content td:not(:where(.not-content *)) {
border-bottom: 1px solid var(--fmq-rule);
}
.sl-markdown-content td:first-child code {
white-space: nowrap;
}
.sl-markdown-content hr:not(:where(.not-content *)) {
border: 0;
border-top: 1px solid var(--fmq-rule);
}
.sl-markdown-content blockquote:not(:where(.not-content *)) {
border-inline-start: 3px solid var(--fmq-saffron);
color: var(--fmq-ink-2);
}
.sl-markdown-content kbd,
.fmq-kbd {
font: 600 0.8em/1 var(--fmq-font-mono);
border: 1px solid var(--fmq-rule-strong);
border-bottom-width: 2px;
border-radius: 3px;
padding: 0.15em 0.4em;
background: var(--fmq-paper);
color: var(--fmq-ink);
}
/* Asides: square mark, quiet frame. */
.starlight-aside {
border: 1px solid var(--fmq-rule);
border-inline-start: 3px solid var(--sl-color-asides-border);
background: var(--fmq-paper-2);
border-radius: 4px;
padding: 0.85rem 1rem;
font-size: 0.96875rem;
}
.starlight-aside--note {
--sl-color-asides-border: var(--fmq-sky);
--sl-color-asides-text-accent: var(--fmq-ink-2);
}
.starlight-aside--tip {
--sl-color-asides-border: var(--fmq-teal);
--sl-color-asides-text-accent: var(--fmq-ink-2);
}
.starlight-aside--caution {
--sl-color-asides-border: var(--fmq-saffron);
--sl-color-asides-text-accent: var(--fmq-ink-2);
}
.starlight-aside--danger {
--sl-color-asides-border: var(--fmq-ruby);
--sl-color-asides-text-accent: var(--fmq-ink-2);
}
.starlight-aside__title {
font: 600 0.7rem/1.2 var(--fmq-font-body);
font-stretch: 88%;
letter-spacing: 0.12em;
text-transform: uppercase;
gap: 0.5rem;
}
.starlight-aside__icon {
display: none;
}
.starlight-aside__title::before {
content: '';
width: 8px;
height: 8px;
background: var(--sl-color-asides-border);
flex: none;
}
/* Starlight badges */
.sl-badge {
font: 600 0.65rem/1 var(--fmq-font-body);
letter-spacing: 0.08em;
text-transform: uppercase;
border-radius: 3px;
}
/* Our badge, for kinds, versions and states. */
.fmq-badge {
display: inline-flex;
align-items: center;
font: 600 0.66rem/1 var(--fmq-font-body);
letter-spacing: 0.08em;
text-transform: uppercase;
border: 1px solid var(--fmq-rule-strong);
color: var(--fmq-ink-2);
border-radius: 3px;
padding: 0.3em 0.45em;
vertical-align: middle;
white-space: nowrap;
text-decoration: none;
}
.fmq-badge.since {
border-color: var(--fmq-teal);
color: var(--fmq-teal);
}
.fmq-badge.deprecated {
border-color: var(--fmq-ruby);
color: var(--fmq-ruby);
}
.fmq-badge.mark {
border-color: var(--fmq-bar);
color: var(--fmq-accent-ink);
}
a.fmq-badge:hover {
border-color: var(--fmq-ink-3);
color: var(--fmq-ink);
}
/* Starlight tabs: saffron mark under the active tab. */
starlight-tabs .tab > [role='tab'] {
font-weight: 500;
color: var(--fmq-ink-3);
border-bottom: 2px solid transparent;
}
starlight-tabs .tab [role='tab'][aria-selected='true'] {
color: var(--fmq-ink);
font-weight: 600;
border-bottom-color: var(--fmq-saffron);
}
starlight-tabs .tablist-wrapper {
border-bottom: 1px solid var(--fmq-rule);
}
/* Steps */
.sl-steps > li::before {
font-family: var(--fmq-font-mono);
border-radius: 3px;
background: var(--fmq-paper-2);
box-shadow: inset 0 0 0 1px var(--fmq-rule-strong);
color: var(--fmq-ink);
}
.sl-steps > li::after {
background: var(--fmq-rule);
}
/* Cards */
.card {
border-radius: 4px;
border-color: var(--fmq-rule);
background: var(--fmq-paper);
}
.sl-link-card {
border-radius: 4px;
border-color: var(--fmq-rule);
box-shadow: none;
}
.sl-link-card:hover {
border-color: var(--fmq-ink-3);
background: var(--fmq-paper-2);
}
/* ---------- Expressive Code ---------- */
.expressive-code {
margin-block: 1rem;
}
.expressive-code .frame .header {
font-family: var(--fmq-font-mono);
}
.expressive-code .frame.is-terminal .header .title,
.expressive-code .frame .header .title {
font-size: 0.75rem;
}
.expressive-code .copy button {
border-radius: 3px;
}
/* ---------- Sidebar ---------- */
#starlight__sidebar .sidebar-content {
padding-top: 0.75rem;
}
#starlight__sidebar summary .large {
font: 600 0.7rem/1.2 var(--fmq-font-body);
font-stretch: 88%;
letter-spacing: 0.12em;
text-transform: uppercase;
color: var(--fmq-ink-3);
}
#starlight__sidebar .top-level > li > a.large {
font-size: var(--sl-text-sm);
font-weight: 500;
color: var(--fmq-ink-2);
}
#starlight__sidebar ul ul li {
border-inline-start: 0;
margin-inline-start: 0;
padding-inline-start: 0;
}
#starlight__sidebar a {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--fmq-ink-2);
border-radius: 3px;
padding: 0.28em 0.5rem;
line-height: 1.35;
}
#starlight__sidebar a:hover,
#starlight__sidebar a:focus-visible {
color: var(--fmq-ink);
background: var(--fmq-paper-2);
}
#starlight__sidebar a[aria-current='page'],
#starlight__sidebar a[aria-current='page']:hover,
#starlight__sidebar a[aria-current='page']:focus {
background: var(--fmq-saffron-tint);
color: var(--fmq-ink);
font-weight: 600;
}
#starlight__sidebar a[aria-current='page']::before {
content: '';
width: 6px;
height: 6px;
flex: none;
background: var(--fmq-saffron);
outline: 1px solid var(--fmq-bar);
outline-offset: -1px;
}
/* Kind letters in the API tree: class, struct, enum, namespace. */
#starlight__sidebar a[data-kind]::after {
content: attr(data-kind);
order: -1;
flex: none;
display: inline-grid;
place-items: center;
width: 1.15rem;
height: 1.15rem;
font: 600 0.62rem/1 var(--fmq-font-mono);
color: var(--fmq-ink-3);
border: 1px solid var(--fmq-rule-strong);
border-radius: 2px;
}
#starlight__sidebar a[data-kind][aria-current='page']::before {
display: none;
}
#starlight__sidebar a[data-kind][aria-current='page']::after {
color: var(--fmq-on-saffron);
background: var(--fmq-saffron);
border-color: var(--fmq-bar);
}
#starlight__sidebar a.fmq-mono {
font-family: var(--fmq-font-mono);
font-size: 0.8125rem;
}
/* ---------- Right column ---------- */
.right-sidebar-panel h2 {
font: 600 0.7rem/1.2 var(--fmq-font-body);
font-stretch: 88%;
letter-spacing: 0.12em;
text-transform: uppercase;
color: var(--fmq-ink-3);
}
.right-sidebar-panel a {
color: var(--fmq-ink-2);
}
.right-sidebar-panel a[aria-current='true'] {
color: var(--fmq-ink);
font-weight: 600;
}
starlight-toc a[aria-current='true'],
starlight-toc a[aria-current='true']:hover,
starlight-toc a[aria-current='true']:focus {
color: var(--fmq-ink);
}
/* ---------- Pagination ---------- */
.pagination-links a {
border-radius: 4px;
border-color: var(--fmq-rule);
box-shadow: none;
color: var(--fmq-ink);
}
.pagination-links a:hover {
border-color: var(--fmq-ink-3);
}
.pagination-links .link-title {
font-weight: 650;
font-size: 1rem;
}
/* ---------- Header ---------- */
header.header {
border-bottom: 1px solid var(--fmq-rule);
background: var(--fmq-paper);
}
/* ---------- Search dialog ---------- */
site-search dialog {
border-radius: 6px;
border: 1px solid var(--fmq-rule-strong);
background: var(--fmq-paper);
box-shadow: var(--fmq-shadow);
}
#starlight__search {
--pagefind-ui-primary: var(--fmq-link);
--pagefind-ui-text: var(--fmq-ink);
--pagefind-ui-background: var(--fmq-paper);
--pagefind-ui-border: var(--fmq-rule-strong);
--pagefind-ui-tag: var(--fmq-paper-3);
--pagefind-ui-font: var(--fmq-font-body);
}
#starlight__search mark {
background: var(--fmq-saffron-tint);
color: var(--fmq-ink);
box-shadow: inset 0 -2px 0 var(--fmq-saffron);
}
/* ---------- Print ---------- */
@media print {
.fmq-eyebrow::after {
background: #000;
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0s !important;
animation-iteration-count: 1 !important;
transition-duration: 0s !important;
scroll-behavior: auto !important;
}
}
#starlight__sidebar a.fmq-nested {
padding-inline-start: 1.6rem;
font-size: 0.78rem;
}
/* No rule between the title and the content. */
.content-panel + .content-panel {
border-top: 0;
}
.content-panel:first-of-type:not(:only-of-type) {
padding-bottom: 0;
}
/* Source pages use the full width of the main column. */
:root:has(.src-code) {
--sl-content-width: 76rem;
}
/* ---------- Home ---------- */
html[data-has-hero] {
--sl-content-width: 74rem;
}
html[data-has-hero] .content-panel {
padding-top: 1rem;
}