# Creating and starting machines

> Describe machines in a Compose file, connect them, run programs in them, and install and check Windows services, desktop programs and tray programs.

A Compose file describes the machines a test needs. This one has a server, made from the [application layer](/docs/testing/images/#the-application-layer), and a client, made from the tools layer:

```yaml title="compose.yaml"
services:
  server:
    image: sample/server:1
    healthcheck:
      test: ["CMD", "curl.exe", "-fs", "http://127.0.0.1:8080/health"]
      interval: 5s
    networks: [lab]
  client:
    image: lab/tools:1
    depends_on:
      server:
        condition: service_healthy
    networks: [lab]
networks:
  lab: {}
```

```sh
endia compose -p "$run" up --wait --wait-timeout 900
endia compose -p "$run" ps
```

`up --wait` returns when every machine is running and ready, and healthy when it has a health check. Ready means Windows has booted, `testuser` is signed in and the [desktop helper](/docs/testing/core-concepts/#key-terms) is running. Here the server started first; the client started once the server's health check passed. The whole fleet took 49 seconds; one machine alone takes about 20. If a machine fails its health check, or the wait passes `--wait-timeout` seconds, `up` exits with 1.

- **Size.** A machine starts with 2 GiB of memory and grows to its `mem_limit`, or to 4 GiB when none is set. `cpus` sets its processors (default 2). Less than 2 GiB is refused.
- **Replicas.** `deploy: replicas: 3` gives `client-1` to `client-3`. Commands that act on one replica take `--index`, as in `endia compose exec --index 2 client ...`.
- **Main process.** A service with no `command` or `entrypoint` keeps running until you stop it, which suits most tests. A service with a `command` behaves like a container: when the program exits, the machine shuts down.
- **Other keys.** `environment`, `hostname`, `user`, `working_dir`, `labels`, `extra_hosts`, `restart`, `ports`, `volumes` and bind mounts are accepted; any other key is refused with `UNSUPPORTED_FIELD` and its name. `endia compose config` prints the file as East India reads it.

## Networks

- **Between machines.** Each network in the Compose file is a private Hyper-V switch with its own addresses (by default from `10.231.0.0/16`). Machines on the same network reach each other by service name, because East India writes the fleet's names into every machine's hosts file, between the lines `# eastindia begin` and `# eastindia end`. In the example, the client reaches the server with `curl.exe http://server:8080/health`. Windows' firewall in the server must let the port in, as the recipe's `New-NetFirewallRule` does.
- **To the internet and the PC.** Every machine also has a card named `internet` on the PC's `Default Switch`, unless all its networks are marked `internal: true`. Through it the machine reaches the internet and the PC itself. To reach a service on the PC, such as a database in Docker, give the PC a name with `extra_hosts: ["pc=host-gateway"]`. The service on the PC must listen on all of the PC's addresses, not only `127.0.0.1`, and the PC's firewall must let the connection in from the Default Switch.
- **From your test to a machine.** Publish a port with `ports: ["18080:8080"]`. East India then listens on the PC's `127.0.0.1:18080` and forwards each connection to the machine's port 8080. From a sandbox, connect to `host.docker.internal:18080` once the sandbox's policy allows `localhost:18080`. A port given without a published number gets a free one; `endia inspect <machine>` shows which.

## Running programs and copying files

```sh
endia exec "$run-server-1" powershell -NoProfile -Command "(Get-Service SampleService -ErrorAction Stop).Status"
endia exec "$run-client-1" curl.exe -fsS http://server:8080/health
```

`exec` runs a program in the machine, prints its output and exits with its exit code. It runs as SYSTEM, outside the desktop, so it cannot show a window; use `desktop launch` for that. `-d` starts the program and returns its process ID at once, `-u` runs it as another local account, and `-w` and `-e` set its folder and environment. Add `-ErrorAction Stop` to a PowerShell command that must fail the `exec` when it fails, because PowerShell's exit code is that of its last statement.

```sh
endia exec "$run-client-1" cmd /c "mkdir C:\apps"
endia cp ./publish/SampleDesktop "$run-client-1:C:/apps"            # the folder itself, into C:\apps
endia cp ./publish/. "$run-client-1:C:/apps"                         # the folder's contents
endia cp "$run-client-1:C:/ProgramData/EastIndiaSample" ./evidence   # back out of the machine
```

`cp` follows Docker's rules. The destination folder in the machine must exist first.

## Testing a Windows service

Install it in the image, as `server.Endiafile` does, or into a running machine:

```sh
m="$run-client-1"
endia exec "$m" cmd /c "mkdir C:\apps"
endia cp ./publish/SampleService "$m:C:/apps"
endia exec "$m" sc.exe create SampleService binPath= "C:\apps\SampleService\SampleService.exe" start= auto
endia exec "$m" sc.exe start SampleService
endia exec "$m" powershell -NoProfile -Command "(Get-Service SampleService).WaitForStatus('Running','00:00:30'); (Get-Service SampleService).Status"
```

Check it in three ways, from the weakest to the strongest:

1. **Windows says it runs:** `Get-Service` above prints `Running`, or `sc.exe query SampleService` shows `STATE : 4 RUNNING`.
2. **It does its job:** call it from inside the machine (`endia exec "$m" curl.exe -fsS http://127.0.0.1:8080/health`), from another machine by name, or from your test through a published port.
3. **It logged what you expect:** read the Windows event log, where a .NET service writes under its own name:

   ```sh
   endia exec "$m" powershell -NoProfile -Command "Get-WinEvent -FilterHashtable @{LogName='Application'; ProviderName='SampleService'} -MaxEvents 5 | Format-List TimeCreated,Message"
   ```

An MSI installs the same way: copy it in, then run `endia exec "$m" msiexec /i C:\apps\MyApp.msi /quiet /norestart`. `msiexec /x ... /quiet` removes it.

## Testing a desktop or tray program

Copy the program in with `cp`, as above, or bake it into the image. Then start it on `testuser`'s desktop:

```sh
pid=$(endia desktop launch "$m" 'C:\apps\SampleDesktop\SampleDesktop.exe' | jq -r .processId)
```

`desktop launch` prints JSON: the process ID (`processId`), its start time, its session (1, `testuser`'s), its user, its integrity level and its windows. Put `--` before program arguments that start with `-`. `--elevated` asks for administrator rights, which `testuser`, a standard user, does not have. For a program that asks for elevation itself, answer the prompt as [Elevation prompts](/docs/testing/driving-the-screen/#elevation-prompts) describes.

**A desktop program** shows a window, so check both that its process runs and that its window is up:

```sh
endia process inspect "$m" "$pid" | jq '.[0] | {running, sessionId, windows: [.windows[] | select(.visible) | .title]}'
endia desktop windows "$m"     # every visible window: process, handle, position, size, title
```

**A tray program** has no visible window, only an icon in the notification area. Check that its process runs in the desktop session, and check something it does, such as a file, a log line or a port it opens:

```sh
tray=$(endia desktop launch "$m" 'C:\apps\SampleTray\SampleTray.exe' | jq -r .processId)
endia process inspect "$m" "$tray" | jq '.[0] | {running, sessionId}'   # running: true, sessionId: 1
endia exec "$m" cmd /c type C:\ProgramData\EastIndiaSample\tray.txt    # the time it last wrote
```

To work the icon itself, use [`desktop tray`](/docs/testing/driving-the-screen/#notification-area-icons).

## Waiting for a program to finish

`endia process wait "$m" "$pid"` waits until the process ends and prints its exit code, as `docker wait` does. It works for a program started by `desktop launch` or `exec -d`. East India knows the exit code only of a program it started since the machine last booted, so for any other process the command fails. `--timeout <seconds>` limits the wait. When the time passes first, the command exits with 1 and writes `Error response from EastIndia: Process <pid> was still running after <seconds> seconds. (TIMEOUT)` to standard error, and the process keeps running.

On success, `process wait` exits with 0 and prints only the exit code, followed by a line break. It prints the code in full, never reduced to 256 values: 3010 prints as `3010`. Windows exit codes from 0x80000000 upwards print as negative numbers, so a crash with 0xC0000005 prints as `-1073741819`.

```sh
code=$(endia process wait --timeout 180 "$m" "$pid")   # 0 when the program succeeded
```

**Telling a program's exit code from an East India failure.** `exec` exits with the program's own exit code, so an exit code alone cannot say whether 1, 125, 126, 127 or 130 came from the program or from East India. Standard error does not settle it either, because the program's own error output arrives there too. To keep the two apart, start the program with `exec -d` and wait for it with `process wait`:

- Each of the two commands exits with 0 when its request succeeds.
- When the service refuses the request or cannot be reached, the command exits with 1 and writes an East India message to standard error.
- A program that is not found, or cannot start, makes `exec -d` fail with `NOT_FOUND` or `CAPABILITY_MISSING`.
- The program's exit code appears only on `process wait`'s standard output, and `endia process logs "$m" "$pid"` prints what the program wrote.

```sh
pid=$(endia exec -d "$m" msiexec /i C:\apps\MyApp.msi /quiet /norestart)
code=$(endia process wait "$m" "$pid")   # 3010: installed, restart needed
```
