NEXItaliano

NEX › Documentation › Cluster services — nex service

Cluster services — nex service

By Roberto Arato of aratoingegneria.it

A service is a program that must stay running: a web server, an API service, a processing daemon. You describe it once in a JSON file and NEX takes care of the rest:

  • it starts it on the compute nodes, in the number of copies (instances) you ask for, on different nodes when it can;
  • it checks that it responds (TCP port, HTTP page or a command of yours) and restarts it if it crashes or stops responding;
  • if a node shuts down, it moves its instances to another node;
  • if a node goes into maintenance (drain), it moves the instances without interruption: the new one starts and responds before the old one stops;
  • when you change the definition, it updates the instances one at a time, and moves on to the next only when the one just updated responds.

How it differs from the other ways of launching programs:

Command What for If the program ends
nex run a command now, attached to the terminal finished
nex run -d a long job detached from the terminal finished, the output stays to be read
nex submit a queued job, starts when there is room finished, result in nex queue
nex service a program that must stay running restarted, always

Contents

  1. The first service
  2. The definition
  3. Health checks
  4. Restarts
  5. Replicas and nodes
  6. Changing a service: rolling update
  7. Viewing the status
  8. Draining a node and nodes that fail
  9. Virtual addresses and names
  10. Cluster locks and a single primary
  11. Who can do what
  12. Examples
  13. How it works inside
  14. Limits of this version
  15. Command summary

1. The first service

A small web server with two instances. Prepare the folder (always inside /nex, the shared filesystem: every node must see it):

mkdir -p /nex/home/$USER/sito
echo "ciao dal cluster" > /nex/home/$USER/sito/index.html
echo ok > /nex/home/$USER/sito/ok.txt

Write the definition in /nex/home/$USER/sito.json:

{
  "name": "sito",
  "description": "il mio sito di prova",
  "command": ["python3", "-m", "http.server", "8080"],
  "cwd": "/nex/home/anna/sito",
  "replicas": 2,
  "port": 8080,
  "health": { "type": "http", "path": "/ok.txt" }
}

and send it to the cluster:

$ nex service apply sito.json
service sito created (revision eafbd68e71c3)
$ nex service list
SERVICE              USER       HEALTHY  REVISION      COMMAND
sito                 anna       2/2      eafbd68e71c3  python3 -m http.server 8080
  sito@0                 node-a:3e64bc      running                  6s  restarts 0    node-a:8080
  sito@1                 node-b:95d4f7      running                  6s  restarts 0    node-b:8080

leader: node-a; nodes: node-a node-b

Two instances, one per node, both healthy. The addresses to reach them:

$ nex service endpoints sito
node-a:8080
node-b:8080

To remove it: nex service remove sito.

2. The definition

A JSON object (or an array of objects, to define several services with a single file). Unknown keys are an error: a misspelled "replica" does not slip through silently.

Key Required Meaning Default
name yes service name: 1-32 characters among a-z, 0-9, -, _
description free text
command yes command and arguments, as an array: ["prog", "arg1"]
cwd yes working directory, inside /nex
user root only user it runs as; a normal user can only give themselves whoever runs apply
env environment variables: ["NAME=value", ...]
replicas number of instances, from 1 to 32 1
nodes allowed nodes: ["node-a", "node-b"] all compute nodes
cpu CPU limit in percent of one core, as a string: "150" none
mem memory limit: "512M", "2G" none
port port the service responds on (for endpoints and for the checks)
health health check (chapter 3) none
restart waits between restarts (chapter 4) 2 s, up to 60 s

Each instance also receives in its environment NEX_SERVICE (name), NEX_INSTANCE (instance number, from 0) and NEX_SERVICE_REV (revision).

The service runs as a detached job of the user (the same as nex run -d): with their permissions, within their quotas, never as root.

3. Health checks

Without health an instance counts as healthy when it has been running for 2 seconds. With health NEX really checks it:

type What it checks Extra keys
tcp the port accepts connections on 127.0.0.1 port (or the service's)
http GET of the path answers 2xx or 3xx port, path (default /)
cmd a command of yours exits with 0 command: array

The cmd command runs on the instance's node as your user, never as root.

The timings, all in seconds:

Key Meaning Default
grace wait after start before the first check 10
interval how often a healthy instance is checked 10
timeout maximum time of a check (1-30) 3
retries consecutive failed checks before the restart 3

Until an instance is healthy it is checked at every round (2 seconds). After retries consecutive failures the instance is unhealthy and is restarted.

"health": { "type": "http", "path": "/salute", "interval": 5, "timeout": 2, "retries": 3, "grace": 15 }

4. Restarts

An instance that exits, for any reason and with any code, or that does not pass the checks, is restarted on the same node. Between one restart and the next the wait doubles: delay, 2×delay, 4×delay... up to max_delay. This way a program that does not start does not occupy the node in a continuous loop. After 60 seconds of good health the wait goes back to the minimum.

"restart": { "delay": 1, "max_delay": 30 }

In nex service list the restarts column counts the instance's restarts and the line below gives the last reason, for example exited with code 1 or GET /ok.txt: 404.

5. Replicas and nodes

With "replicas": N NEX keeps N instances running, numbered from 0 to N-1, and puts them on different nodes when it can: it chooses the node with the fewest instances of the same service, then the one with the fewest instances overall. If there are fewer nodes than replicas, some instances share a node. In that case watch out for ports: two instances on the same port and on the same node cannot both start.

With "nodes" you restrict the allowed nodes, for example for a service that needs a device attached to a specific node:

"nodes": ["node-b"]

To change the number of replicas just change replicas and run apply again. The extra instances stop; the new ones start.

6. Changing a service: rolling update

Edit the file and run apply again:

$ nex service apply sito.json
service sito updated (revision 70d8995378a7): rolling update, one instance at a time

NEX does not stop everything at once. It updates instance 0. When the new version is healthy it moves on to instance 1, and so on. Meanwhile the other instances keep responding. In nex service list the instances still on the old version show their revision (rev ...). If you apply an identical file again it answers unchanged and restarts nothing.

To restart everything without changing anything, again one instance at a time:

nex service restart sito

If the new version never becomes healthy, the update stops there. The other instances stay on the old version, which works. You fix the file and run apply again.

7. Viewing the status

nex service list              # all your services (root: all)
nex service list sito         # just one
nex service list --json       # everything, in JSON, for scripts
nex service endpoints sito    # node:port of the healthy instances, one per line

Instance states (as shown by nex service list):

State Meaning
starting started, the checks have not passed yet
running healthy
unhealthy too many failed checks: about to be restarted
waiting to restart exited or unhealthy: restarts after the wait
error did not start (reason in the line below)
handing over leaving the node: stays running until the new one is healthy
no node no node can host it right now
silent node the node gives no news

Each instance is a detached job (NODE:JOB in the table), so the job tools work too:

nex jobs                      # instances appear as detached jobs
nex attach node-a:3e64bc      # the latest output (up to 1 MB) of an instance; Ctrl-] to detach

In the dashboard (dashboard.md) the Services tab shows the same information and refreshes by itself every 5 seconds:

  • the services, with the healthy instances out of those requested: green if all, yellow if some, red if none;
  • the instances, with state, node, job, restarts, address and last message;
  • the leader and the compute nodes, with the silent or drained ones.

Each user sees their own services, root sees all. On storage-only nodes the shared filesystem is not there, and the tab says to open the dashboard of a compute node.

8. Draining a node and nodes that fail

Drain (planned maintenance, root only):

sudo nex service drain node-b      # the services leave node-b
sudo nex service undrain node-b    # node-b is available again

The instances leave the node one at a time per service. The new one starts on another node, and the old one stays running (state handing over) until the new one is healthy. The service never stops responding.

Services with port. Two instances on the same node would compete for the port, so the replicas of a service with port are always on different nodes. If during a drain there is no other free node (for example 2 replicas on 2 nodes), the instance on the drained node stops and stays waiting: the service runs with one replica less, and the virtual address stays on the other one. The instance stops only after the virtual address has moved to the other healthy instance; if the other one is still starting, it waits for it to be healthy (at most 60 seconds). It restarts by itself when a node becomes available again.

nexctl leave does this by itself. Before detaching a node from the cluster it puts the services drain in place and waits for the instances to have moved elsewhere, up to drain_timeout + 60 seconds. The next nexctl join removes that drain. A drain set by hand with nex service drain, instead, stays until you run undrain.

A node that fails (switched off, network lost, agent stopped): every node gives a sign of life every 2 seconds. After 15 seconds without signs the node is silent and its instances are started on other nodes. If the node comes back, the instances left there stop by themselves, because by now they are assigned elsewhere.

9. Virtual addresses and names

Whoever uses a service from outside (a PC, another program) should not need to know which node it is running on at the moment. That is what virtual addresses (VIPs) are for: an IP address that NEX puts on a live node and moves by itself when needed. They are managed by root only:

sudo nex vip add web 10.20.0.51/24 --service sito   # follows the "sito" service
sudo nex vip add cluster 10.20.0.50/24              # on any live compute node
nex vip list                                        # who holds what, since when
sudo nex vip remove web
$ nex vip list
NAME             ADDRESS             SERVICE        NODE          SINCE  ALLOWED NODES
cluster.nex      10.20.0.50/24       -              node-a          12m  all
web.nex          10.20.0.51/24       sito           node-b           3m  all
  • With --service the address is always on a node where an instance of the service is healthy. If the instance moves because of a drain, a failed node or an update, the address follows it. Clients always use 10.20.0.51, or web.nex.
  • Without --service it stays on a live compute node. It is useful as the "cluster" address, for example for the dashboard or to log in with ssh.
  • With --publish 8080[,8443...] the address offers the cluster ports nex:8080 to the outside: the program can listen on nex:8080 on any node, even one other than the node holding the address, and the port follows it when it moves. It is requested port by port: listening on nex never makes anything visible outside the cluster. With --proxy-protocol the service receives the real client address first (PROXY protocol v1, understood for example by nginx and HAProxy). For a very busy service --service remains better, as it puts the address on the service's node, with no hop in between: you choose service by service.
  • --nodes node-a,node-b restricts the allowed nodes; --interface ens34 chooses the interface. Without --interface NEX uses the one that already has an address in the same subnet.

When a node takes the address it announces it with gratuitous ARP, so PCs and switches immediately update where to send packets. The move takes a few seconds.

Cluster names. Every agent keeps in its node's /etc/hosts a block managed by NEX, refreshed every 10 seconds:

# BEGIN NEX: cluster names, managed by nexagentd (do not edit)
10.20.0.10      node-a.nex
10.20.0.11      node-b.nex
10.20.0.12      nex-stor.nex
10.20.0.51      web.nex
# END NEX

On the cluster nodes curl http://web.nex:8080/ always works, wherever the service runs. The rest of /etc/hosts is not touched. The names of the virtual addresses appear on the compute nodes, which read the shared filesystem; storage-only nodes have the node names. A PC outside the cluster uses the address, or adds it to its own hosts file.

Safety against duplicate addresses. A virtual address on two nodes at once would confuse the network. NEX avoids it this way:

  • when the agent stops, even because of a crash (ExecStopPost of the unit), the node removes its virtual addresses;
  • a node that loses the shared filesystem (nexctl leave) removes them immediately;
  • a node isolated from the storage removes them after about 30 seconds: 20 without a successful round, plus the confirmation that the NEXFS meta nodes do not answer it either;
  • the leader gives the address of a silent node to another node only after 25 seconds of observation without errors, when that node has already removed it. In the isolation test there was never a duplicate.

How long a move takes (lab measurements):

  • Address bound to a service, drain or nexctl leave: no interruption. The new node takes the address and announces it, and the old one keeps it for about 5 more seconds. The old instance stops only afterwards. If in those 5 seconds the address goes back to the old node, the old node announces it again with gratuitous ARP.
  • Free address on a node that shuts down suddenly, or whose agent stops: reachable again after about 27 seconds, the 25 of waiting plus one round.
  • Restart of the agent on the node holding an address (upgrade): the unit removes it on stop and the new agent puts it back after a few seconds. Upgrades are therefore done one node at a time, after a drain.

10. Cluster locks and a single primary

Some things must happen only once in the whole cluster:

  • a single copy of a program that writes a file;
  • a single "primary" among the replicas of a service;
  • a single maintenance at a time on a shared resource.

nex lock starts a command only once it has taken a cluster lock and releases it when the command ends. It is like flock, but it applies across all nodes.

nex lock backup -- ./backup.sh            # waits for its turn, then runs
nex lock --nowait backup -- ./backup.sh   # if the lock is taken exits immediately with 75
nex lock --timeout 60 backup -- ./backup.sh   # waits at most 60 s (then 75)
nex lock list                             # held locks: node, token, since when, command
$ nex lock --nowait backup -- ./backup.sh
nex lock: lock backup busy (held by a process on node-a)
$ echo $?
75
  • Names are per user. Your backup and another user's are different locks, so nobody can block yours.
  • Exit code: that of the command; 75 if the lock was taken or the wait expired; 76 if the lock was lost while the command was running.
  • In the command's environment: NEX_LOCK_NAME, NEX_LOCK_NODE and NEX_LOCK_TOKEN, the fencing token: a number that grows at every acquisition of the lock.

What happens if something goes wrong. The lock is a lease: the node's agent renews it every 2 seconds and it expires after 15 seconds without renewal.

  • The command ends, or you press Ctrl-C: the lock is released immediately.
  • nex is killed: the command dies with it and the lock is released.
  • The node's agent dies: nex stops the command immediately (code 76). The lock expires by itself after at most 15 seconds and another node takes it.
  • The node loses the storage (network, isolation): the agent can no longer renew the lock. After 10 seconds it notifies nex, which stops the command with SIGTERM, and with SIGKILL after 3 more seconds, before the lock expires. Another node can take it only afterwards, so two commands never run at the same time.

The fencing token covers the last case, the rarest: a frozen node (a paused virtual machine) that wakes up after the lock has passed to another. A resource that wants to be safe records the highest token it has seen and rejects whoever brings a lower one:

# writes only if its own token is not older than the last one seen
nex lock dati -- sh -c '
  ultimo=$(cat /nex/progetto/.token 2>/dev/null || echo 0)
  [ "$NEX_LOCK_TOKEN" -gt "$ultimo" ] || exit 1
  echo "$NEX_LOCK_TOKEN" > /nex/progetto/.token
  ./aggiorna-dati'

A single primary among the replicas of a service. Every replica launches the program "as primary" through nex lock. Only one takes the lock and becomes primary; the others wait. If the primary fails, the lock passes to another replica, which becomes primary in turn:

{
  "name": "coda-ordini",
  "command": ["nex", "lock", "coda-ordini-primario", "--", "/nex/home/anna/bin/elabora-ordini"],
  "cwd": "/nex/home/anna",
  "replicas": 2
}

The two instances run on different nodes. One processes the orders; the other waits for the lock, and the health check without health considers it healthy anyway. If the primary exits, nex service restarts it, and the restarted one starts waiting in turn.

11. Who can do what

  • Every user can define services for themselves and sees, changes, restarts and removes only their own.
  • root sees and manages all services. When it defines one it must give "user", because services never run as root.
  • Only root drains and undrains nodes and manages virtual addresses (nex vip add, remove); everyone can see nex vip list.
  • Service names are unique across the whole cluster: if a name already belongs to another user, apply refuses it.

12. Examples

A service without a port, checked by a command. A processor that writes a heartbeat file every 10 seconds. The check verifies that the file is recent:

{
  "name": "elaboratore",
  "command": ["/nex/home/anna/bin/elabora", "--coda", "/nex/home/anna/coda"],
  "cwd": "/nex/home/anna",
  "env": ["LIVELLO_LOG=info"],
  "health": { "type": "cmd", "command": ["sh", "-c", "test $(( $(date +%s) - $(stat -c %Y /nex/home/anna/battito) )) -lt 30"],
              "interval": 15, "grace": 20 },
  "restart": { "delay": 5, "max_delay": 120 }
}

A service pinned to a node, with limits.

{
  "name": "lettore-seriale",
  "command": ["/nex/home/anna/bin/lettore", "/devnodes/node-b/dev/ttyUSB0"],
  "cwd": "/nex/home/anna",
  "nodes": ["node-b"],
  "cpu": "50",
  "mem": "256M"
}

Several services in one file (an array):

[
  { "name": "api", "command": ["/nex/home/anna/bin/api", "--porta", "9000"], "cwd": "/nex/home/anna",
    "replicas": 2, "port": 9000, "health": { "type": "tcp" } },
  { "name": "pulizia", "command": ["/nex/home/anna/bin/pulizia", "--ogni", "3600"], "cwd": "/nex/home/anna" }
]

From a script: a client that uses any instance.

for e in $(nex service endpoints api); do
  curl -sf "http://$e/stato" && break
done

13. How it works inside

For the administrator. The state is not kept in files under /nex but in the control store of NEXFS, in key tables:

  • svc.defs the definitions;
  • svc.assign where each instance must run;
  • svc.status/<node> the state of that node's instances;
  • svc.nodes the signs of life;
  • svc.drained the drained nodes;
  • svc.vips the virtual addresses and svc.vipassign the node holding each one;
  • svc.leader the leader lock;
  • queue the job queue of nex submit.

The control store is built to coordinate nodes: every write is durable, atomic compare operations and expiring locks apply across all nodes, and a node that cannot reach the storage gets an error within 8 seconds instead of waiting. To look at the state by hand (as root, on a cluster node):

nexfsctl kv tables                       # the tables
nexfsctl kv list svc.assign              # the assignments
nexfsctl lock owner svc.leader leader    # who is the leader

Every compute node has an agent, and among the agents only one acts as leader: it decides the assignments. The leader holds an expiring lock of 15 seconds in the svc.leader table and renews it every 2. If the leader fails the lock expires by itself, without the need for that node to be alive to release it, and the first agent that tries takes it. A node isolated from the storage can neither renew it nor take it, so there are never two leaders.

How long recovery takes after the sudden failure of a node. If the node is also a NEXFS node (compute and storage node together), the storage recovers by itself within a few seconds: writes continue on the other copies and, if it was the leader of the meta nodes, the others elect a new one. The NEX leader then waits 15 seconds for instances, or 25 for free addresses, of observation without errors before declaring the node silent. This way, on recovery, heartbeats left stale during the pause do not make all nodes look dead. On a compute-only node this pause does not happen. During the pause the watchdog does not remove the virtual addresses of healthy nodes: it first asks the NEXFS meta nodes whether the majority answers, and if it does, the slowness is the storage's and not the node's.

Every agent runs the instances assigned to it, checks them, restarts them and writes their state. After a restart of the agent it takes over the instances still running, without restarting them. The agent log (journalctl -u nexagentd) records every step with the prefix nex service.

14. Limits of this version

  • Stateless services. If a node loses contact with the storage but stays on, its instances may stay running while the leader starts others: for a while there are two copies. For a web server that is fine, for a database it is not. Databases and services with their own data will have dedicated adapters, with fencing, in the next part of phase 8.
  • The cmd check runs on the instance's node, outside the service's CPU and memory limits: it must be lightweight.
  • An instance's output is the last 1 MB kept by its job (nex attach). For long logs the program should write to a file.
  • A program that ignores SIGTERM keeps its node's agent busy until systemd kills it (90 s): meanwhile the other instances on that node are not checked.
  • The dashboard shows the services but does not change them: it is read-only.

15. Command summary

Command What it does
nex service apply FILE creates or updates (FILE - = standard input)
nex service list [NAME] [--json] services, instances, state, leader, nodes
nex service endpoints NAME node:port of the healthy instances
nex service restart NAME rolling restart
nex service remove NAME removes the service and stops the instances
sudo nex service drain NODE moves the services off the node, without interruption
sudo nex service undrain NODE the node is available again
sudo nex vip add NAME IP[/P] [--service SVC] [--publish P,...] [--proxy-protocol] virtual address (and name NAME.nex); --publish: the cluster ports nex:P offered to the outside
nex vip list virtual addresses and the nodes holding them
sudo nex vip remove NAME removes the virtual address
nex lock [--nowait or --timeout S] NAME -- CMD runs CMD while holding a cluster lock
nex lock list held locks

nex svc is a synonym of nex service; ls and rm stand for list and remove.