Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 140 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,98 @@
# README
# simple-rpc

Zero setup RPC for distributed deployment and orchestration.

## How it works

simple-rpc calls a function on another machine the same way you already
run a command there: over ssh, and with `sudo` or `su` to run it as
another user. There is no always-running RPC server, no port to open,
and no package to install or configuration to change on the machine.

The server is a command line executable. It is a Haskell program
consisting of a collection of plain Haskell functions called endpoints;
each endpoint works like an independent command. Think of the executable
as a collection of custom commands which can be executed on a machine to
perform any task.

The client is a Haskell program. It calls an endpoint on a machine just
like a local Haskell function, by running the server executable on that
machine over ssh. You can also run the server executable yourself, like
any other command.

The only thing a machine needs is a copy of the server executable, which
the client can copy over ssh using `installOnRemote`. Therefore, this is
a zero setup RPC.

The output of a call on one machine can be used seamlessly as the input
of a call on another, so a deployment or a configuration change that
spans several machines can be written as a simple Haskell program.

## Usage

**Step 1: define endpoints.** Export a function as an endpoint with
`rpcExport`. The argument and result types must have `ToJSON` and
`FromJSON` instances:

```haskell
module Module1 (printFromModule1) where

import Simple.RPC

raw_printFromModule1 :: Int -> String -> Bool -> IO (Int, String, Bool)
raw_printFromModule1 val1 val2 val3 = ...

$(rpcExport "raw_printFromModule1" "printFromModule1")
```

This defines `printFromModule1`, the endpoint named
`Module1.printFromModule1`.

**Step 2: generate the endpoint map.** `simple-rpc-generate` generates
the `RpcMap` module, which lists all the endpoints of a library. It
reads the Template Haskell dump files of the library, so the library
must be built with `ghc-options: -ddump-to-file -dth-dec-file`. The
configuration file gives the build directory of the library, its source
directories and the module to generate; see `generate/README.md`:

```
cabal build lib:example
cabal run simple-rpc-generate -- rpcConfig.json
```

**Step 3: build the server.** Add `RpcMap` to the `other-modules` of the
server executable and call `mainWith` in its `main`:

```haskell
import RpcMap (rpcMap)
import Simple.RPC (mainWith)

main :: IO ()
main = mainWith "0.1.1" rpcMap
```

The first argument of `mainWith` is the version of the executable. The
client checks it before each call.

**Step 4: call the endpoints.** The client imports the endpoint and
calls it with `runAt`:

```haskell
import Simple.RPC
import Module1 (printFromModule1)

main :: IO ()
main = do
let remote = ("user@host", "22")
exe = Executable "/opt/simple-rpc/example-server" "0.1.1"
installOnRemote
(Executable "./example-server" "0.1.1") remote (executablePath exe)
r <- runAt (setRemote remote (defaultConfig exe)) printFromModule1
22 "Test" True
print r
```

## Example

See `example` for an example application. `example/app/RpcMap.hs` is
generated by `simple-rpc-generate` from `example/rpcConfig.json`:
Expand All @@ -8,19 +102,59 @@ cabal build lib:example
cd example && cabal run simple-rpc-generate -- rpcConfig.json
```

## Pre-requisites
`distBuildDir` in `example/rpcConfig.json` contains the platform and the
GHC version (`x86_64-linux/ghc-9.10.3`); edit it to match yours.

## Prerequisites

* Remote machine should be accessible via ssh for some user(s). For
The server executable is built on a build machine and installed on the
target machines. The target machines must have the same OS and
architecture as the build machine, and compatible versions of the shared
libraries that the executable links to, unless it is statically linked.
When the endpoints use Haskell libraries such as streamly-coreutils
instead of external programs, the target machines need no other packages
installed.

* The remote machine must be accessible via ssh for some user(s), for
example, by adding the user's public key to the user's
$HOME/.ssh/authorized_keys file.
`$HOME/.ssh/authorized_keys` file.
* The login shell of the ssh user must be a POSIX shell.
* The shell startup files of the ssh user (e.g. `.bashrc`) must not print
anything to stdout, otherwise the version check fails.
* The client runs ssh with `-o "StrictHostKeyChecking off"`, so it does
not verify the host key of the remote machine.
* To avoid putting the user's private key on each machine, ssh agent
forwarding can be used to forward the keys from one machine to another.
* Need a `sudo` capable user on each remote machine for:
The client does not enable it; set `ForwardAgent yes` in the ssh
configuration for the hosts that need it.
* A user with passwordless `sudo` is needed on each remote machine for:
* installing the rpc executable
* running commands as an arbitrary user

## Usage as a CLI
ssh runs without a terminal, so `sudo` cannot prompt for a password.
* An endpoint function must not read stdin; the server reads its input
from stdin.

## Using the server as a command

The server executable can be used as a CLI command to invoke any
endpoint from the command line. The endpoint name is the argument, the
JSON array of the function arguments is read from stdin, and the result
is printed as JSON on the last line of stdout:

```
echo '[22, "Test", true]' | cabal run example-server -- "Module1.printFromModule1"
```

Running the executable without arguments prints its version.

## Distributed scripting in Haskell

Your client program is essentially a Haskell script to perform the
tasks. Only the functions that run on another machine need to be
endpoints; all other function calls are local. An endpoint running on
a remote machine can in turn call endpoints on other machines. For
remote to remote calls, the remote machine needs ssh access to the
other machines, e.g. via ssh agent forwarding. By using modular
functions as endpoints, you can orchestrate a distributed computing
task.
203 changes: 203 additions & 0 deletions dev/design-issues.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
# Design issues

Problems with the design of simple-rpc, with proposed changes that have a
wide design impact. The proposed changes are not implemented.

## ssh host key checking is disabled

Every ssh command uses `-o "StrictHostKeyChecking off"`. ssh then accepts
the key of a host it has not seen before without asking, and a man in the
middle on the first connection is not detected. Proposal: make the option
a field of `RunningConfig`, with the default `accept-new`, which accepts
only the key of a new host and refuses a changed key.

## Two processes for each call

`runAt` runs the server executable twice for each call, once without
arguments for the version check and once for the endpoint. For a remote
host this is two ssh connections for each call. The version check also
runs without `sudo` and `su`, it can check a different executable from
the one that the endpoint call runs, e.g. when the `PATH` of the user
differs.

Proposal: the client passes the expected version as an argument of the
endpoint call, e.g. `EXE --version VERSION ENDPOINT`. The server compares
`VERSION` with its own version before it reads stdin, and exits with an
error if they differ. One process, and one ssh connection, for each call.
The version is checked by the process that runs the endpoint, with the
same `sudo`, `su` and `PATH`. The server does the comparison, therefore
the output of the shell startup files of the ssh user does not affect it.

The client must distinguish a version mismatch from other server errors,
to raise `VersionMismatch` with the version of the server. The server
needs a distinct exit code or the structured error line proposed in
"Server errors reach the client only as an exit code".

A server of the current version raises `InvalidUsage` for more than one
argument, before it runs the endpoint. A new client calling an old server
fails without running the endpoint, but only with `ProcessFailure 1`. The
client can either require a new server or, after this failure, fall back
to the separate version check.

`installOnRemote` can use the same mechanism to check the remote copy,
see "installOnRemote copies the local executable": call an endpoint that
does nothing, with the version argument.

## Identify the executable by its sha256

Goal: the version of the server executable is the sha256 of the
executable file, instead of a string chosen by the user, e.g. `"0.1.0"`,
and passed to `mainWith`.

A user chosen version string does not detect a changed executable when
the user does not change the string, e.g. a rebuild after a code change.
Two builds of the same source give different sha256 values, and the
check then requires exactly the file that the client expects.

* The server computes the sha256 of its own file, from
`getExecutablePath`, only when the client passes the expected version.
Hashing reads the whole file on each call, an estimated 50 to 100 ms for
a 50 MB executable, not measured.
* The server can cache the hash in a file keyed by the path, size,
modification time and status change time (ctime) of the executable. A
user cannot set the ctime, a replaced file gets a new ctime and is
hashed again. The cache must be in a directory that the server user can
write, e.g. `$XDG_CACHE_HOME`, not next to the executable, which is in a
directory owned by root after `installOnRemote`. Add the cache only if
the measured cost of hashing matters.
* Alternative, not preferred: embed a build ID in the executable at build
time.
* The client gets the expected sha256 from the local executable, or from
the user when the executable for the remote host is built elsewhere,
e.g. for another OS or CPU architecture.
* The hash is hexadecimal, it needs no quoting on the command line.
* `installOnRemote`, or a replacement for it, can compare the sha256 of
the remote file with the local one, and copy the executable only when
they differ, see the `XXX` notes in `Simple.RPC.Internal.Types` and
`Simple.RPC.Client`.

## The result is the last line of stdout

The output of the endpoint and the result share stdout, the client takes
the last line as the result. Output that reaches stdout after the result,
e.g. from a background process started by the endpoint that inherited
stdout, replaces the result. Logs of a nested `runAt` call inside an
endpoint, written with the default `putStrLn` logger, are also part of
this stdout. Proposal: write the result after a marker line that the
endpoint output cannot produce, or on a separate file descriptor for a
local server.

## Server errors reach the client only as an exit code

An `EndpointNotFound` or `InvalidInput` exception in the server makes the
client raise `ProcessFailure 1`, the message is only in the logged
stderr. Proposal: the server writes a structured error line, and the
client raises the corresponding `RpcException`.

## The input and output are buffered

The server reads the whole input line into memory, the client keeps the
whole last output line and the whole stderr of the server in memory.
`invokeFunction` reads stdin in blocks, the bytes after the input line in
the last block are lost to the endpoint. Proposal: stream the arguments
and the result, and log the stderr lines as they arrive.

## setUser and useSudo together

With both, the endpoint is run as `sudo su USER -c 'sudo EXE ...'`, the
user must be allowed to use sudo. A source comment already notes that the
two options should not be combined. The user is also given in two places,
`user@host` in `setRemote` and `setUser`. Proposal: one field with a sum
type: the current user, another user with `sudo -u USER`, or root.

## Types of the exported fields

`evaluator` returns an `RpcEval`, and the `call` field of `RpcSymbol`
takes a `Runner`. Neither type is exported, a user cannot write a type
signature for these values, and Haddock does not link them. Proposal:
export both types, `RpcEval` without its constructor.

`rcImageFlags` is a `String` split at white space, a flag cannot contain
white space. `rcRemote` is a pair of strings, the port is a `String`.
Proposal: `[String]` for the flags and a record with a numeric port for
the remote.

## installOnRemote logging and privileges

`installOnRemote` logs with `putStrLn`, a `RunningConfig` logger is not
used, and it needs sudo even for a directory that the ssh user can write.
Proposal: take a `RunningConfig`, use its logger, and use sudo only when
`useSudo` is set.

## Windows

The client and the server run on Windows, and a Windows client can call a
POSIX host with `setRemote`. The following do not work on Windows, the
documentation states the limits:

* `useSudo` and `setUser` without `setRemote` run `sudo` and `su` on the
local host. Windows has no `su`, and the `sudo` of Windows 11 has
different options.
* A Windows remote host: the remote commands are POSIX shell commands, the
default shell of the Windows OpenSSH server is `cmd.exe`.
* `installOnRemote` from a Windows client, see the next section.
`scpLocalPath` also prefixes `./` to a path with a drive letter, e.g.
`C:\build\server.exe`, because of the colon.

Proposal: raise a named exception for the unsupported cases on Windows
instead of running a command that fails, and do not prefix `./` to a path
with a drive letter on Windows.

## installOnRemote copies the local executable

`installOnRemote` runs the local executable for the version check and
copies the same file to the remote host. The remote host must run that
file: the same OS and CPU architecture, and, for a dynamically linked
executable, compatible versions of the shared libraries, e.g. glibc,
libgmp and libffi. A macOS executable does not run on Linux, an executable
from a Linux distribution with a newer glibc may not run on an older one,
and a Windows executable does not run on a POSIX host. The local host must
also run it, for the version check.

`installOnRemote` does not run the remote copy, the failure shows up at
the first `runAt`: the version check exits with a non-zero exit code and a
loader error on stderr, and `runAt` raises a `ProcessFailure` exception.

Proposal: check the version on the remote host after the copy, so that an
executable that does not run there is reported by `installOnRemote`, and
do not run the local executable. Document that the executable must be
built for the remote host, e.g. statically linked.

## External commands

The external commands that each mode needs are listed in `design.md`.
Changes that remove some of them:

* `scp` and `mktemp` in `installOnRemote`. The executable can be sent on
the stdin of a single ssh command, e.g.
`t=$(mktemp) && cat > "$t" && sudo mkdir -p DIR &&
sudo install -m 755 "$t" PATH; r=$?; rm -f "$t"; exit $r`.
This removes `scp` and `scpLocalPath`, the `./` prefix that
`scpLocalPath` adds to a Windows path with a drive letter, and two of the
three ssh connections. `mktemp` is still used, but in the same shell, no
path is returned to the client.
* `su` in `setUser`. `sudo -u USER EXE ARGS` runs the executable as the
user without the shell of the user: no POSIX shell is needed for the
user, no quoting, and the rc file of the user is not run. It is the
"another user" case of the sum type proposed in "setUser and useSudo
together".
* Shell startup output in the version check. With the expected version
passed as an argument of the endpoint call, proposed in "Two processes
for each call", the server compares the version, the client does not
parse it from stdout.

Commands that stay:

* `ssh` on the local host for `setRemote`. Replacing it with an ssh library
would add a C dependency, e.g. libssh2, and lose the user ssh config,
agent and keys that the `ssh` command uses.
* A shell on the remote host. ssh always passes the command to the login
shell of the ssh user. Only the quoting depends on the shell; quoting for
`cmd.exe` would allow a Windows remote host, see "Windows".
* `sudo` for `useSudo`, `setUser`, and `installOnRemote` to a directory
that the ssh user cannot write.
Loading
Loading