# Run a sidecar beside your service

> Write a small Go sidecar, mark it as one and add it to an environment, whose deployments bring a copy of it to each of its hosts.

You have a service, `Billing`, deployed to `Billing/Prod` on a host group, and you want a small program next to it on every host it runs on: here a watchdog, `HelloSidecar`, that says every half minute whether Billing is up and answers.

In this tutorial you write it in Go, release it, make it a [sidecar](../concepts/sidecars.md), and add it to `Billing/Prod`. From then on, each deployment of `Billing/Prod` brings its copy to each host where it changed. At the end you take it off again.

## Before you start {#before}

- **A service deployed to hosts:** here `Billing/Prod`, targeting the host group `web`, with `web-1` and `web-2`. It runs as a systemd service, from an archive, as every release does today.
- **The command line, logged in:** `plinto login`.

## Write the sidecar {#write}

**Its package**
In the Code app, **New package**: name it `HelloSidecar` and pick the template **Go service**. plinto makes its git repository, with a Go program and its test.

**Its code**
Get it into a workspace on your `main` group:

```sh
$ plinto workspace create sidecars --version-group main
$ cd sidecars
$ plinto workspace add HelloSidecar
```

Replace its program with the sidecar. It reads what plinto gives each copy: `PLINTO_BESIDE`, the environment it runs beside, its service's name and port, and `LOGS_FOLDER`, a value of its own:

```go file=src/HelloSidecar/src/main.go
// HelloSidecar: a copy runs beside each environment that adds it, and every EVERY seconds says whether its
// service is active, and whether its port answers.
package main

import (
	"fmt"
	"net"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"time"
)

func main() {
	every := 60 * time.Second
	if seconds, err := strconv.Atoi(os.Getenv("EVERY")); err == nil && seconds > 0 {
		every = time.Duration(seconds) * time.Second
	}
	for {
		fmt.Println(report())
		time.Sleep(every)
	}
}

func report() string {
	var parts []string
	if unit := os.Getenv("PLINTO_BESIDE_UNIT"); unit != "" {
		parts = append(parts, unit+" is "+active(unit))
	}
	if port := os.Getenv("PLINTO_BESIDE_PORT"); port != "" {
		if answers(port) {
			parts = append(parts, ":"+port+" answers")
		} else {
			parts = append(parts, ":"+port+" doesn't answer")
		}
	}
	return fmt.Sprintf("HelloSidecar %s beside %s on %s: %s; LOGS_FOLDER=%s", os.Getenv("PLINTO_VERSION"),
		os.Getenv("PLINTO_BESIDE"), os.Getenv("PLINTO_HOST"), strings.Join(parts, ", "), os.Getenv("LOGS_FOLDER"))
}

// The service's state: a copy runs as its environment's service does, as the user's service or the system's.
func active(unit string) string {
	for _, args := range [][]string{{"--user", "is-active", unit}, {"is-active", unit}} {
		out, _ := exec.Command("systemctl", args...).Output()
		if state := strings.TrimSpace(string(out)); state != "" && state != "inactive" {
			return state
		}
	}
	return "inactive"
}

func answers(port string) bool {
	conn, err := net.DialTimeout("tcp", net.JoinHostPort("localhost", port), 2*time.Second)
	if err != nil {
		return false
	}
	_ = conn.Close()
	return true
}
```

Its test, `src/HelloSidecar/src/main_test.go`, checks `report()` with the variables set. `plinto build` in `src/HelloSidecar` builds and tests it; then commit and push.

**Its group**
A deployment deploys a group's main package, so the sidecar gets a version-group of its own. In the Groups app, **New group**: `hellosidecar`, branched from `main`.

In the Builds app, **New build**: the group `hellosidecar`, the package `HelloSidecar` at the commit you pushed, then **Build into hellosidecar…**. Once it's released, open the group and **Set the main package**: `HelloSidecar`.

## Make it a sidecar {#sidecar}

**The sidecar app**
In the Environments app, **New app**: name it `HelloSidecar` and tick **A sidecar**. Then **New sub-environment**: `Prod`.

**Its configuration**
On `HelloSidecar`, **Configuration**, **Edit**:

| Key | Value | |
|---|---|---|
| `EVERY` | `30` | |
| `LOGS_FOLDER` | `/var/log/app` | **Declared** |

**Declared** lets each environment adding it give its own value, from its own configuration. Leave **Deploy settings** without a health URL: this sidecar listens on nothing, so a copy that keeps running is healthy.

**Its release**
On `HelloSidecar/Prod`, **Pick a revision…**: the group `hellosidecar`, its newest revision, **Pick**. It goes to no server of its own:

```text
Picked HelloSidecar 1.0-1 for HelloSidecar/Prod: no environment names it yet
```

## Add it beside Billing {#add}

**Add it**
On `Billing/Prod`, the **Sidecars** card, **Add a sidecar**: `HelloSidecar/Prod`. The card says *added: Billing/Prod's next deployment brings it*. Nothing changes on the hosts yet.

**Deploy**
**Restart…** reviews what the deployment does. Under **Sidecars it brings**:

```text
HelloSidecar/Prod   HelloSidecar 1.0 #33   brings it → #33 on web-1 and web-2
```

**Restart**. On each host, once Billing is healthy again, one more step brings the copy:

```text
(9/9) HelloSidecar/Prod → #33
HelloSidecar/Prod → #33: HelloSidecar-1.0-1-linux-x64.tar.gz (2 MB) into Billing+Prod++HelloSidecar+Prod/releases/34
Started plinto-Billing_Prod__HelloSidecar_Prod.service - HelloSidecar beside Billing/Prod, deployed by plinto.
HelloSidecar 1.0-1 beside Billing/Prod on web-1: plinto-Billing_Prod is active, :8080 answers; LOGS_FOLDER=/var/log/app
It is running (no health-url to check)
```

The line before last is the sidecar's own, its first report.

**Read the card**
The **Sidecars** card now reads *✓ #33 on web-1 and web-2*, with `LOGS_FOLDER = /var/log/app, from HelloSidecar`. On a host, the copy's reports are in its journal, under the service named in the log:

```sh
$ journalctl --user -u plinto-Billing_Prod__HelloSidecar_Prod -f
```

## Give it Billing's own value {#declared}

Billing writes its logs to `/srv/billing/logs`, and the sidecar should know. In `Billing`'s configuration, add `LOGS_FOLDER = /srv/billing/logs`: as the sidecar declares the key, Billing's value wins.

The next **Restart…** reviews it under **Sidecars it brings**, *#33, its variables*, with `LOGS_FOLDER` edited. Once it's done, each copy says:

```text
HelloSidecar 1.0-1 beside Billing/Prod on web-1: plinto-Billing_Prod is active, :8080 answers; LOGS_FOLDER=/srv/billing/logs
```

Billing's other keys never reach it: only what the sidecar declares.

## Change the sidecar {#change}

Change its code, push, and **New build** into `hellosidecar` again; then **Pick a revision…** on `HelloSidecar/Prod`, the new revision. Every environment adding it brings the new release with its next deployment, *#33 → #35*, each at its own pace, and its pipeline's next deployment does too.

A copy that fails to start is a warning: Billing's deployment still succeeds, the copy keeps what it ran, and the warning shows on Billing's page until a deployment brings it fine.

## Take it off {#off}

On `Billing/Prod`, **Remove** on `HelloSidecar/Prod`. The next **Restart…** reviews it, *named no more: takes it off web-1 and web-2*, and each host ends with:

```text
(9/9) Take off HelloSidecar/Prod
Stopping plinto-Billing_Prod__HelloSidecar_Prod.service
Removed plinto-Billing_Prod__HelloSidecar_Prod.service
Removed /srv/plinto/Billing+Prod++HelloSidecar+Prod
```

## How it works {#how}

- **A sidecar environment picks; the environments adding it deploy.** Its release reaches a host only through a deployment of an environment there, which brings it where its copy differs.
- **Each copy is the environment's**: a service of its own in a folder beside the environment's, started with it when the host boots. A deployment that doesn't bring it leaves it running. Two environments on a host get two copies.
- **What a copy gets**: the sidecar's configuration, the environment's own values of the keys it declares, and where it runs, as `PLINTO_BESIDE`, `PLINTO_BESIDE_UNIT`, `PLINTO_BESIDE_PORT` and `PLINTO_BESIDE_HOME`.

- [Sidecars](../concepts/sidecars.md): what a sidecar is, and what each copy gets
- [Environments](../concepts/environments.md): where it's added
- [Go](../languages/go.md): the sidecar's language
