mcl_core_singleton (mcl_core v1.0.0)

View Source

Run a side effect on exactly one node of a cluster (mcl-om#8, A3 package 3).

Every node of a cluster runs the same release, so a service that sends a mail, ticks a timer or calls out to the world would do it once per node. Wrap that work in a singleton instead: put

mcl_core_singleton:child_spec(my_mailer, {my_mailer, start_link, []})

in the service's supervisor on every node. Each node starts a guard. The guard that registers the global name {mcl_core_singleton, Name} first starts the work (apply(M, F, A), which returns {ok, Pid} and links it); the others stand by, watching the holder. When the holder goes away (its node stops, or the work dies and the guard with it) a standby registers the name and starts the work on its own node.

TWO HOLDERS THAT MEET. Nodes that started apart each hold the name; when they connect, global finds the clash and calls resolve/3, which keeps the holder on the node whose name sorts first and tells the other to stand down: it stops its work and stands by.

On a node without distribution (a standalone release) there is no one to share with: the guard registers the name and runs the work, as any child.

A NETSPLIT RUNS ONE COPY PER PARTITION. global sees only the nodes it is connected to, so while a cluster is split each connected part elects a holder of its own; when the parts meet again, resolve/3 keeps one. A side effect that must never run twice, even across a split, needs more than this.

The work's start function answers as a supervisor child's does: {ok, Pid} or {ok, Pid, Info} runs it, ignore gives the name up and the guard ends as a child that was ignored, {error, Reason} stops the guard.

Summary

Functions

The child spec a service's supervisor lists, on every node.

global's resolver for two holders of one name: the holder on the node whose name sorts first keeps it, the other stands down.

The work's pid, on whichever node runs it, or undefined while no node does.

Functions

child_spec(Name, MFA)

-spec child_spec(term(), {module(), atom(), [term()]}) -> supervisor:child_spec().

The child spec a service's supervisor lists, on every node.

handle_call(Msg, From, State)

handle_cast(Msg, S)

handle_info(Msg, State)

init(_)

resolve(GlobalName, Pid1, Pid2)

-spec resolve(term(), pid(), pid()) -> pid().

global's resolver for two holders of one name: the holder on the node whose name sorts first keeps it, the other stands down.

start_link(Name, MFA)

-spec start_link(term(), {module(), atom(), [term()]}) -> {ok, pid()} | ignore | {error, term()}.

terminate(Reason, State)

whereis(Name)

-spec whereis(term()) -> pid() | undefined.

The work's pid, on whichever node runs it, or undefined while no node does.