NEXItaliano

NEX › Documentation › NEX HTTP/JSON API

NEX HTTP/JSON API

By Roberto Arato of aratoingegneria.it

The API lets scripts and programs, even outside the cluster and in any language, read the state of the cluster and act with the permissions of a user: start and stop jobs, use the queue, manage services and snapshots. It is served by nex-dashd, the same HTTPS service as the dashboard, on every node: https://NODE:7443/api/v1/....

Together with libnex (the C library to use on the nodes), it is the developers section of the NEX site.

Contents

  1. The token
  2. Making a request
  3. Reads
  4. Actions
  5. Errors
  6. Security
  7. Examples

1. The token

A script authenticates with a token, which the user creates themselves on a cluster node:

umask 077
nex token create ci > ~/.config/nex/token              # read and actions, expires in 90 days
nex token create monitor --read-only --days 365 > ~/.config/nex/token.monitor
nex token list                                          # your own tokens, when they expire, last use
nex token revoke ci                                     # takes effect immediately, across the whole cluster
  • Only once. The secret (nex_ followed by 64 hexadecimal digits) is shown only at creation: NEX keeps only its SHA-256 fingerprint. It must be kept like a password, in a file readable only by its owner.
  • Expiry. Every token expires: 90 days by default, --days from 1 to 365. An expired token stops working by itself.
  • Limits. At most 20 tokens per user, each with a different name.
  • --read-only. Allows reads only, and is the right choice for monitoring.
  • Permissions. The token is worth exactly as much as its user, no more, no less: it sees the user's processes and jobs, stops only the user's jobs, creates snapshots only in the user's home. If the user is removed, their tokens are no longer valid.
  • Root. With nex token list root sees all tokens and with nex token revoke USER/NAME revokes any of them.

2. Making a request

curl --cacert ca.crt -H "Authorization: Bearer $(cat ~/.config/nex/token)" \
     https://node-a:7443/api/v1/nodes
  • TLS. The nex-dashd certificate is signed by the cluster CA (/etc/nex/pki/ca.crt on the nodes); from outside you need a copy of that file. The node name must be resolvable: the IP address alone is not enough.
  • Formats. You read with GET, you act with POST and DELETE. The body is JSON (Content-Type: application/json, at most 64 KiB) and the responses are JSON too.
  • Node. Any node will do: the responses concern the whole cluster.
  • Browser. Reads also work with the dashboard session, changes do not.

GET /api/v1/me says who you are:

{"api":1,"user":"mario","uid":20001,"admin":false,"read_only":false,"token":true,
 "node":"node-a","dashd":"1.4.0"}

3. Reads

Request Content Command-line equivalent
GET /api/v1/me who is calling
GET /api/v1/nodes nodes, load, CPU, memory, disks, space of /nex nex nodes, nxdf
GET /api/v1/ps the user's processes on all nodes (root: all) nxps
GET /api/v1/jobs detached jobs nex jobs
GET /api/v1/queue job queue nex queue
GET /api/v1/services services, instances, leader nex service list
GET /api/v1/alarms active alarms and recent history nex alarm
GET /api/v1/cron scheduled tasks nex cron list
GET /api/v1/locks cluster locks nex lock list
GET /api/v1/devices exported devices (/devnodes) nex devices
GET /api/v1/ports cluster ports on nex:PORT (127.77.0.1): port, node, uid nex ss --cluster
GET /api/v1/tokens your own tokens (without secrets) nex token list
GET /api/v1/snapshots?path=P snapshots of the protected folder containing P nex snapshot P
GET /api/v1/logs?node=&unit=&grep=&lines=&prio= journal logs nex logs
GET /api/v1/storage NEXFS state: health, nodes, blocks, space, traffic, data nodes nexctl storage status, nexfsctl health, nexfsctl node list
GET /api/v1/license edition, nodes in use out of the limit, expiry and modules, for everyone nex license --json
GET /api/v1/acct?from=YYYY-MM-DD&to=YYYY-MM-DD&user= usage per user: CPU of jobs and sessions, jobs, memory, space nex acct
GET /api/v1/audit?since=EPOCH&until=EPOCH&type=PREFIX&user=&limit= audit log: jobs and actions nex audit
GET /api/v1/metrics?node=&since=SECONDS&step=SECONDS measurement history: CPU, load, memory, network, disk of each node (30 days) nex history

The JSON formats are those described in libnex.md (chapters 4, 7, 8, 10). Example of GET /api/v1/snapshots?path=/nex/home/mario:

{"dir":"/nex/home/mario","rel":"",
 "snapshots":[{"name":"nex-20261006-1800","kind":"auto","when":"20261006-1800"},
              {"name":"man-20261006-1852-prima","kind":"manual","when":"20261006-1852"}]}

The history (GET /api/v1/metrics?node=node-a&since=600) gives one series per measurement, with one value per interval of step seconds starting from from (epoch); null where the node has no samples. Without step there are about 120 intervals; since ranges from 300 seconds to 30 days (6 hours if missing):

{"from":1791532140,"step":60,"points":10,
 "nodes":[{"node":"node-a",
           "cpu":[9.4,null,23.6,10.6,26.6,10.6,15.2,12.2,14.6,12.6],
           "load":[1.61,null,0.38,0.66,0.48,0.32,0.52,0.41,1.14,0.79],
           "mem":[39.5,null,39.8,39.2,39.5,39.4,39.3,39.3,39.2,39.3],
           "rx":[79225,null,85158,...],"tx":[43533,null,...],"disk":[...]}]}

cpu, mem and disk are percentages, load the one-minute load, rx and tx bytes per second (all interfaces except lo).

With &storage=1 the answer also has "storage": the history of NEXFS for the whole cluster (used and total bytes, read and write bytes per second, degraded blocks with missing copies, rebuild copies to remake, ok 1 when the state was ok), one sample per minute from the leader of the services.

4. Actions

They require a token that is not read-only. Every action ends up in the nex-dashd log with the user, the method and the path.

Jobs

POST /api/v1/jobs starts a detached job, like nex run -d:

{"argv":["./simula","--caso","3"], "cwd":"/nex/home/mario/progetto",
 "node":"any", "env":["OMP_NUM_THREADS=2"], "cpu":"200", "mem":"4G"}
  • Required fields: argv (array of strings) and cwd (a folder in /nex).
  • node: "any" = the least loaded node, a name, or empty for the node that receives the request.
  • cpu and mem: optional limits ("200" = two CPUs).
  • image: optional, an image from the cluster archive (nex image list): the job runs in a rootless Podman container, as the user, with /nex and the node's network. It also applies to the queue.
  • Response: {"node":"node-b","job":"3fa2c1","unit":"nex-job-3fa2c1"}.

The job's state is followed with GET /api/v1/jobs: state running, then exited with code.

DELETE /api/v1/jobs/NODE/JOB stops the job (only your own).

Queue

POST /api/v1/queue queues a job, like nex submit. The body is that of jobs, plus "prio" from 0 to 9 (default 5). cpu is also the reservation: the entry starts when a node has that many free CPUs. Response {"queue":"q1a2b3c","position":N}.

DELETE /api/v1/queue/QID removes an entry that is still waiting.

Services

Request Effect
POST /api/v1/services creates or updates a service; the body is the JSON definition from servizi.md
POST /api/v1/services/NAME/restart rolling restart, one instance at a time
DELETE /api/v1/services/NAME removes the service

Everyone manages their own services; root manages all.

Snapshots

Request Effect
POST /api/v1/snapshots with {"path":"/nex/home/mario","label":"prima"} manual snapshot (the folder's owner, or root)
DELETE /api/v1/snapshots?path=/nex/home/mario&name=man-20261006-1852-prima removes a manual snapshot

Files are restored on the cluster, with nex snapshot restore (see the user guide).

Alarms

POST /api/v1/alarms/ID/ack acknowledges an alarm (root only).

Data for programs: kv, messages, queues

They are the same data as nex kv, nex pub and nex mq, on behalf of the token's user. The space is chosen with space:

  • group:NAME: the space of a group;
  • cluster: everyone reads it, only root writes it;
  • without space: the personal space.
Request What
GET /api/v1/kv?key=K value of K: {"found","key","value","expires","modified","by"}
GET /api/v1/kv?prefix=P keys starting with P: {"items":[...]}
POST /api/v1/kv {"key","value",["ttl"],["if_absent"],["expect"],["space"]} writes; with if_absent or expect atomic across nodes, otherwise {"ok":false,"conflict":true,"current"}
DELETE /api/v1/kv?key=K removes K: {"ok":true,"existed"}
POST /api/v1/pub {"topic","message",["space"]} to all subscribers: {"delivered":N}
POST /api/v1/mq/push {"queue","message",["space"]} at the end of the queue
POST /api/v1/mq/pop {"queue",["wait"],["space"]} the first message, taken by one consumer only; {"found":false} if the queue stays empty (wait at most 300 s)
GET /api/v1/mq/len?queue=Q {"length":N}
H="Authorization: Bearer $(cat ~/.config/nex/token)"
curl -s -H "$H" -H 'Content-Type: application/json' \
     -d '{"key":"notte/capo","value":"ci-42","if_absent":true,"ttl":3600}' https://node-a:7443/api/v1/kv
curl -s -H "$H" 'https://node-a:7443/api/v1/kv?key=notte/capo'
  • Subscribing: not possible from the API, because it needs a connection that stays open. Use nex sub or the library's nex_sub_open.
  • Secrets: the API gives no access to secrets (nex secret), because a stolen token would give them all away.

5. Errors

Code When Body
200 success the response JSON
400 request refused (permissions, invalid values, non-existent resource) {"error":"reason"}, the same text as the nex commands
401 token missing, wrong, expired or revoked {"error":...} and WWW-Authenticate: Bearer
403 change with a read-only token or from the browser session {"error":...}
404 non-existent path {"error":...}
405 method other than GET, POST, DELETE {"error":...}
429 too many wrong tokens from the same address: 5 in 5 minutes, then a 5-minute wait {"error":...}
502 the node's agent does not respond {"error":...}

6. Security

  • Encryption. Everything goes over TLS, with the node's certificate signed by the cluster CA.
  • Secrets. The token's secret is never stored: the cluster's control store (table tokens) holds only its SHA-256. Whoever reads the store cannot derive the tokens.
  • Permissions. nex-dashd verifies the token and asks the agent for every action on behalf of the token's user. The agent accepts this delegation only from root (nex-dashd) and only for detached jobs, queue, services, alarms and snapshots. The rules are the same as for the nex commands, so a token cannot do anything its user cannot do: for example it does not run commands as root.
  • Browser. The dashboard cookie is valid only for reads: an external site cannot make a logged-in user's browser perform actions (CSRF).
  • Attempts. Wrong tokens count like failed logins.
  • Revocation. nex token revoke takes effect immediately on all nodes.

7. Examples

Shell: start a computation and wait for it to finish.

H="Authorization: Bearer $(cat ~/.config/nex/token)"
API=https://node-a:7443/api/v1
J=$(curl -s --cacert ca.crt -H "$H" -H 'Content-Type: application/json' \
      -d '{"argv":["./simula","--caso","3"],"cwd":"/nex/home/mario/progetto","node":"any"}' \
      $API/jobs)
NODE=$(echo "$J" | jq -r .node); JOB=$(echo "$J" | jq -r .job)
until curl -s --cacert ca.crt -H "$H" $API/jobs |
      jq -e --arg j "$JOB" '.nodes[].jobs[]? | select(.job==$j and .state=="exited")' >/dev/null; do
  sleep 5
done
echo "finished on $NODE"

Python: active alarms for a monitoring system.

import json, ssl, urllib.request

ctx = ssl.create_default_context(cafile="ca.crt")
token = open("/home/mario/.config/nex/token.monitor").read().strip()
req = urllib.request.Request("https://node-a:7443/api/v1/alarms",
                             headers={"Authorization": "Bearer " + token})
for a in json.load(urllib.request.urlopen(req, context=ctx))["alarms"]:
    print(("CRITICAL" if a["level"] >= 2 else "WARNING"), a["message"])

Shell: snapshot before a risky operation.

curl -s --cacert ca.crt -H "$H" -H 'Content-Type: application/json' \
     -d '{"path":"/nex/home/mario","label":"before-cleanup"}' $API/snapshots

The behaviour described here is verified on the test cluster at every release (P12.01.7P12.01.7).