# Run commands and move files

A program that has an API key can run commands in a machine and move files without an SSH client or an SSH key. The requests go through the API to an agent inside the machine. The machine must be running, or the request fails with `machine_not_running`.

The examples use a machine named `calm-river-otter` and read the API key from `ARVM_API_KEY`.

## Run a command

```console
$ arvm exec calm-river-otter -- uname -r
```

The command's output goes to your terminal, and its exit code becomes the exit code of `arvm exec`. What follows `--` is the command and its arguments, not a shell line: for a pipe or `&&`, run `sh -c` in the machine. [CLI](cli.md#arvm-exec) has the flags.

The same through the API:

```console
$ curl -s -X POST "https://api.arvm.dev/v1/machines/calm-river-otter/exec" \
    -H "Authorization: Bearer $ARVM_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"command": ["uname", "-r"]}'
```

The response arrives when the command exits:

```json
{
  "exit_code": 0,
  "stdout": "6.8.0-48-generic\n",
  "stderr": "",
  "truncated": false,
  "timed_out": false,
  "oom_killed": false,
  "duration_ms": 41
}
```

`command` is a list of arguments, not a shell line. No shell reads it, so `*`, `|` and `&&` have no special meaning.

## Run a shell line

To use pipes, redirects or `&&`, run a shell and give it the line:

```console
$ curl -s -X POST "https://api.arvm.dev/v1/machines/calm-river-otter/exec" \
    -H "Authorization: Bearer $ARVM_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"command": ["sh", "-c", "cd /srv/app && make test"], "timeout_seconds": 600}'
```

## Set the user, the directory, the environment and the input

| Field | Default | What it sets |
|---|---|---|
| `user` | `dev` | The user the command runs as. Use `root` for a command that needs it. |
| `working_dir` | The user's home directory | The directory the command starts in. |
| `env` | None | Variables added to the machine's `env` for this command. |
| `stdin` | None | Text written to the command's standard input, which is then closed. It may hold a NUL. It cannot hold bytes that are not UTF-8: to give a command binary input, [write it to a file](#write-a-file) and redirect from the file. |
| `timeout_seconds` | 30 | The command is killed after this long. At most 3,600. |

```console
$ curl -s -X POST "https://api.arvm.dev/v1/machines/calm-river-otter/exec" \
    -H "Authorization: Bearer $ARVM_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"command": ["tee", "/etc/motd"], "user": "root", "stdin": "Staging. Ask before you reboot.\n"}'
```

## Read the result

| Field | Meaning |
|---|---|
| `exit_code` | The command's exit status. A command that a signal ended reports 128 plus the signal number. |
| `timed_out` | `true` when `timeout_seconds` passed and the command was killed with SIGKILL. `exit_code` is then 137. |
| `oom_killed` | `true` when the kernel killed a process of the command because memory ran out. |
| `truncated` | `true` when `stdout` or `stderr` passed 8 MiB and was cut. |

A command that exits with a status other than zero is still a successful API request with status 200. Check `exit_code`. A program that is not found exits 127, and one that is not executable exits 126, with the reason on `stderr`, as a shell reports them.

A 200 always means that the command ran in the machine. Only the API's own answers say what happened to the command: a 200, or one of these problem documents (`application/problem+json`):

| Answer | What happened | What to do |
|---|---|---|
| `machine_unreachable` (503) | The request could not be sent to the machine's server. Nothing ran. | Send it again after `Retry-After`. |
| `invalid_request` (400) | The machine refused the command, for example for a `user` that does not exist. Nothing ran. | Fix the request. |
| `exec_outcome_unknown` (502) | The request reached the server's connection, and then no sign that the command started came back within 10 seconds (or within `timeout_seconds`, if that is shorter), or the connection was lost before the command's exit. It may not have started, may have run to its end, or may still be running. There is no exit code. | Check what the command changes before you run it again. |

Any other answer says nothing about the command, and the command may have run. That includes an answer the API did not write, such as a 502 or 504 from a proxy or from the gateway in front of the API, whose body is not a problem document, even when it has a `Retry-After`, and a connection that ends with no answer. Treat it as `exec_outcome_unknown`.

Output is text. Bytes that are not UTF-8 are replaced. To get binary output, write it to a file in the machine and [read the file](#read-a-file).

## Stream the output

With `"stream": true` the response is a server-sent event stream. Output arrives while the command runs.

```console
$ curl -sN -X POST "https://api.arvm.dev/v1/machines/calm-river-otter/exec" \
    -H "Authorization: Bearer $ARVM_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"command": ["sh", "-c", "cd /srv/app && make test"], "timeout_seconds": 600, "stream": true}'
```

```text
event: stdout
data: {"data":"go test ./...\n"}

: keepalive

event: stderr
data: {"data":"warning: no test files\n"}

event: exit
data: {"exit_code":0,"timed_out":false,"oom_killed":false,"duration_ms":5210}
```

The response is 200 only after the command has started. A command that does not start gets the same error as without `stream`.

The last event says how the command ended. It is `exit`, or `outcome_unknown` when the connection to the command was lost after it started. A stream with no sign of a start gets `exec_outcome_unknown` as a 502, before any 200. A stream that ends or breaks after the 200 without its last event leaves the same unknown: the command had started. The data of `outcome_unknown` is the same problem as `exec_outcome_unknown`, with no exit code.

A line that starts with a colon, such as `: keepalive`, is a comment and not an event. The API sends one every 15 seconds, so a command that prints nothing for a long time keeps its stream open through proxies that close idle connections.

A stream cannot be resumed. If your connection drops, the command is killed.

## Run a job that outlives the request

A command ends when its request ends: at `timeout_seconds`, or when a stream's connection drops. A command also owns what it starts. When the command exits, the machine kills every process that the command left running. A job that you start with `&`, `nohup` or `setsid` is killed when the command exits, and the response still shows an `exit_code` of 0.

Before you start a long job, [turn idle stop off](machines.md#change-or-turn-off-idle-stop). Sustained CPU work above the idle threshold keeps the machine awake, but a job that sleeps, waits on I/O, or uses very little CPU does not.

For a job that takes longer than an hour, or that must survive a dropped connection, give the job to systemd with `systemd-run`:

```console
$ curl -s -X POST "https://api.arvm.dev/v1/machines/calm-river-otter/exec" \
    -H "Authorization: Bearer $ARVM_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"command": ["sudo", "systemd-run", "--unit=release", "--uid=dev", "--gid=dev", "--working-directory=/srv/app", "sh", "-c", "make release > /home/dev/release.log 2>&1"]}'
```

The response arrives at once, with `Running as unit: release.service` in `stderr`. The job runs as the user `dev` in a systemd unit named `release`, and writes its output to `/home/dev/release.log`. [Read the file](#read-a-file) to follow the job.

The job gets neither the request's `env` nor the machine's `env`. To set a variable, add `--setenv=NAME=value` before `sh`. To get the machine's `env`, run the line with `bash -lc` in place of `sh -c`.

Ask systemd for the state of the job:

```console
$ curl -s -X POST "https://api.arvm.dev/v1/machines/calm-river-otter/exec" \
    -H "Authorization: Bearer $ARVM_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"command": ["systemctl", "is-active", "release"]}'
```

| `stdout` | The job |
|---|---|
| `active` | Is running. |
| `inactive` | Is not running. The job ended with exit status 0, or you stopped it, or no job has this name. |
| `failed` | Ended with another exit status, or a signal killed it. |

Read the state from `stdout`. The `exit_code` of this command is 0 only while the job is `active`.

To stop the job, send the command `["sudo", "systemctl", "stop", "release"]` the same way.

A unit name is free again when its job is `inactive`. After `failed`, send `["sudo", "systemctl", "reset-failed", "release"]` before you start a job with the same name.


For a job that must restart after a reboot, write a systemd unit. The machine runs systemd like any server.

## Write a file

The request body is the file's content, as bytes.

```console
$ curl -s -X PUT "https://api.arvm.dev/v1/machines/calm-river-otter/files?path=/home/dev/app/.env&make_parents=true&mode=0600" \
    -H "Authorization: Bearer $ARVM_API_KEY" \
    -H "Content-Type: application/octet-stream" \
    --data-binary @.env
```

| Parameter | Default | Meaning |
|---|---|---|
| `path` | Required | An absolute path in the machine. |
| `mode` | `0644` | Permission bits in octal, applied when the file is created. |
| `make_parents` | `false` | Create missing parent directories. |

The file is owned by the user `dev`. Writing to a path that exists replaces the content. The response describes the file as written.


## Read a file

The response body is the file's content, as bytes.

```console
$ curl -s "https://api.arvm.dev/v1/machines/calm-river-otter/files?path=/home/dev/app/.env" \
    -H "Authorization: Bearer $ARVM_API_KEY" \
    -o .env
```

A path that does not exist fails with `file_not_found`. A path that is a directory fails with `not_a_file`.

## List a directory

```console
$ curl -s "https://api.arvm.dev/v1/machines/calm-river-otter/files/list?path=/home/dev/app" \
    -H "Authorization: Bearer $ARVM_API_KEY"
```

The response lists the entries of that one directory, by name, with each entry's type, size, mode and modification time. The list does not go into subdirectories. A path that is not a directory fails with `not_a_directory`.

## Delete a file or a directory

```console
$ curl -s -X DELETE "https://api.arvm.dev/v1/machines/calm-river-otter/files?path=/home/dev/app/.env" \
    -H "Authorization: Bearer $ARVM_API_KEY"
```

A directory that is not empty fails with `directory_not_empty`. Add `recursive=true` to delete a directory with everything in it:

```console
$ curl -s -X DELETE "https://api.arvm.dev/v1/machines/calm-river-otter/files?path=/home/dev/app&recursive=true" \
    -H "Authorization: Bearer $ARVM_API_KEY"
```

## When a request fails

| Code | Status | Meaning |
|---|---|---|
| `machine_not_running` | 409 | The machine is stopped. Start it first. |
| `machine_unreachable` | 503 | The machine's server does not answer. Try again. |
| `exec_outcome_unknown` | 502 | For `exec` only: whether the command ran is unknown. It may not have started, may have run, or may still be running. Check its effects before you run it again. |
| `file_not_found` | 404 | No file is at the path. |
| `not_a_file` | 409 | The path is a directory. |
| `not_a_directory` | 409 | The path is a file. |
| `directory_not_empty` | 409 | Delete with `recursive=true`. |


[The machines reference](api/machines.md#run-a-command-in-a-machine) lists every field.
