libnex — programming the NEX cluster in C
By Roberto Arato of aratoingegneria.it
libnex is the library with which a C program (or C++, or any language
that can call C functions) uses the NEX cluster: it sees the nodes and the
processes, launches commands on other nodes, waits for them, stops them,
uses the job queue, opens connections to services on other nodes. It is the
same library used by nex, nexsh and the dashboard.
Up to 1.0 beta 1 it was called libnex_dev (packages libnex-dev0 and
libnex-dev-dev, functions nex_dev_*): from 1.0 beta 2 it has the name of
NEX, with the packages libnex0 and libnex-dev, which take the place of the
old ones with apt. A program written for beta 1 is updated by changing
nex_dev.h into nex.h, -lnex_dev into -lnex, the prefixes nex_dev_
and NEX_DEV_ into nex_ and NEX_, and the type nex_dev into nex_conn.
This guide is also the developers section of the NEX site.
Contents
- Installation and compilation
- Concepts
- Connecting to the agent
- Nodes and processes
- Spawn and wait
- Execution with live output: nex_run
- Detached jobs
- The job queue
- Signals, messages, passwords
- Cluster logs
- Connections to services on other nodes
- Remote graphics and audio: X11, Wayland, PulseAudio
- Cluster key-value
- Generic requests
- Errors
- The examples
- Function list
1. Installation and compilation
apt install libnex-dev # header nex.h, library, examples, man nex(3)
The libnex0 package (the shared library) comes along by itself as a
dependency; on the cluster nodes it is already there, because nex uses it.
cc -Wall -O2 -o mioprog mioprog.c -lnex
With NEX installed by hand in /usr/local (lab, development):
cc -I/usr/local/include -o mioprog mioprog.c -L/usr/local/lib -Wl,-rpath,/usr/local/lib -lnex
The library exports only the nex_* functions: the libraries it uses
internally stay hidden, so it does not conflict with those of the program.
The program must run on a cluster node, where the agent (nexagentd)
is.
2. Concepts
- The local agent. Every call talks to the NEX agent of the node where
the program runs, on the socket
/run/nex/agent.sock. The agent forwards to the other nodes, over TLS and with mutual authentication. - No credentials. Who you are is told to the agent by the kernel: the
program acts as the user running it and sees what it would see with the
nexcommands (its own processes and jobs; root everything). Nothing can be launched on behalf of another user, andnex runis not allowed to root. - JSON responses. The read functions return a JSON document in an
allocated string, to be freed with
nex_free. The format is part of the API: it stays compatible as long as the"version"field does not change. To read it you use a JSON library (json-c, cJSON, jansson...). The examples, so as not to depend on any of them, use a smallvalore()function. - Nodes. Wherever a node is requested:
NULLor""means the local node,"any"lets the agent choose the least loaded one, otherwise the name ("node-b"). - The folder. A command on another node starts in the given folder,
which must be in
/nex(the shared filesystem, identical on all nodes). - Threads. A
nex_connhandle must not be used by several threads at once: each thread opens its own.nex_spawnandnex_waitopen and close their own connection and can be called from any thread.
3. Connecting to the agent
nex_conn *nex_open(const char *socket_path); // NULL = /run/nex/agent.sock
void nex_close(nex_conn *nd);
void nex_free(char *s); // for every returned string
const char *nex_version(void); // "0.20.0"
const char *nex_strerror(int err); // text of an error code
nex_open returns NULL if the agent does not answer (nexagentd
stopped or node not configured).
nex_conn *nd = nex_open(NULL);
if (nd == NULL) { fprintf(stderr, "agent NEX non raggiungibile\n"); return 1; }
...
nex_close(nd);
4. Nodes and processes
int nex_nodes(nex_conn *nd, char **response); // nex nodes
int nex_nodes_detail(nex_conn *nd, char **response); // + disks and /nex (nex df)
int nex_nodes_want(nex_conn *nd, const char *want, char **response); // "cpu", "net", "sockets"
int nex_ps(nex_conn *nd, int cluster, char **response); // cluster 0 = this node
Response of nex_nodes:
{"version":1,"nodes":[
{"node":"node-a","status":"ok","ms":0.4,
"info":{"compute":true,"mounted":true,"mount":"/nex","load1":0.12,"load5":0.10,
"load15":0.05,"ncpu":2,"uptime":3600,"mem_total_kb":8000000,
"mem_avail_kb":6000000,"mem_free_kb":5000000,"cache_kb":900000,
"swap_total_kb":0,"swap_free_kb":0,"jobs":0}},
{"node":"nex-stor","status":"unreachable","error":"..."}]}
With nex_nodes_detail every info also has "disks" (local
filesystems: mount, dev, fstype, size_kb, used_kb, avail_kb) and
"nexfs" (space of /nex). With nex_nodes_want the requested
sections are added, separated by commas: "cpu" (usage per processor and
model), "net" (interfaces and traffic), "sockets" (TCP and UDP
connections with their process).
Response of nex_ps: for each node the list of visible processes.
{"version":1,"nodes":[{"node":"node-a","status":"ok","ms":0.4,"processes":[
{"pid":1234,"ppid":1,"uid":1000,"user":"mario","state":"S","cpu":0.0,
"rss_kb":12345,"threads":1,"age":3600,"kernel":false,
"cmd":"sleep 300","cgroup":"/user.slice/..."}]}]}
Complete example: 01_nodi.c.
The history of measurements
int nex_metrics(nex_conn *nd, const char *node, int since, int step, char **response); // nex history
The functions above tell how the cluster is now; nex_metrics tells
how it was. Every agent saves one sample per minute and the cluster keeps
them for 30 days.
node:NULLfor all nodes.since: how many seconds back, from 300 to 30 days.step: width of each interval;0leaves about 120 intervals.- Response: for each node one series per measurement, with the average
of the samples of each interval (
nullif there are none). The format is that ofGET /api/v1/metrics(api.md).
// the measurements of node-a, minute by minute, over the last hour
char *r = NULL;
if (nex_metrics(nd, "node-a", 3600, 60, &r) == NEX_OK)
puts(r);
else
fprintf(stderr, "metrics: %s\n", nex_errmsg());
nex_free(r);
The response is JSON text, to be read with whatever JSON library the program already uses:
{"from":1792840000,"step":60,"points":60,
"nodes":[{"node":"node-a","cpu":[12.5,null,8.0,...],"load":[...],
"mem":[...],"rx":[...],"tx":[...],"disk":[...]}]}
5. Spawn and wait
The simplest way to use the cluster from a program: the style of
posix_spawn and waitpid.
typedef struct {
char node[64]; // node where it runs
char job[16]; // job identifier
} nex_pid;
int nex_spawn(const char *node, const char *const argv[], nex_pid *pid);
int nex_spawn_ex(const char *node, const char *const argv[], const char *cwd,
const char *const env[], const char *cpu, const char *mem,
nex_pid *pid);
int nex_wait(const nex_pid *pid, int *status, int timeout_ms);
const char *nex_errmsg(void);
nex_spawnstartsargvon the node and returns immediately. The command starts in the program's current folder (in/nexfor another node) with the program'sPATH,LANG,LC_ALLandTZ. The cluster "pid" is the pair node + job, the same thatnex jobsshows and thatnex attachandnex stopaccept (node-b:3fa2c1).nex_spawn_exchooses folder (NULL= current), environment ({"NAME=value", ..., NULL};NULL= no variables), maximum CPU ("50"= half a CPU,"200"= two) and maximum memory ("512M","2G"). Beyond the memory the process is stopped, it does not swap.nex_waitwaits for the end and puts in*statusthe exit code like the shell's$?: 0..255, or 128 + the signal number if the process was killed (143 = SIGTERM, 137 = SIGKILL).timeout_ms:-1without limit,0checks and returns immediately (likeWNOHANG), otherwise at most that many milliseconds. Likewaitpidit reaps the job: after a successful return it no longer appears innex jobs.nex_errmsggives the reason for the last spawn or wait error in the thread, for examplenode-b: directory /tmp is not under /nex.
The process does not depend on the program that launched it: if the
program ends or crashes, the process carries on and can be found with
nex jobs.
The process's output stays with its keeper and can be read before the
wait with nex_attach_json (chapter 7). If it is needed live you use
nex_run (chapter 6); if it is needed later, it is written to a file in
/nex:
const char *argv[] = { "sh", "-c", "./simula --caso 3 > risultati/caso3.txt", NULL };
Example: four computations in parallel on the least loaded nodes, then the wait.
nex_pid pid[4];
for (int i = 0; i < 4; i++) {
char caso[16];
snprintf(caso, sizeof(caso), "%d", i);
const char *argv[] = { "./simula", "--caso", caso, NULL };
if (nex_spawn("any", argv, &pid[i]) != NEX_OK) {
fprintf(stderr, "caso %d: %s\n", i, nex_errmsg());
return 1;
}
printf("caso %d su %s (job %s)\n", i, pid[i].node, pid[i].job);
}
for (int i = 0; i < 4; i++) {
int st;
if (nex_wait(&pid[i], &st, -1) == NEX_OK) printf("caso %d: codice %d\n", i, st);
else printf("caso %d: %s\n", i, nex_errmsg());
}
Return values of nex_wait:
| Code | Meaning |
|---|---|
NEX_OK |
finished, code in *status |
NEX_ERR_TIMEOUT |
still running when timeout_ms expired |
NEX_ERR_LOST |
the job's keeper or the node were lost (node silent for 60 s): outcome unknown |
NEX_ERR_NOTFOUND |
the job is no longer there: stopped, already reaped, or finished more than 24 hours ago |
Complete example: 02_spawn_wait.c.
In a fixed environment: the image variants
Every way of launching a command has a variant with an image from the
cluster archive (nex image list). The command runs in a rootless Podman
container, as the user, with /nex mounted at the same path, the given
folder and the node's network; the PATH is the image's.
int nex_spawn_image(const char *node, const char *image, const char *const argv[], nex_pid *pid);
char *nex_run_json_image(const char *node, const char *const argv[], const char *cwd,
const char *const env[], const char *cpu, const char *mem,
int tty, int rows, int cols, const char *image);
int nex_run_detached_image(nex_conn *nd, const char *node, const char *const argv[], const char *cwd,
const char *const env[], const char *cpu, const char *mem,
int tty, int rows, int cols, int quiet, const char *image, char **response);
int nex_submit_image(nex_conn *nd, const char *node, const char *const argv[], const char *cwd,
const char *const env[], const char *cpu, const char *mem, int prio, int quiet,
const char *image, char **response);
const char *argv[] = { "python3", "simula.py", "--caso", "3", NULL };
nex_pid pid;
int st;
if (nex_spawn_image("any", "docker.io/library/python:3.12", argv, &pid) == NEX_OK &&
nex_wait(&pid, &st, -1) == NEX_OK)
printf("finito con %d\n", st);
The exit code, signals and the cpu/mem limits work as without a
container. If the image is not in the archive the request is refused
(NEX_ERR_AGENT, with the reason).
6. Execution with live output: nex_run
Like system() or a pipe, but on the cluster: the command runs on another
node and its output arrives as it is written. The program can write to its
stdin and send it signals.
char *nex_run_json(const char *node, const char *const argv[], const char *cwd,
const char *const env[], const char *cpu, const char *mem);
nex_job *nex_run(nex_conn *nd, const char *request, int *err);
int nex_job_next(nex_job *job, int *event, char **data, size_t *len);
int nex_job_write(nex_job *job, const void *buf, size_t len);
int nex_job_close_stdin(nex_job *job);
int nex_job_signal(nex_job *job, int sig);
void nex_job_free(nex_job *job);
nex_run_jsonprepares the request (a string to be freed withnex_free);nex_runsends it. From then on the handle is dedicated to the job: for other requests you open another one.nex_job_nextreturns one event at a time (blocking). The data must be freed withnex_free.
| Event | data |
|---|---|
NEX_EV_STARTED |
JSON {"node","unit"}: the command has started, and where |
NEX_EV_STDOUT |
bytes of standard output (len bytes, not terminated) |
NEX_EV_STDERR |
bytes of standard error |
NEX_EV_EXIT |
JSON {"code","unit"}: end, code as in the shell |
NEX_EV_LOST |
JSON {"node","reason"}: the node does not answer, outcome unknown |
NEX_EV_ERROR |
text: request refused, the command did not start |
After EXIT, LOST or ERROR no other events arrive.
3. nex_job_write writes to the command's stdin;
nex_job_close_stdin closes it (the command sees the end of the
data); nex_job_signal sends a signal (SIGINT, SIGTERM...).
4. nex_job_free frees the job; if the command is still running, it
closes the connection and the command is stopped.
A job can be driven from several threads: one writes stdin, one sends signals, only one reads the events.
char cwd[4096];
getcwd(cwd, sizeof(cwd));
const char *argv[] = { "sort", "-n", NULL };
nex_conn *nd = nex_open(NULL);
char *req = nex_run_json("node-b", argv, cwd, NULL, NULL, "1G");
int err, ev;
nex_job *job = nex_run(nd, req, &err);
nex_free(req);
nex_job_write(job, "42\n7\n1000\n", 10);
nex_job_close_stdin(job);
char *data;
size_t len;
while (nex_job_next(job, &ev, &data, &len) == NEX_OK) {
if (ev == NEX_EV_STDOUT) fwrite(data, 1, len, stdout); // 7, 42, 1000
nex_free(data);
}
nex_job_free(job);
nex_close(nd);
With a terminal. For interactive programs (editors, shells, top):
char *nex_run_json_tty(const char *node, const char *const argv[], const char *cwd,
const char *const env[], const char *cpu, const char *mem,
int rows, int cols);
int nex_job_resize(nex_job *job, int rows, int cols);
The command has a terminal of rows x cols. Output and error both arrive
as STDOUT, and Ctrl-C is sent as the byte 0x03 with
nex_job_write. When the window changes you call
nex_job_resize.
Complete examples: 03_run_uscita.c, 04_stdin_segnali.c.
7. Detached jobs
A detached job runs in its own unit with its keeper and does not depend on
whoever launched it: it is nex run -d. nex_spawn is a convenient
form of this same mechanism.
int nex_run_detached(nex_conn *nd, const char *node, const char *const argv[], const char *cwd,
const char *const env[], const char *cpu, const char *mem,
int tty, int rows, int cols, int quiet, char **response);
int nex_jobs(nex_conn *nd, char **response);
int nex_job_stop(nex_conn *nd, const char *node, const char *job, char **response);
char *nex_attach_json(const char *node, const char *job);
nex_run_detachedstarts and answers immediately with{"node","job","unit"}. Withtty != 0the job has a terminal ofrowsxcols; withquiet != 0no notice appears on the user's terminals at the end.nex_jobslists the visible jobs (one's own, root all) on all nodes:
{"version":1,"nodes":[{"node":"node-b","status":"ok","ms":3.1,"jobs":[
{"job":"3fa2c1","node":"node-b","unit":"nex-job-3fa2c1","uid":20001,"pid":4242,
"tty":false,"cmd":"./simula --caso 3","cwd":"/nex/home/mario","start":1791300000,
"state":"running","attached":false}]}]}
state is running, exited (with code and end) or lost.
nex_job_stopstops the job:{"ok":true,"node","message"}.nex_attach_jsonprepares the request to reattach withnex_run. There arriveSTARTED({"node","unit","job","tty","replay"}), the kept output (up to 1 MiB) and the new output, thenEXITwhen the command ends.nex_job_freedetaches without stopping the job. Reattaching to a job that has already finished delivers its output and closes it: afterwards it no longer appears innex jobs.
Complete example: 05_staccati.c.
8. The job queue
The queue is useful when there are more jobs than free CPUs: each entry
waits until a compute node has room (sum of the reserved CPUs, one by
default) and then starts as a detached job. It is nex submit.
int nex_submit(nex_conn *nd, const char *node, const char *const argv[], const char *cwd,
const char *const env[], const char *cpu, const char *mem, int prio, int quiet,
char **response);
int nex_queue(nex_conn *nd, char **response);
int nex_queue_cancel(nex_conn *nd, const char *qid, char **response);
nex_submit:nodeNULL= any node;cpuis also the reservation;priogoes from 0 to 9 (9 = the highest;nex submituses 5). Response{"queue":"q1a2b3c","position":N}.nex_queue: one's own entries (root all):
{"version":1,"queue":[{"qid":"q1a2b3c","user":"mario","uid":20001,"prio":5,
"state":"queued","position":1,"node":"","run_node":"","job":"",
"submitted":1791300000,"argv":["./simula","--caso","3"],"cwd":"/nex/home/mario",
"cpu":"100","mem":"2G"}]}
state goes from queued to claimed (a node has taken it), then
running (with run_node and job), then done (with code and
ended, or error).
nex_queue_cancelremoves an entry that is still waiting.
Complete example (parametric study): 06_coda.c.
9. Signals, messages, passwords
int nex_kill(nex_conn *nd, const char *node, int pid, int sig, char **response);
int nex_msg(nex_conn *nd, const char *to, const char *text, char **response);
int nex_passwd(nex_conn *nd, const char *current, const char *new_password, char **response);
nex_killsends a signal to a PID on any node (only to one's own processes; root to all), likenex kill node-b:PID. Response{"ok","node","message"}.nex_msgwrites on a user's terminals on all nodes (nex msg);"*"writes to everyone and is for root only. Response{"delivered":N,"nodes":[{"node","delivered"}]}.nex_passwdchanges the password of the calling user, if it is a cluster user, on all nodes (nex passwd).*responsecontains the message for the user even when it fails. Passwords must never be written in the code or in command arguments.
10. Cluster logs
int nex_logs(nex_conn *nd, const char *node, const char *unit, const char *grep, int lines,
long long since_usec, int prio, char **response);
The journal lines of all nodes (node NULL) or of one, merged in time
order, like nex logs:
- the last
lineslines (from 1 to 5000); - from
since_useconwards (microseconds since 1970; 0 = all); - with priority up to
prio(0 emergency ... 7 debug); - filtered by systemd unit (
unit) and by text (grep);NULLmeans no filter.
A user sees only the lines of their own programs, root all of them.
{"version":1,"nodes":[{"node":"node-a","status":"ok","ms":50.3}],
"entries":[{"t":1791300000123456,"node":"node-a","unit":"nex-job-3fa2c1.service",
"id":"simula","pid":4242,"prio":6,"msg":"caso 3 finito"}]}
Complete example (with kill and msg): 08_processi_log.c.
11. Connections to services on other nodes
char *nex_forward_json(const char *node, const char *host, int port);
The given node opens a TCP connection to host:port as it sees it
("localhost" = the node itself). This way a service reachable only from
inside a node (a database on 127.0.0.1, a port not open on the network)
becomes usable, through the encrypted channel between the agents. It is
nex forward. It is used with nex_run:
STARTEDarrives with{"node","peer"};- the service's bytes arrive as
STDOUT; nex_job_writesends,nex_job_close_stdincloses for writing;EXITarrives when the service closes.
Complete example: 07_forward.c.
12. Remote graphics and audio: X11, Wayland, PulseAudio
For a graphical program that runs on another node and appears on the local screen, the request is prepared with:
char *nex_run_json_ex(const char *node, const char *const argv[], const char *cwd,
const char *const env[], const char *cpu, const char *mem,
int tty, int rows, int cols, const char *x11_cookie);
char *nex_run_json_gfx(const char *node, const char *const argv[], const char *cwd,
const char *const env[], const char *cpu, const char *mem,
int tty, int rows, int cols, const char *x11_cookie, int wayland);
int nex_job_x11_send(nex_job *job, unsigned id, const void *buf, size_t len);
int nex_job_x11_close(nex_job *job, unsigned id);
int nex_job_wl_send(nex_job *job, unsigned id, const void *buf, size_t len);
int nex_job_wl_close(nex_job *job, unsigned id);
char *nex_run_json_av(const char *node, const char *const argv[], const char *cwd,
const char *const env[], const char *cpu, const char *mem,
int tty, int rows, int cols, const char *x11_cookie, int wayland,
int audio);
int nex_job_pa_send(nex_job *job, unsigned id, const void *buf, size_t len);
int nex_job_pa_close(nex_job *job, unsigned id);
X11. With x11_cookie (32 hexadecimal digits, a fake cookie chosen by
the caller) the remote node creates a display. Every connection of the
remote program arrives as NEX_EV_X11_OPEN, _DATA and _CLOSE
events. The data begins with the connection id (4 bytes, big endian). The
caller passes it to the local X server and sends back the replies with
nex_job_x11_send.
Wayland. With wayland = 1 the command runs under waypipe server and
the NEX_EV_WL_* events go to a local waypipe client. With
wayland = 2 a node without waypipe runs the command without graphics
instead of refusing it.
Audio (libnex 0.14.0). nex_run_json_av adds the audio
parameter to the options of nex_run_json_gfx. With audio = 1 the
remote node creates a socket private to the job and puts in the program's
environment PULSE_SERVER=unix:<socket> and PULSE_CLIENTCONFIG, with a
file that turns off shared memory (it does not cross the network). Every
PulseAudio connection of the program arrives as NEX_EV_PA_OPEN,
_DATA and _CLOSE events. For each id the caller opens a connection to
its own audio server ($XDG_RUNTIME_DIR/pulse/native, also with
pipewire-pulse), passes it the data and sends back the replies with
nex_job_pa_send. There is no cookie to replace: the remote socket
belongs only to the user, and the local server sees a connection from the
same user. With audio = 2 (as nexsh does) audio is requested without
being mandatory.
It is an advanced use: nex run -X, nex run -W and nex run -A already
do it, and their code is the reference.
13. Cluster key-value
int nex_kv_get(nex_conn *nd, const char *space, const char *key, char **value);
int nex_kv_set(nex_conn *nd, const char *space, const char *key, const char *value, int ttl);
int nex_kv_cas(nex_conn *nd, const char *space, const char *key, const char *expect,
const char *value, int ttl);
int nex_kv_del(nex_conn *nd, const char *space, const char *key);
int nex_kv_list(nex_conn *nd, const char *space, const char *prefix, char **response);
Text values, up to 64 KiB, that every process reads identically from any
node. They live in the NEXFS control store, not in a file: two processes on
different nodes do not step on each other's toes. They are the same thing
as nex kv on the command line.
Spaces
space |
Who reads | Who writes |
|---|---|---|
NULL or "" |
only the caller | only the caller |
"group:NAME" |
the group members | the group members |
"cluster" |
everyone | root only |
Functions
- Keys: from 1 to 200 bytes, without control characters. The
/character is fine for making logical folders (progetto/stato), andnex_kv_listfilters by prefix. - Expiry:
ttlis in seconds, 0 means no expiry. An expired key counts as absent. nex_kv_get: returnsNEX_ERR_NOTFOUNDif the key is not there. The value must be freed withnex_free.nex_kv_cas: it is the atomic compare across all nodes. It writes only if the key still has the valueexpect; withexpectNULLit writes only if the key does not exist. If someone else has written in the meantime it returnsNEX_ERR_CONFLICT: you read again and retry.nex_kv_list: returns in JSON{"items":[{"key","value","expires","modified","by"}...]}, at most 1000 keys.
Two typical uses
nex_conn *nd = nex_open(NULL);
/* only one process among many does the work (the others find the key already taken) */
char io[128];
snprintf(io, sizeof(io), "%s:%d", nodo, (int)getpid());
if (nex_kv_cas(nd, "group:calcolo", "notte/capo", NULL, io, 3600) == NEX_OK)
elabora();
/* shared counter without lost updates */
for (;;) {
char *v = NULL, nuovo[32];
long n = 0;
if (nex_kv_get(nd, NULL, "casi/fatti", &v) == NEX_OK) n = atol(v);
snprintf(nuovo, sizeof(nuovo), "%ld", n + 1);
int r = nex_kv_cas(nd, NULL, "casi/fatti", v, nuovo, 0); /* v NULL: did not exist */
nex_free(v);
if (r != NEX_ERR_CONFLICT) break; /* done, or a real error */
}
nex_close(nd);
Since nex_kv_cas is atomic across all nodes, several processes on
different nodes can increment the same counter together without losing an
update: whoever finds the value changed gets NEX_ERR_CONFLICT and
retries. Complete example:
10_kv.c.
The caller's secrets
int nex_secret_get(nex_conn *nd, const char *name, char **value);
int nex_secret_set(nex_conn *nd, const char *name, const char *value);
int nex_secret_del(nex_conn *nd, const char *name);
int nex_secret_list(nex_conn *nd, char **response);
void nex_secret_free(char *value);
They are for passwords, tokens and keys that a program reads from any node
without keeping them in a file (nex secret on the command line).
- Owner: they belong only to the caller.
- Encryption: with the cluster key (AES-256-GCM). User and name are bound to the ciphertext, so an envelope copied under another name does not open.
- Names and values: names of 1-128 characters among letters, digits and
. _ - / @, values up to 64 KiB. nex_secret_get: returnsNEX_ERR_NOTFOUNDif the secret is missing. The value must be freed withnex_secret_free, which zeroes it before freeing it.nex_secret_list: gives the names, never the values.
char *pw = NULL;
if (nex_secret_get(nd, "db/produzione", &pw) == NEX_OK) {
collega_database(pw);
nex_secret_free(pw);
} else {
fprintf(stderr, "segreto: %s\n", nex_errmsg()); /* e.g. cluster key missing on the node */
}
The control store never holds the value in clear text, and a tampered ciphertext is rejected.
Messages between processes
int nex_pub(nex_conn *nd, const char *space, const char *topic, const char *message,
int *delivered);
int nex_pub_ex(nex_conn *nd, const char *space, const char *topic, const char *message,
int flags, int *delivered);
nex_sub *nex_sub_open(const char *space, const char *topic, int history, int *err);
int nex_sub_next(nex_sub *sub, char **message, int timeout_ms);
int nex_sub_fd(nex_sub *sub);
void nex_sub_close(nex_sub *sub);
int nex_mq_push(nex_conn *nd, const char *space, const char *queue, const char *message);
int nex_mq_pop(nex_conn *nd, const char *space, const char *queue, int wait_s, char **message);
int nex_mq_len(nex_conn *nd, const char *space, const char *queue, int *length);
Publish and subscribe:
- Who receives: every subscriber, on any node, receives every message
published after its subscription. With
historyit first also receives the latest messages of the history, which keeps 100 of them. nex_pub: in*deliveredit tells how many subscribers received it.nex_pub_ex: likenex_pub, withflags. WithNEX_PUB_NOHISTORYthe message reaches only the subscribers connected at that moment and is not kept in the history, so a later subscriber never sees it: this is for sensitive data, such as clipboard contents. Withflags0 it is the same asnex_pub.- Connection: the subscription has its own.
nex_sub_next: returns the JSON envelope{"m","user","node","t","by"}withintimeout_ms(-1 = without limit), otherwiseNEX_ERR_TIMEOUT.nex_sub_fd: lets you wait for the subscription withpolltogether with other things.
int err;
nex_sub *s = nex_sub_open("group:calcolo", "simulazione/fine", 0, &err);
if (s == NULL) { fprintf(stderr, "%s\n", nex_errmsg()); return 1; }
char *m = NULL;
while (nex_sub_next(s, &m, 60000) == NEX_OK) {
printf("ricevuto: %s\n", m);
nex_free(m);
}
nex_sub_close(s);
Queues:
- A single consumer: every message put with
nex_mq_pushis taken by a singlenex_mq_pop, even with many consumers on different nodes. It is used to distribute work. - Waiting:
wait_sis how long to wait if the queue is empty (at most 300 s). It returnsNEX_ERR_NOTFOUNDif the queue stays empty.
14. Generic requests
int nex_request(nex_conn *nd, const char *request, char **response);
Every nex command corresponds to a JSON request to the agent: an "op"
field plus the parameters. Those without a dedicated function are sent this
way. With NEX_ERR_AGENT, *response contains the reason for the
refusal in plain text.
| Request | Like |
|---|---|
{"op":"service","action":"list"} |
nex service list |
{"op":"alarm","action":"list"} |
nex alarm |
{"op":"alarm","action":"ack","id":"nexfs"} |
nex alarm ack nexfs (root) |
{"op":"snapshot","action":"config"} |
nex snapshot config |
{"op":"snapshot","action":"create","path":"/nex/home/mario","label":"prima"} |
nex snapshot create --name prima |
{"op":"cron","action":"list"} |
nex cron list |
{"op":"lock-list"} |
nex lock list |
{"op":"devlist"} |
nex devices |
Complete example: 09_richiesta.c.
15. Errors
| Code | Value | Meaning |
|---|---|---|
NEX_OK |
0 | succeeded |
NEX_ERR_PARAM |
-1 | invalid parameters (NULL pointer, empty argv...) |
NEX_ERR_CONNECT |
-2 | agent not reachable |
NEX_ERR_IO |
-3 | connection with the agent interrupted |
NEX_ERR_AGENT |
-4 | the agent refused the request; the reason is in *response or in nex_errmsg() |
NEX_ERR_LOST |
-5 | job or node lost: outcome unknown |
NEX_ERR_TIMEOUT |
-6 | nex_wait: the job is still running |
NEX_ERR_NOTFOUND |
-7 | nex_wait: the job does not exist (any more); nex_kv_get: the key is not there |
NEX_ERR_CONFLICT |
-8 | nex_kv_cas: someone else wrote first, the value is not the expected one |
nex_strerror(code) gives the text of the code. Some typical reasons
for NEX_ERR_AGENT:
directory /tmp is not under /nex: a command for another node must start in/nex;unknown node X;root may not use nex run;root only.
16. The examples
The examples are in /usr/share/doc/libnex-dev/examples/ (in the
sources: docs/esempi/libnex). They are built
with make and tried on a cluster node, from a folder in /nex:
cp -r /usr/share/doc/libnex-dev/examples ~/esempi && cd ~/esempi && make
./02_spawn_wait 6
| Example | What it shows |
|---|---|
| 01_nodi.c | connecting, version, nodes, processes |
| 02_spawn_wait.c | spawn and wait in parallel, wait with a timeout |
| 03_run_uscita.c | remote command with live output and error, and exit code |
| 04_stdin_segnali.c | data on the remote stdin, SIGTERM to a remote command |
| 05_staccati.c | detached jobs: start, list, reattach, stop |
| 06_coda.c | parametric study in the job queue |
| 07_forward.c | connection to a service as seen from another node |
| 08_processi_log.c | finding a process, kill by PID, messages, logs |
| 09_richiesta.c | generic requests: services, alarms, snapshots, locks |
| 10_kv.c | key-value: a single winner among several processes, counter without lost updates |
Every release builds them and runs them on a test cluster before it is published.
17. Function list
| Function | Chapter |
|---|---|
nex_open, nex_close, nex_free, nex_version, nex_strerror |
3 |
nex_nodes, nex_nodes_detail, nex_nodes_want, nex_ps, nex_metrics |
4 |
nex_spawn, nex_spawn_ex, nex_wait, nex_errmsg, nex_spawn_image, nex_run_json_image, nex_run_detached_image, nex_submit_image |
5 |
nex_run_json, nex_run_json_tty, nex_run, nex_job_next, nex_job_write, nex_job_close_stdin, nex_job_signal, nex_job_resize, nex_job_free |
6 |
nex_run_detached, nex_jobs, nex_job_stop, nex_attach_json |
7 |
nex_submit, nex_queue, nex_queue_cancel |
8 |
nex_kill, nex_msg, nex_passwd |
9 |
nex_logs |
10 |
nex_forward_json |
11 |
nex_run_json_ex, nex_run_json_gfx, nex_job_x11_send, nex_job_x11_close, nex_job_wl_send, nex_job_wl_close, nex_run_json_av, nex_job_pa_send, nex_job_pa_close |
12 |
nex_kv_get, nex_kv_set, nex_kv_cas, nex_kv_del, nex_kv_list, nex_secret_get, nex_secret_set, nex_secret_del, nex_secret_list, nex_secret_free, nex_pub, nex_pub_ex, nex_sub_open, nex_sub_next, nex_sub_fd, nex_sub_close, nex_mq_push, nex_mq_pop, nex_mq_len |
13 |
nex_request |
14 |