Compare commits
14
Commits
009c4bc8d1
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe70100959 | ||
|
|
5ed2d33124 | ||
|
|
2fecad021b | ||
|
|
a05b98fdf5 | ||
|
|
ef126eaf61 | ||
|
|
920fa5e904 | ||
|
|
d4ed79115c | ||
|
|
9943d5f7b7 | ||
|
|
255b4cc299 | ||
|
|
3edfaa4ab2 | ||
|
|
d2717de47a | ||
|
|
6becd3462d | ||
|
|
3379ada59a | ||
|
|
25137eb5da |
@@ -0,0 +1,173 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
Guidance for Claude Code when working in this repository.
|
||||||
|
|
||||||
|
> User-facing docs are in Portuguese (BR): [README.md](README.md) and [docs/](docs/).
|
||||||
|
> This file is in English and is the technical source of truth for how the code works.
|
||||||
|
|
||||||
|
## What this is
|
||||||
|
|
||||||
|
A terminal UI (TUI) **installer** for the "App do Dono" **client middleware**. The
|
||||||
|
middleware runs on a tenant's infrastructure and brokers communication between the
|
||||||
|
tenant's servers and davinTI's **central server**.
|
||||||
|
|
||||||
|
The installer is a guided wizard that: checks Docker → logs into the private registry
|
||||||
|
→ pulls images → (optionally) sets up a WireGuard tunnel (`vproxy`) when there is no
|
||||||
|
public IP → collects configuration via terminal forms → generates config files
|
||||||
|
(`config.toml`, `envs`) → runs the Docker containers.
|
||||||
|
|
||||||
|
It is **not** the middleware itself — it only provisions and launches it via `docker`.
|
||||||
|
|
||||||
|
## Tech stack
|
||||||
|
|
||||||
|
- **Go 1.25**
|
||||||
|
- **Bubble Tea v2** (`charm.land/bubbletea/v2`) — Elm-architecture TUI runtime.
|
||||||
|
- **Bubbles v2** — `textinput`, `spinner` components.
|
||||||
|
- **Lip Gloss v2** — styling.
|
||||||
|
- **BurntSushi/toml** — read existing `config.toml` for form defaults.
|
||||||
|
- Module path: `git.davinti.com.br/davinTI/app-dono/tui`.
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
```
|
||||||
|
cmd/main.go Entry point; starts the Bubble Tea program.
|
||||||
|
internal/tui/
|
||||||
|
model.go Model struct, ConfigValues, loadConfig (defaults), InitialModel, Init.
|
||||||
|
steps.go step enum — the ordered wizard stages.
|
||||||
|
update.go Update: global keys + per-step dispatch (handlers).
|
||||||
|
view.go View: header + per-step body + help footer (AltScreen).
|
||||||
|
form.go Generic FormStep/FormField component (text/password/number/select).
|
||||||
|
cmds.go Msg types and async tea.Cmd wrappers around docker/file ops.
|
||||||
|
docker.go os/exec wrappers around the `docker` binary.
|
||||||
|
config.go Generates & writes config.toml and envs (+ numeric validation).
|
||||||
|
styles.go Lip Gloss palette/styles.
|
||||||
|
Makefile Multi-arch build + S3 publish.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Architecture (Model–Update–View)
|
||||||
|
|
||||||
|
- **Model** ([model.go](internal/tui/model.go)) holds all state: `currentStep`,
|
||||||
|
progress/error flags, one `FormStep` per form, and `configValues` (`ConfigValues`)
|
||||||
|
which accumulates each form's `map[string]string` output by section.
|
||||||
|
- **Update** ([update.go](internal/tui/update.go)) handles global messages
|
||||||
|
(`Ctrl+C`, window size, spinner tick) then dispatches on `currentStep` to per-step
|
||||||
|
handlers. Step transitions happen when a form returns `done == true` or when an
|
||||||
|
async completion message arrives.
|
||||||
|
- **View** ([view.go](internal/tui/view.go)) renders per-step.
|
||||||
|
- **Commands** ([cmds.go](internal/tui/cmds.go)) wrap every blocking op (docker calls,
|
||||||
|
file writes) as a `tea.Cmd` returning a `Msg`: `DockerCheckedMsg`,
|
||||||
|
`ImageDownloadFinishedMsg`, `ConfigFileMsg`, `DockerRunMsg`, `TickMsg`.
|
||||||
|
|
||||||
|
## Wizard flow
|
||||||
|
|
||||||
|
`steps.go` defines the order. See [docs/fluxo.md](docs/fluxo.md) for full detail.
|
||||||
|
|
||||||
|
1. `StepCheckDocker` — `exec.LookPath("docker")`. Missing → `StepDockerInstall`
|
||||||
|
(instructs manual install and exits; **never auto-installs Docker**).
|
||||||
|
2. `StepDockerLogin` → `StepDownloadImage` — `docker login` + `pull` of the app image.
|
||||||
|
These registry credentials are **reused** later for the vproxy image.
|
||||||
|
3. `StepIPQuestion` — "public IP available?"
|
||||||
|
- **Yes** → jump to `StepAppConfig`.
|
||||||
|
- **No** → vproxy block: `StepWireguardConfig` → `StepGenerateWireguardFile`
|
||||||
|
(writes `envs`) → `StepDownloadWireguard` → `StepRunWireguard`.
|
||||||
|
4. Config forms: `StepAppConfig` → `StepServerConfig` → `StepDatabaseConfig` →
|
||||||
|
`StepCertConfig`.
|
||||||
|
5. `StepReview` — shows all collected config; Enter confirms.
|
||||||
|
6. `StepGenerateFile` — writes `config.toml` (validates numeric fields first).
|
||||||
|
7. `StepRunDocker` — runs `app-dono-cliente` container.
|
||||||
|
8. `StepRunUpdater` — runs `app-dono-updater`, which auto-updates `app-dono-cliente`
|
||||||
|
whenever a new image is pushed to `:latest`.
|
||||||
|
9. `StepDone`.
|
||||||
|
|
||||||
|
### Navigation & error handling
|
||||||
|
|
||||||
|
- **Back navigation:** `Esc` returns to the previous *input* step. The Model keeps a
|
||||||
|
`history []step` stack; `advance(next)` pushes the current input step, `goBack()`
|
||||||
|
pops. `isInputStep` ([steps.go](internal/tui/steps.go)) gates which steps participate
|
||||||
|
— action/wait steps (downloads, file gen, container runs) are excluded so back never
|
||||||
|
re-enters a side-effecting step. `Esc` is handled globally in `Update`; forms don't
|
||||||
|
consume it. Form values survive going back because the `FormStep`s live on the Model.
|
||||||
|
- **Retry vs. fix:** transient failures (image pull, container run) offer `r` to re-run
|
||||||
|
just that command (`q`/other quits). Validation failures (file generation) route back
|
||||||
|
to the relevant form to correct the value instead of quitting.
|
||||||
|
|
||||||
|
## Key constants
|
||||||
|
|
||||||
|
In [update.go](internal/tui/update.go):
|
||||||
|
|
||||||
|
- `imageName = hub.davinti.com.br:443/app-dono/app-cliente:latest`
|
||||||
|
- `wireguardImageName = hub.davinti.com.br:443/davinti-vproxy:latest`
|
||||||
|
- `updaterImageName = docker:cli`
|
||||||
|
- `configPath = config.toml`, `wireguardConfigPath = envs`
|
||||||
|
|
||||||
|
In [docker.go](internal/tui/docker.go): `networkName = app-dono_app` (all containers
|
||||||
|
join this network; created on demand).
|
||||||
|
|
||||||
|
## Generated files
|
||||||
|
|
||||||
|
- **`config.toml`** — app config, bind-mounted at `/app/config.toml`. If present at
|
||||||
|
startup it seeds form defaults via `loadConfig`. Generated by `GenerateConfigTOML`.
|
||||||
|
- **`envs`** — vproxy/WireGuard env vars, passed via `--env-file`. Generated only when
|
||||||
|
there is no public IP. By `GenerateWireguardConfig`.
|
||||||
|
|
||||||
|
Both are gitignored.
|
||||||
|
|
||||||
|
## Containers
|
||||||
|
|
||||||
|
| Container | Image | Notes |
|
||||||
|
| ------------------ | -------------------- | -------------------------------------------------------- |
|
||||||
|
| `app-dono-cliente` | app-cliente | `<host port>:8080`, mounts config.toml + cert dir, `--restart unless-stopped`, runs as host uid:gid. |
|
||||||
|
| `vproxy` | davinti-vproxy | `--cap-add=NET_ADMIN`, `/dev/net/tun`, `--env-file envs`, only without public IP. |
|
||||||
|
| `app-dono-updater` | docker:cli | Not a third-party updater — a poll loop (`sh -c`) baked into the official `docker:cli` image, since Watchtower was archived upstream in Dec 2025 with no maintained successor recommended for production. Every `updaterPollIntervalSeconds` (300s) it `docker pull`s `app-dono-cliente`'s image, compares image IDs, and if changed, stops/removes/recreates the container using the exact same `docker run` argv as the original start (`appClienteRunArgs` in `docker.go`, shared by both call sites so they can't drift). Mounts `/var/run/docker.sock` and the host's `~/.docker/config.json` (written by the earlier `docker login`) for private-registry auth. Not on `app-dono_app` — only talks to the Docker daemon. |
|
||||||
|
|
||||||
|
`seccomp=unconfined` is added to either container when the "Modo Compatibilidade"
|
||||||
|
(`seccomp_unconfined`) select is `"Sim"` — for old machines.
|
||||||
|
|
||||||
|
## Gotchas (read before editing)
|
||||||
|
|
||||||
|
- **Port:** `config.toml` always writes `port = 8080` (hardcoded in
|
||||||
|
`GenerateConfigTOML`). The form's "Porta" value only sets the **host-side** port in
|
||||||
|
the `docker run` mapping (`<port>:8080`); inside the container the app always listens
|
||||||
|
on 8080.
|
||||||
|
- **Network name** is the `networkName` constant (`app-dono_app`) in
|
||||||
|
[docker.go](internal/tui/docker.go); use it rather than re-typing the literal.
|
||||||
|
- **Registry credentials** are collected once (login form) and reused for the vproxy
|
||||||
|
pull — no second prompt.
|
||||||
|
- Containers run detached and are verified with `docker inspect` for `running`; on
|
||||||
|
failure the last 20 log lines are surfaced.
|
||||||
|
|
||||||
|
## Build & run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run ./cmd # run from source
|
||||||
|
go build -o installer ./cmd # local binary
|
||||||
|
|
||||||
|
make build # multi-arch (linux/darwin/windows, amd64/arm64) → ./dist
|
||||||
|
make build VERSION=2.0.0
|
||||||
|
make clean
|
||||||
|
make push S3_BUCKET=<bucket> VERSION=<v> # sync dist/ to S3 (version + latest)
|
||||||
|
make release S3_BUCKET=<bucket> VERSION=<v> # per-binary copy with OS/arch naming
|
||||||
|
```
|
||||||
|
|
||||||
|
**Versioning:** `tui.Version` ([internal/tui/version.go](internal/tui/version.go))
|
||||||
|
defaults to `"dev"` and is stamped at build time via `VERSION_LDFLAG`
|
||||||
|
(`-X .../internal/tui.Version=$(VERSION)`) in the Makefile. `installer --version`
|
||||||
|
(or `-v`) prints it and exits before the TUI starts; it is also shown in the TUI
|
||||||
|
header. A plain `go build` leaves it as `"dev"`. The Makefile build rules have no
|
||||||
|
source deps, so `make build` will not rebuild existing `dist/` artifacts — run
|
||||||
|
`make clean` first when re-stamping a new VERSION.
|
||||||
|
|
||||||
|
Tests (`go test ./...`) cover the pure logic in
|
||||||
|
[config_test.go](internal/tui/config_test.go) (config.toml/envs generation + numeric
|
||||||
|
validation) and [form_test.go](internal/tui/form_test.go) (`FormStep.Values()`). The
|
||||||
|
docker wrappers, Update and View are not unit-tested — verify those by running
|
||||||
|
`go build ./...` and exercising the TUI manually. Fully running the installer requires
|
||||||
|
a working Docker daemon and registry access.
|
||||||
|
|
||||||
|
## Conventions
|
||||||
|
|
||||||
|
- User-facing strings in the TUI are **Portuguese (BR)**; keep new ones consistent.
|
||||||
|
- Keep code comments and identifiers matching the surrounding style (mixed
|
||||||
|
English identifiers, Portuguese user messages).
|
||||||
|
- When adding a wizard step: add it to `steps.go`, a handler in `update.go`, a render
|
||||||
|
branch in `view.go`, and any new `Msg`/`Cmd` in `cmds.go`.
|
||||||
@@ -5,29 +5,32 @@ S3_BUCKET ?=
|
|||||||
BINARY_NAME ?= installer
|
BINARY_NAME ?= installer
|
||||||
BUILD_DIR := ./dist
|
BUILD_DIR := ./dist
|
||||||
|
|
||||||
|
MODULE := git.davinti.com.br/davinTI/app-dono/tui
|
||||||
|
VERSION_LDFLAG := -X $(MODULE)/internal/tui.Version=$(VERSION)
|
||||||
|
|
||||||
ARCHS := linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 windows/amd64
|
ARCHS := linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 windows/amd64
|
||||||
|
|
||||||
build: $(addprefix $(BUILD_DIR)/$(BINARY_NAME)-, $(subst /,-,$(ARCHS)))
|
build: $(addprefix $(BUILD_DIR)/$(BINARY_NAME)-, $(subst /,-,$(ARCHS)))
|
||||||
|
|
||||||
$(BUILD_DIR)/$(BINARY_NAME)-linux-amd64:
|
$(BUILD_DIR)/$(BINARY_NAME)-linux-amd64:
|
||||||
@mkdir -p $(BUILD_DIR)
|
@mkdir -p $(BUILD_DIR)
|
||||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-extldflags -static" -o $@ ./cmd
|
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-extldflags -static $(VERSION_LDFLAG)" -o $@ ./cmd
|
||||||
|
|
||||||
$(BUILD_DIR)/$(BINARY_NAME)-linux-arm64:
|
$(BUILD_DIR)/$(BINARY_NAME)-linux-arm64:
|
||||||
@mkdir -p $(BUILD_DIR)
|
@mkdir -p $(BUILD_DIR)
|
||||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-extldflags -static" -o $@ ./cmd
|
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-extldflags -static $(VERSION_LDFLAG)" -o $@ ./cmd
|
||||||
|
|
||||||
$(BUILD_DIR)/$(BINARY_NAME)-darwin-amd64:
|
$(BUILD_DIR)/$(BINARY_NAME)-darwin-amd64:
|
||||||
@mkdir -p $(BUILD_DIR)
|
@mkdir -p $(BUILD_DIR)
|
||||||
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -o $@ ./cmd
|
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags="$(VERSION_LDFLAG)" -o $@ ./cmd
|
||||||
|
|
||||||
$(BUILD_DIR)/$(BINARY_NAME)-darwin-arm64:
|
$(BUILD_DIR)/$(BINARY_NAME)-darwin-arm64:
|
||||||
@mkdir -p $(BUILD_DIR)
|
@mkdir -p $(BUILD_DIR)
|
||||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -o $@ ./cmd
|
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="$(VERSION_LDFLAG)" -o $@ ./cmd
|
||||||
|
|
||||||
$(BUILD_DIR)/$(BINARY_NAME)-windows-amd64:
|
$(BUILD_DIR)/$(BINARY_NAME)-windows-amd64:
|
||||||
@mkdir -p $(BUILD_DIR)
|
@mkdir -p $(BUILD_DIR)
|
||||||
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o $@ ./cmd
|
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="$(VERSION_LDFLAG)" -o $@ ./cmd
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm -rf $(BUILD_DIR)
|
rm -rf $(BUILD_DIR)
|
||||||
|
|||||||
@@ -0,0 +1,234 @@
|
|||||||
|
# App do Dono — Instalador Cliente (TUI)
|
||||||
|
|
||||||
|
Instalador de terminal (TUI) que faz, em poucos passos guiados, a configuração e o
|
||||||
|
provisionamento do **middleware cliente** do "App do Dono". Esse middleware roda na
|
||||||
|
infraestrutura do **tenant** (cliente) e é responsável por intermediar a comunicação
|
||||||
|
entre os servidores do tenant e o **servidor central** da davinTI.
|
||||||
|
|
||||||
|
A ferramenta cuida de tudo de ponta a ponta: valida o Docker, autentica no registry
|
||||||
|
privado, baixa as imagens, coleta as configurações via formulários no terminal, gera
|
||||||
|
os arquivos de configuração (`config.toml` e `envs`) e sobe os containers necessários.
|
||||||
|
|
||||||
|
> Construído com [Bubble Tea](https://github.com/charmbracelet/bubbletea),
|
||||||
|
> [Bubbles](https://github.com/charmbracelet/bubbles) e
|
||||||
|
> [Lip Gloss](https://github.com/charmbracelet/lipgloss) (linha Charm v2).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sumário
|
||||||
|
|
||||||
|
- [App do Dono — Instalador Cliente (TUI)](#app-do-dono--instalador-cliente-tui)
|
||||||
|
- [Sumário](#sumário)
|
||||||
|
- [O que ele faz](#o-que-ele-faz)
|
||||||
|
- [Pré-requisitos](#pré-requisitos)
|
||||||
|
- [Como usar](#como-usar)
|
||||||
|
- [Navegação na interface](#navegação-na-interface)
|
||||||
|
- [Fluxo de instalação](#fluxo-de-instalação)
|
||||||
|
- [Conectividade: IP público vs. vproxy](#conectividade-ip-público-vs-vproxy)
|
||||||
|
- [Arquivos gerados](#arquivos-gerados)
|
||||||
|
- [Containers e rede Docker](#containers-e-rede-docker)
|
||||||
|
- [Build a partir do código](#build-a-partir-do-código)
|
||||||
|
- [Documentação adicional](#documentação-adicional)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## O que ele faz
|
||||||
|
|
||||||
|
O instalador conduz o operador por um assistente (wizard) no terminal que:
|
||||||
|
|
||||||
|
1. **Verifica o Docker** na máquina (encerra com instruções se não houver).
|
||||||
|
2. **Autentica** no registry Docker privado (`hub.davinti.com.br`).
|
||||||
|
3. **Baixa a imagem** do app cliente (`app-dono/app-cliente`).
|
||||||
|
4. Pergunta se a máquina possui **IP público**:
|
||||||
|
- **Sim** → segue direto para a configuração da aplicação.
|
||||||
|
- **Não** → configura o túnel **vproxy** (WireGuard) e sobe esse container antes.
|
||||||
|
5. Coleta, via formulários, as configurações de **aplicação, servidor, banco de dados
|
||||||
|
e certificados**.
|
||||||
|
6. **Gera o `config.toml`** e sobe o container `app-dono-cliente`.
|
||||||
|
7. Sobe o container **`app-dono-updater`**, que mantém o `app-dono-cliente`
|
||||||
|
atualizado automaticamente a cada novo push em `:latest`.
|
||||||
|
8. Exibe a confirmação de sucesso.
|
||||||
|
|
||||||
|
## Pré-requisitos
|
||||||
|
|
||||||
|
- **Docker** instalado e em execução na máquina de destino.
|
||||||
|
- O instalador **não** instala o Docker automaticamente — se não encontrar, ele
|
||||||
|
orienta a instalação manual e encerra.
|
||||||
|
- **Credenciais** do registry privado `hub.davinti.com.br`.
|
||||||
|
- **Token de inscrição** (enrollment token) gerado no painel web do App do Dono.
|
||||||
|
- Quando **não** houver IP público: dados do túnel **vproxy** (chave privada, IP
|
||||||
|
virtual, pre-shared key e mapeamento de proxy).
|
||||||
|
- Diretório local com os **certificados** mTLS do cliente (`client.crt`, `client.key`,
|
||||||
|
`ca.crt`).
|
||||||
|
|
||||||
|
## Como usar
|
||||||
|
|
||||||
|
Baixe o binário pré-compilado correspondente ao seu sistema operacional (distribuído
|
||||||
|
via S3 — veja o time de infraestrutura) e execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
chmod +x installer-linux-amd64
|
||||||
|
./installer-linux-amd64
|
||||||
|
```
|
||||||
|
|
||||||
|
Ou rode direto a partir do código-fonte:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run ./cmd
|
||||||
|
```
|
||||||
|
|
||||||
|
### Navegação na interface
|
||||||
|
|
||||||
|
| Tecla | Ação |
|
||||||
|
| ------------------ | ------------------------------------- |
|
||||||
|
| `Tab` / `↓` | Próximo campo |
|
||||||
|
| `Shift+Tab` / `↑` | Campo anterior |
|
||||||
|
| `←` / `→` | Alternar opção (campos de seleção) |
|
||||||
|
| `Enter` | Confirmar campo / avançar etapa |
|
||||||
|
| `Esc` | Voltar à etapa anterior |
|
||||||
|
| `r` | Tentar novamente (em telas de erro) |
|
||||||
|
| Qualquer tecla | Avançar em telas de status |
|
||||||
|
| `Ctrl+C` | Sair a qualquer momento |
|
||||||
|
|
||||||
|
## Fluxo de instalação
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────────────┐
|
||||||
|
│ Verifica Docker │ ──── não instalado ──► orienta instalação e encerra
|
||||||
|
└────────┬─────────┘
|
||||||
|
│ instalado
|
||||||
|
▼
|
||||||
|
┌──────────────────┐
|
||||||
|
│ Login Registry │
|
||||||
|
└────────┬─────────┘
|
||||||
|
▼
|
||||||
|
┌──────────────────┐
|
||||||
|
│ Baixa imagem │ (app-cliente)
|
||||||
|
│ app-cliente │
|
||||||
|
└────────┬─────────┘
|
||||||
|
▼
|
||||||
|
┌──────────────────┐
|
||||||
|
│ Tem IP público? │
|
||||||
|
└───┬──────────┬───┘
|
||||||
|
│ Sim │ Não
|
||||||
|
│ ▼
|
||||||
|
│ ┌──────────────────┐
|
||||||
|
│ │ Config. vproxy │ → gera "envs" → baixa imagem vproxy → sobe container vproxy
|
||||||
|
│ └────────┬─────────┘
|
||||||
|
│ │
|
||||||
|
▼ ▼
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ Config. Aplicação → Servidor → │
|
||||||
|
│ Banco de Dados → Certificados │
|
||||||
|
└────────────────────┬────────────────────┘
|
||||||
|
▼
|
||||||
|
┌──────────────────┐
|
||||||
|
│ Revisão (Review) │ ← esc volta para editar
|
||||||
|
└────────┬─────────┘
|
||||||
|
▼
|
||||||
|
┌──────────────────┐
|
||||||
|
│ Gera config.toml │
|
||||||
|
└────────┬─────────┘
|
||||||
|
▼
|
||||||
|
┌──────────────────┐
|
||||||
|
│ Sobe container │ (app-dono-cliente)
|
||||||
|
│ app-dono-cliente │
|
||||||
|
└────────┬─────────┘
|
||||||
|
▼
|
||||||
|
┌──────────────────┐
|
||||||
|
│ Sobe container │ (app-dono-updater,
|
||||||
|
│ de auto-update │ atualiza o app-cliente sozinho)
|
||||||
|
└────────┬─────────┘
|
||||||
|
▼
|
||||||
|
✅ Concluído
|
||||||
|
```
|
||||||
|
|
||||||
|
## Conectividade: IP público vs. vproxy
|
||||||
|
|
||||||
|
O middleware cliente precisa se comunicar com o servidor central. A forma de
|
||||||
|
conectividade depende da infraestrutura do tenant:
|
||||||
|
|
||||||
|
- **Com IP público:** a comunicação é direta; o passo do vproxy é pulado.
|
||||||
|
- **Sem IP público:** sobe-se o container **vproxy** (túnel WireGuard, imagem
|
||||||
|
`davinti-vproxy`), que estabelece o túnel de saída e expõe os serviços necessários
|
||||||
|
através do `PROXY_EDPS`. O protocolo padrão é **UDP** (melhor desempenho); caso
|
||||||
|
firewalls restritivos bloqueiem UDP, é possível selecionar **TCP**.
|
||||||
|
|
||||||
|
## Arquivos gerados
|
||||||
|
|
||||||
|
O instalador gera dois arquivos no diretório de execução:
|
||||||
|
|
||||||
|
- **`config.toml`** — configuração do app cliente (servidor, banco, certificados,
|
||||||
|
aplicação, log). É montado dentro do container em `/app/config.toml`.
|
||||||
|
- **`envs`** — variáveis de ambiente do vproxy/WireGuard (gerado somente quando não há
|
||||||
|
IP público). É passado ao container via `--env-file`.
|
||||||
|
|
||||||
|
Ambos os arquivos são reaproveitados como **valores padrão** caso já existam ao reabrir
|
||||||
|
o instalador (no caso do `config.toml`).
|
||||||
|
|
||||||
|
## Containers e rede Docker
|
||||||
|
|
||||||
|
`app-dono-cliente` e `vproxy` são conectados à rede Docker **`app-dono_app`** (criada
|
||||||
|
automaticamente se não existir). O `app-dono-updater` fica fora dessa rede — ele só fala
|
||||||
|
com o daemon Docker via socket, não com os outros containers pela rede.
|
||||||
|
|
||||||
|
| Container | Imagem | Quando sobe |
|
||||||
|
| --------------------- | ------------------------------------------------ | -------------------- |
|
||||||
|
| `app-dono-cliente` | `hub.davinti.com.br:443/app-dono/app-cliente` | Sempre |
|
||||||
|
| `vproxy` | `hub.davinti.com.br:443/davinti-vproxy` | Quando não há IP púb.|
|
||||||
|
| `app-dono-updater` | `docker:cli` | Sempre |
|
||||||
|
|
||||||
|
Características:
|
||||||
|
|
||||||
|
- Todos sobem com `--restart unless-stopped`.
|
||||||
|
- O container do app expõe a porta configurada no host, mapeando para a `8080` interna,
|
||||||
|
e monta o `config.toml` e o diretório de certificados como volumes.
|
||||||
|
- O `vproxy` roda com `--cap-add=NET_ADMIN` e acesso a `/dev/net/tun`.
|
||||||
|
- O `app-dono-updater` **não** é o Watchtower — esse projeto foi arquivado pelos
|
||||||
|
mantenedores originais em dez/2025 sem um sucessor mantido recomendado para produção.
|
||||||
|
Em vez disso, é um loop simples (`sh -c`) rodando na imagem oficial `docker:cli`: a
|
||||||
|
cada 5 minutos baixa a imagem do `app-dono-cliente`, compara com a que está rodando e,
|
||||||
|
se mudou, recria o container. Usa as mesmas credenciais do login feito no passo 2 (via
|
||||||
|
`~/.docker/config.json`) e precisa de acesso ao socket do Docker
|
||||||
|
(`/var/run/docker.sock`) para poder recriar o container.
|
||||||
|
- O **modo compatibilidade** (`seccomp=unconfined`) pode ser ativado para máquinas
|
||||||
|
antigas onde o seccomp padrão causa problemas.
|
||||||
|
|
||||||
|
## Build a partir do código
|
||||||
|
|
||||||
|
Requer **Go 1.25+**. O `Makefile` gera binários estáticos para múltiplas plataformas:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make build # compila para linux/darwin/windows (amd64/arm64) em ./dist
|
||||||
|
make build VERSION=2.0.0 # define a versão
|
||||||
|
make clean # remove ./dist
|
||||||
|
|
||||||
|
# Publicação no S3 (requer S3_BUCKET):
|
||||||
|
make push S3_BUCKET=meu-bucket VERSION=1.0.0
|
||||||
|
make release S3_BUCKET=meu-bucket VERSION=2.0.0
|
||||||
|
make help # lista variáveis e alvos
|
||||||
|
```
|
||||||
|
|
||||||
|
Para um build local rápido:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go build -o installer ./cmd
|
||||||
|
./installer
|
||||||
|
```
|
||||||
|
|
||||||
|
A versão é gravada no binário em tempo de build (`make build VERSION=1.2.0`) e pode ser
|
||||||
|
consultada sem abrir a interface:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./installer --version # ex.: app-dono installer 1.2.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Um `go build` simples (sem o `Makefile`) deixa a versão como `dev`.
|
||||||
|
|
||||||
|
## Documentação adicional
|
||||||
|
|
||||||
|
- [docs/fluxo.md](docs/fluxo.md) — detalhamento de cada etapa do assistente.
|
||||||
|
- [docs/configuracao.md](docs/configuracao.md) — referência de todos os campos de
|
||||||
|
configuração e dos arquivos gerados.
|
||||||
|
- [docs/arquitetura.md](docs/arquitetura.md) — visão da arquitetura interna do código
|
||||||
|
(modelo Bubble Tea, comandos, etapas).
|
||||||
@@ -9,6 +9,14 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
if len(os.Args) > 1 {
|
||||||
|
switch os.Args[1] {
|
||||||
|
case "--version", "-v":
|
||||||
|
fmt.Println("app-dono installer", tui.Version)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
p := tea.NewProgram(tui.InitialModel())
|
p := tea.NewProgram(tui.InitialModel())
|
||||||
if _, err := p.Run(); err != nil {
|
if _, err := p.Run(); err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# TODO — UX / UI improvements
|
||||||
|
|
||||||
|
Backlog of usability and interface improvements for the installer TUI. Ordered by
|
||||||
|
value-to-effort. Status: ☐ pending · ☑ done.
|
||||||
|
|
||||||
|
## High value
|
||||||
|
|
||||||
|
- ☑ **1. Back navigation between steps.** Maintain a history stack of *input* steps
|
||||||
|
(forms + IP question + review) and bind `Esc` to go back. Action steps (download,
|
||||||
|
generate, run) are not part of the stack and are not re-enterable via back. Form
|
||||||
|
values are preserved because the `FormStep`s live on the `Model`.
|
||||||
|
|
||||||
|
- ☑ **2. Review/summary step before running containers.** Show all collected config
|
||||||
|
(`StepReview`) for confirmation before `StepGenerateFile`/`StepRunDocker`. Natural
|
||||||
|
anchor for "go back and edit a section" via `Esc`.
|
||||||
|
|
||||||
|
- ☑ **3. Retry instead of quit on transient errors.** Image pull / container run
|
||||||
|
failures offer `r: tentar novamente` (re-runs just that command) instead of throwing
|
||||||
|
away the whole session. Validation errors (generate file) route back to the relevant
|
||||||
|
form to fix the value.
|
||||||
|
|
||||||
|
## Medium value
|
||||||
|
|
||||||
|
- ☐ **4. Center the layout (vertically + horizontally).** Use
|
||||||
|
`lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, body)` — the
|
||||||
|
Model already tracks `width`/`height`. Caveat: every `viewXxx`/`form.View` currently
|
||||||
|
hardcodes a manual left pad (`strings.Repeat(" ", padding)`); to center cleanly,
|
||||||
|
strip that and wrap the body in one padded/bordered box, then `Place` it. Consider
|
||||||
|
pinning the help footer to the bottom rather than centering it with the body.
|
||||||
|
|
||||||
|
- ☐ **5. Inline field validation.** Numeric validation currently happens only at file
|
||||||
|
write time (`WriteConfigFile`), far from input. Wire `textinput.Validate` per field
|
||||||
|
and render a red hint under invalid fields in `form.go`.
|
||||||
|
|
||||||
|
- ☐ **6. Step indicator.** Show "Etapa N / Total" or a breadcrumb in the header. Total
|
||||||
|
is dynamic because the vproxy branch adds steps.
|
||||||
|
|
||||||
|
## Low value / cosmetic
|
||||||
|
|
||||||
|
- ☐ **7. Replace the fake progress bar.** `viewCheckDocker` animates a random-increment
|
||||||
|
bar for an instant `LookPath` check, then waits for a keypress. Use a spinner that
|
||||||
|
resolves immediately (or auto-advance on success).
|
||||||
|
|
||||||
|
- ☐ **8. Bordered card + `bubbles/help` footer.** Wrap the body in a rounded
|
||||||
|
`lipgloss` border and render the footer via `bubbles/help` with a proper key map and
|
||||||
|
a `?` toggle. Pairs with #4.
|
||||||
|
|
||||||
|
- ☐ **9. Password reveal toggle** (`ctrl+r`) on the login password field.
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
# Arquitetura Interna
|
||||||
|
|
||||||
|
Visão de como o código está organizado. A aplicação segue o padrão
|
||||||
|
[The Elm Architecture](https://github.com/charmbracelet/bubbletea) (Model–Update–View)
|
||||||
|
da biblioteca Bubble Tea.
|
||||||
|
|
||||||
|
## Estrutura de pastas
|
||||||
|
|
||||||
|
```
|
||||||
|
.
|
||||||
|
├── cmd/
|
||||||
|
│ └── main.go # Ponto de entrada; inicia o programa Bubble Tea
|
||||||
|
├── internal/tui/
|
||||||
|
│ ├── model.go # Struct Model, ConfigValues, carga de defaults, InitialModel/Init
|
||||||
|
│ ├── steps.go # Enum das etapas do assistente
|
||||||
|
│ ├── update.go # Lógica de transição (Update) por etapa
|
||||||
|
│ ├── view.go # Renderização (View) por etapa
|
||||||
|
│ ├── form.go # Componente genérico de formulário (FormStep/FormField)
|
||||||
|
│ ├── cmds.go # Mensagens (Msg) e comandos assíncronos (tea.Cmd)
|
||||||
|
│ ├── docker.go # Wrappers de chamadas ao binário docker
|
||||||
|
│ ├── config.go # Geração e gravação de config.toml e envs
|
||||||
|
│ └── styles.go # Paleta de cores e estilos Lip Gloss
|
||||||
|
├── config.toml # (gerado em runtime; ignorado no git)
|
||||||
|
├── envs # (gerado em runtime, vproxy)
|
||||||
|
└── Makefile # Build multiplataforma e publicação no S3
|
||||||
|
```
|
||||||
|
|
||||||
|
## Componentes principais
|
||||||
|
|
||||||
|
### `Model` ([model.go](../internal/tui/model.go))
|
||||||
|
|
||||||
|
Estado único da aplicação. Campos relevantes:
|
||||||
|
|
||||||
|
- `currentStep` — etapa atual do assistente.
|
||||||
|
- Estado de progresso/flags: `dockerInstalled`, `downloadDone`, `finishedFile`,
|
||||||
|
`finishedDockerRun`, e os respectivos erros.
|
||||||
|
- Um `FormStep` por etapa de formulário (`loginForm`, `wireguardForm`, `appForm`,
|
||||||
|
`serverForm`, `dbForm`, `certForm`).
|
||||||
|
- `configValues` (`ConfigValues`) — acumula os valores de todos os formulários,
|
||||||
|
agrupados por seção.
|
||||||
|
|
||||||
|
`loadConfig()` define os **valores padrão** e, se houver um `config.toml` no diretório,
|
||||||
|
sobrescreve com o conteúdo dele (usando `BurntSushi/toml`). `InitialModel()` constrói
|
||||||
|
todos os formulários com esses defaults.
|
||||||
|
|
||||||
|
### Etapas ([steps.go](../internal/tui/steps.go))
|
||||||
|
|
||||||
|
`step` é um enum (`iota`) que define a ordem do assistente. O `Update` faz o dispatch
|
||||||
|
com base em `currentStep`. Ver [fluxo.md](fluxo.md) para o detalhamento.
|
||||||
|
|
||||||
|
### Update ([update.go](../internal/tui/update.go))
|
||||||
|
|
||||||
|
`Update` trata primeiro mensagens globais (`Ctrl+C`, `WindowSizeMsg`, tick do spinner)
|
||||||
|
e depois delega para um handler por etapa (ex.: `updateCheckDocker`,
|
||||||
|
`updateDownloadImage`, `updateRunDocker`). As transições de etapa acontecem ao
|
||||||
|
concluir formulários (`done == true`) ou ao receber mensagens de conclusão dos
|
||||||
|
comandos assíncronos.
|
||||||
|
|
||||||
|
Constantes importantes ficam no topo do arquivo:
|
||||||
|
|
||||||
|
- `imageName` / `wireguardImageName` — imagens no registry privado.
|
||||||
|
- `configPath` (`config.toml`) / `wireguardConfigPath` (`envs`).
|
||||||
|
|
||||||
|
### View ([view.go](../internal/tui/view.go))
|
||||||
|
|
||||||
|
`View` monta a tela com cabeçalho fixo, corpo dependente da etapa e rodapé de ajuda.
|
||||||
|
Usa `AltScreen`. Cada etapa tem um método `viewXxx` ou reutiliza o `View()` do
|
||||||
|
formulário.
|
||||||
|
|
||||||
|
### Formulário genérico ([form.go](../internal/tui/form.go))
|
||||||
|
|
||||||
|
`FormStep` agrupa vários `FormField`. Suporta os tipos texto, senha, número e seleção.
|
||||||
|
`Update` cuida da navegação entre campos (`Tab`/setas) e retorna `done = true` quando
|
||||||
|
o `Enter` é pressionado no último campo. `Values()` devolve um `map[string]string`
|
||||||
|
indexado pelo `Id` de cada campo — é isso que alimenta o `ConfigValues`.
|
||||||
|
|
||||||
|
### Comandos e mensagens ([cmds.go](../internal/tui/cmds.go))
|
||||||
|
|
||||||
|
Toda operação bloqueante (chamar `docker`, escrever arquivo) é encapsulada em um
|
||||||
|
`tea.Cmd` que roda em goroutine e devolve uma `Msg` ao loop do Bubble Tea:
|
||||||
|
|
||||||
|
| Comando | Ação | Mensagem de retorno |
|
||||||
|
| ----------------------------- | ------------------------------------- | --------------------------- |
|
||||||
|
| `CheckDockerCmd` | `exec.LookPath("docker")` | `DockerCheckedMsg` |
|
||||||
|
| `DownloadImageCmd` | `docker login` + `pull` (app) | `ImageDownloadFinishedMsg` |
|
||||||
|
| `DownloadWireguardImageCmd` | `docker login` + `pull` (vproxy) | `ImageDownloadFinishedMsg` |
|
||||||
|
| `GenerateConfigFile` | grava `config.toml` | `ConfigFileMsg` |
|
||||||
|
| `GenerateWireguardConfigFile` | grava `envs` | `ConfigFileMsg` |
|
||||||
|
| `RunAppContainer` | `docker run` (app) | `DockerRunMsg` |
|
||||||
|
| `RunWireguardContainer` | `docker run` (vproxy) | `DockerRunMsg` |
|
||||||
|
| `TickCmd` | tick da barra de progresso | `TickMsg` |
|
||||||
|
|
||||||
|
### Camada Docker ([docker.go](../internal/tui/docker.go))
|
||||||
|
|
||||||
|
Funções utilitárias que invocam o binário `docker` via `os/exec`:
|
||||||
|
|
||||||
|
- `EnsureNetwork` — cria a rede `app-dono_app` se necessário.
|
||||||
|
- `RunAppClienteContainer` / `RunWireguardDockerContainer` — montam os argumentos do
|
||||||
|
`docker run`, removem container homônimo prévio e verificam o status `running`.
|
||||||
|
- `verifyContainerRunning` — inspeciona o status e, em falha, anexa os últimos logs.
|
||||||
|
- `removeExistingContainer`, `PullImage`, `ImageExists`, `PushFileToContainer`.
|
||||||
|
|
||||||
|
### Estilos ([styles.go](../internal/tui/styles.go))
|
||||||
|
|
||||||
|
Paleta de cores e estilos Lip Gloss reutilizados na View (títulos, cursor, ajuda,
|
||||||
|
erros, barra de progresso, seleção).
|
||||||
|
|
||||||
|
## Dependências
|
||||||
|
|
||||||
|
- `charm.land/bubbletea/v2` — runtime TUI (loop Model/Update/View).
|
||||||
|
- `charm.land/bubbles/v2` — componentes (`textinput`, `spinner`).
|
||||||
|
- `charm.land/lipgloss/v2` — estilização.
|
||||||
|
- `github.com/BurntSushi/toml` — leitura do `config.toml` para defaults.
|
||||||
|
|
||||||
|
## Observações para manutenção
|
||||||
|
|
||||||
|
- **Porta:** o `config.toml` grava `port = 8080` fixo; a porta do formulário só afeta o
|
||||||
|
mapeamento de host no `docker run`. Ver [configuracao.md](configuracao.md).
|
||||||
|
- **Credenciais:** o login do registry é coletado uma vez e reutilizado para baixar a
|
||||||
|
imagem do vproxy.
|
||||||
|
- **Rede:** o nome da rede é a constante `networkName` (`app-dono_app`) em `docker.go`;
|
||||||
|
usar sempre a constante ao referenciá-la.
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# Referência de Configuração
|
||||||
|
|
||||||
|
Este documento descreve todos os campos coletados pelo instalador e os arquivos que
|
||||||
|
ele gera.
|
||||||
|
|
||||||
|
## Arquivo `config.toml`
|
||||||
|
|
||||||
|
Gerado por `GenerateConfigTOML` em
|
||||||
|
[`internal/tui/config.go`](../internal/tui/config.go) e montado no container do app em
|
||||||
|
`/app/config.toml`. Se um `config.toml` já existir no diretório ao iniciar o
|
||||||
|
instalador, seus valores são usados como **padrão** nos formulários.
|
||||||
|
|
||||||
|
### `[server]`
|
||||||
|
|
||||||
|
| Campo | Origem (formulário) | Observações |
|
||||||
|
| ----------------- | ----------------------------- | ------------------------------------------------------------ |
|
||||||
|
| `port` | **fixo `8080`** no arquivo | A porta do formulário é usada apenas no **mapeamento do host** (`<porta>:8080`). Dentro do container o app sempre escuta na `8080`. |
|
||||||
|
| `timeout_seconds` | Servidor → Timeout | Em segundos. Padrão `30`. |
|
||||||
|
| `environment` | Servidor → Ambiente | `development` ou `production`. |
|
||||||
|
|
||||||
|
> **Atenção:** o campo "Porta (host)" do formulário define a porta exposta no host,
|
||||||
|
> não a porta interna. O `config.toml` sempre grava `port = 8080` (constante
|
||||||
|
> `containerAppPort` em `docker.go`).
|
||||||
|
|
||||||
|
### `[database]`
|
||||||
|
|
||||||
|
| Campo | Origem | Observações |
|
||||||
|
| ----------- | -------------------- | ------------------------------------ |
|
||||||
|
| `type` | Banco → Tipo do Banco| `postgres` ou `oracle`. |
|
||||||
|
| `url` | Banco → URL de acesso| String de conexão completa. |
|
||||||
|
| `max_conns` | Banco → Conexões máx.| Validado como número. |
|
||||||
|
| `min_conns` | Banco → Conexões mín.| Validado como número. |
|
||||||
|
|
||||||
|
### `[certificate]`
|
||||||
|
|
||||||
|
| Campo | Valor | Observações |
|
||||||
|
| ------------ | ------------------------------------ | -------------------------------------------- |
|
||||||
|
| `mapped_dir` | Certificado → Diretório | Diretório local montado em `/app/certs`. |
|
||||||
|
| `cert_path` | `/app/certs/client.crt` (fixo) | Caminho **dentro** do container. |
|
||||||
|
| `key_path` | `/app/certs/client.key` (fixo) | Caminho **dentro** do container. |
|
||||||
|
| `ca_path` | `/app/certs/ca.crt` (fixo) | Caminho **dentro** do container. |
|
||||||
|
|
||||||
|
O diretório indicado deve conter os arquivos `client.crt`, `client.key` e `ca.crt`
|
||||||
|
(comunicação mTLS com o servidor central).
|
||||||
|
|
||||||
|
### `[application]`
|
||||||
|
|
||||||
|
| Campo | Origem | Observações |
|
||||||
|
| -------------------- | ------------------------------- | ------------------------------------ |
|
||||||
|
| `erp` | `TOTVS` (fixo) | ERP integrado. |
|
||||||
|
| `central_server_url` | Aplicação → URL Servidor Central| Ex.: `https://app-dono-api.vitruvio.com.br:8443`. |
|
||||||
|
| `enrollment_token` | Aplicação → Token de Inscrição | Gerado no painel web. |
|
||||||
|
|
||||||
|
### `[log]`
|
||||||
|
|
||||||
|
| Campo | Valor |
|
||||||
|
| -------- | ----------------- |
|
||||||
|
| `level` | `debug` (fixo) |
|
||||||
|
| `format` | `json` (fixo) |
|
||||||
|
|
||||||
|
## Arquivo `envs` (vproxy / WireGuard)
|
||||||
|
|
||||||
|
Gerado por `GenerateWireguardConfig` apenas quando **não há IP público**. Passado ao
|
||||||
|
container do vproxy via `--env-file`.
|
||||||
|
|
||||||
|
| Variável | Origem | Observações |
|
||||||
|
| ------------ | ----------------------- | ------------------------------------------------------------ |
|
||||||
|
| `PRIVKEY` | vproxy → Chave Privada | Chave privada WireGuard. |
|
||||||
|
| `VIP` | vproxy → IP Virtual | Padrão `127.0.0.1`. |
|
||||||
|
| `PSK` | vproxy → Pre-Shared Key | Chave pré-compartilhada. |
|
||||||
|
| `PROXY_EDPS` | vproxy → Proxy EDPS | Mapeamento de portas, ex.: `22:127.0.0.1:22`. |
|
||||||
|
| `MTU` | vproxy → MTU | Opcional. Padrão `1380`. Validado como número. |
|
||||||
|
| `PROTO` | vproxy → Protocolo | `UDP` (padrão) ou `TCP`. |
|
||||||
|
|
||||||
|
### Sobre o protocolo
|
||||||
|
|
||||||
|
- **UDP** (padrão): melhor desempenho e estabilidade. Manter sempre que possível.
|
||||||
|
- **TCP**: usar apenas quando firewalls restritivos bloqueiam o tráfego UDP e não for
|
||||||
|
possível negociar a liberação com o cliente.
|
||||||
|
|
||||||
|
## Campo "Modo Compatibilidade"
|
||||||
|
|
||||||
|
Presente no formulário de Servidor (`seccomp_unconfined`). Quando definido como
|
||||||
|
**`Sim`**, os containers sobem com `--security-opt seccomp=unconfined`. Útil em
|
||||||
|
máquinas antigas onde o perfil seccomp padrão do Docker causa falhas. Aplica-se tanto
|
||||||
|
ao container do app quanto ao do vproxy.
|
||||||
|
|
||||||
|
## Tipos de campo dos formulários
|
||||||
|
|
||||||
|
Definidos em [`internal/tui/form.go`](../internal/tui/form.go):
|
||||||
|
|
||||||
|
| Tipo | Comportamento |
|
||||||
|
| ------------------ | ---------------------------------------------- |
|
||||||
|
| `FieldTypeText` | Texto livre. |
|
||||||
|
| `FieldTypePassword`| Texto mascarado. |
|
||||||
|
| `FieldTypeNumber` | Texto (validação numérica na gravação). |
|
||||||
|
| `FieldTypeSelect` | Opções alternadas com `←`/`→`. |
|
||||||
+127
@@ -0,0 +1,127 @@
|
|||||||
|
# Fluxo do Instalador
|
||||||
|
|
||||||
|
Este documento detalha cada etapa do assistente, a ordem em que ocorrem e as ações
|
||||||
|
executadas em segundo plano. As etapas são definidas em
|
||||||
|
[`internal/tui/steps.go`](../internal/tui/steps.go).
|
||||||
|
|
||||||
|
## Visão geral das etapas
|
||||||
|
|
||||||
|
| # | Etapa (`step`) | O que acontece |
|
||||||
|
| -- | ---------------------------- | ------------------------------------------------------------------- |
|
||||||
|
| 1 | `StepCheckDocker` | Verifica se o binário `docker` está no `PATH`. |
|
||||||
|
| 2 | `StepDockerInstall` | Tela final exibida quando o Docker não é encontrado. |
|
||||||
|
| 3 | `StepDockerLogin` | Formulário de login no registry privado. |
|
||||||
|
| 4 | `StepDownloadImage` | `docker login` + `docker pull` da imagem do app cliente. |
|
||||||
|
| 5 | `StepIPQuestion` | Pergunta se há IP público disponível. |
|
||||||
|
| 6 | `StepWireguardConfig` | Formulário de configuração do vproxy (apenas sem IP público). |
|
||||||
|
| 7 | `StepGenerateWireguardFile` | Gera o arquivo `envs`. |
|
||||||
|
| 8 | `StepDownloadWireguard` | `docker login` + `docker pull` da imagem do vproxy. |
|
||||||
|
| 9 | `StepRunWireguard` | Sobe o container `vproxy`. |
|
||||||
|
| 10 | `StepAppConfig` | Formulário da aplicação (URL central, token). |
|
||||||
|
| 11 | `StepServerConfig` | Formulário do servidor (porta, timeout, ambiente, compatibilidade). |
|
||||||
|
| 12 | `StepDatabaseConfig` | Formulário do banco de dados. |
|
||||||
|
| 13 | `StepCertConfig` | Formulário do diretório de certificados. |
|
||||||
|
| 14 | `StepReview` | Revisão de todas as configurações antes de instalar. |
|
||||||
|
| 15 | `StepGenerateFile` | Gera o `config.toml`. |
|
||||||
|
| 16 | `StepRunDocker` | Sobe o container `app-dono-cliente`. |
|
||||||
|
| 17 | `StepDone` | Mensagem de sucesso. |
|
||||||
|
|
||||||
|
## Navegação e tratamento de erros
|
||||||
|
|
||||||
|
- **Voltar (`Esc`):** retorna à etapa de entrada anterior (formulários, pergunta de IP
|
||||||
|
e revisão). O `Model` mantém uma pilha `history` de etapas; etapas de ação (downloads,
|
||||||
|
geração de arquivo, subida de container) ficam de fora e não são reexecutadas ao
|
||||||
|
voltar. Os valores já digitados nos formulários são preservados.
|
||||||
|
- **Revisão (`StepReview`):** antes de gravar qualquer arquivo, todas as configurações
|
||||||
|
coletadas são exibidas para confirmação. `Enter` confirma e gera o `config.toml`;
|
||||||
|
`Esc` volta ao formulário anterior para editar.
|
||||||
|
- **Tentar novamente:** falhas transitórias (download de imagem, subida de container)
|
||||||
|
oferecem `r` para reexecutar apenas aquele passo (`q` sai). Erros de validação
|
||||||
|
(geração de arquivo) levam de volta ao formulário correspondente para correção.
|
||||||
|
|
||||||
|
## Detalhamento
|
||||||
|
|
||||||
|
### 1. Verificação do Docker (`StepCheckDocker`)
|
||||||
|
|
||||||
|
Ao iniciar, o `Init()` dispara três comandos em paralelo: `CheckDockerCmd`,
|
||||||
|
`TickCmd` (anima a barra de progresso) e o tick do spinner. O `CheckDockerCmd`
|
||||||
|
executa `exec.LookPath("docker")`.
|
||||||
|
|
||||||
|
- **Encontrado:** ao pressionar qualquer tecla, segue para o login.
|
||||||
|
- **Não encontrado:** vai para `StepDockerInstall`, que orienta a instalação manual
|
||||||
|
e encerra. O instalador **não** instala o Docker.
|
||||||
|
|
||||||
|
### 3–4. Login e download da imagem do app
|
||||||
|
|
||||||
|
O formulário coleta usuário e senha do registry. Em seguida, `DownloadImageCmd`
|
||||||
|
executa:
|
||||||
|
|
||||||
|
```
|
||||||
|
docker login hub.davinti.com.br:443/app-dono/app-cliente:latest -u <user> -p <senha>
|
||||||
|
docker pull hub.davinti.com.br:443/app-dono/app-cliente:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
As **mesmas credenciais** são reaproveitadas mais adiante para baixar a imagem do
|
||||||
|
vproxy. Em caso de erro de login ou pull, a mensagem do Docker é exibida e o
|
||||||
|
instalador encerra ao pressionar qualquer tecla.
|
||||||
|
|
||||||
|
### 5. Pergunta de IP público (`StepIPQuestion`)
|
||||||
|
|
||||||
|
- **Sim** → pula o bloco do vproxy e vai direto para `StepAppConfig`.
|
||||||
|
- **Não** → vai para `StepWireguardConfig`.
|
||||||
|
|
||||||
|
### 6–9. Bloco vproxy (somente sem IP público)
|
||||||
|
|
||||||
|
1. **`StepWireguardConfig`** — coleta `PRIVKEY`, `VIP`, `PSK`, `PROXY_EDPS`, `MTU`
|
||||||
|
e `PROTO` (UDP/TCP).
|
||||||
|
2. **`StepGenerateWireguardFile`** — grava o arquivo `envs`
|
||||||
|
(ver [`config.go`](../internal/tui/config.go), `GenerateWireguardConfig`).
|
||||||
|
3. **`StepDownloadWireguard`** — faz login e pull da imagem `davinti-vproxy`.
|
||||||
|
4. **`StepRunWireguard`** — sobe o container `vproxy` com `--cap-add=NET_ADMIN`,
|
||||||
|
`--device /dev/net/tun`, `--env-file envs` e o conecta à rede `app-dono_app`.
|
||||||
|
Após subir, espera 2s e verifica se o status é `running`; se não, mostra os
|
||||||
|
últimos logs do container.
|
||||||
|
|
||||||
|
Ao final do bloco, segue para `StepAppConfig`.
|
||||||
|
|
||||||
|
### 10–13. Configuração da aplicação
|
||||||
|
|
||||||
|
Quatro formulários sequenciais preenchem o `ConfigValues`:
|
||||||
|
|
||||||
|
- **Aplicação:** URL do servidor central e token de inscrição.
|
||||||
|
- **Servidor:** porta, timeout, ambiente (`development`/`production`) e modo
|
||||||
|
compatibilidade (`seccomp=unconfined`).
|
||||||
|
- **Banco de dados:** tipo (`postgres`/`oracle`), URL de conexão, conexões máx./mín.
|
||||||
|
- **Certificado:** diretório local com os certificados mTLS.
|
||||||
|
|
||||||
|
### 14. Geração do `config.toml` (`StepGenerateFile`)
|
||||||
|
|
||||||
|
`WriteConfigFile` valida os campos numéricos (`port`, `timeout`, `max_conns`,
|
||||||
|
`min_conns`) e grava o `config.toml`. Em caso de valor inválido, exibe o erro e
|
||||||
|
permite tentar novamente.
|
||||||
|
|
||||||
|
### 15. Subida do container do app (`StepRunDocker`)
|
||||||
|
|
||||||
|
`RunAppClienteContainer` remove um container homônimo existente, garante a rede
|
||||||
|
`app-dono_app`, e executa `docker run` com:
|
||||||
|
|
||||||
|
- usuário/grupo do host (`-u uid:gid`);
|
||||||
|
- mapeamento de porta `<porta do host>:8080`;
|
||||||
|
- volume do `config.toml` em `/app/config.toml`;
|
||||||
|
- volume do diretório de certificados em `/app/certs`;
|
||||||
|
- `--restart unless-stopped`.
|
||||||
|
|
||||||
|
Verifica o status `running` da mesma forma que o vproxy.
|
||||||
|
|
||||||
|
### 16. Conclusão (`StepDone`)
|
||||||
|
|
||||||
|
Exibe "Instalação realizada com sucesso!". Qualquer tecla encerra.
|
||||||
|
|
||||||
|
## Tratamento de erros
|
||||||
|
|
||||||
|
Em etapas de download, geração de arquivo e subida de container, qualquer falha:
|
||||||
|
|
||||||
|
- interrompe o avanço automático;
|
||||||
|
- mostra a mensagem/erro do Docker (ou do sistema de arquivos) com estilo de erro;
|
||||||
|
- permite **sair** (em downloads) ou **tentar novamente** (em geração/run) conforme
|
||||||
|
a etapa.
|
||||||
+13
-27
@@ -43,12 +43,10 @@ func TickCmd() tea.Cmd {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func DownloadImageCmd(username, password string) tea.Cmd {
|
func DownloadImageCmd(image, username, password string) tea.Cmd {
|
||||||
return func() tea.Msg {
|
return func() tea.Msg {
|
||||||
url := imageName
|
|
||||||
|
|
||||||
loginOut, err := exec.Command(
|
loginOut, err := exec.Command(
|
||||||
"docker", "login", url,
|
"docker", "login", image,
|
||||||
"-u", username,
|
"-u", username,
|
||||||
"-p", password,
|
"-p", password,
|
||||||
).CombinedOutput()
|
).CombinedOutput()
|
||||||
@@ -60,29 +58,7 @@ func DownloadImageCmd(username, password string) tea.Cmd {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
message, err := PullImage(url)
|
message, err := PullImage(image)
|
||||||
return ImageDownloadFinishedMsg{Message: message, Err: err}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func DownloadWireguardImageCmd(username, password string) tea.Cmd {
|
|
||||||
return func() tea.Msg {
|
|
||||||
url := wireguardImageName
|
|
||||||
|
|
||||||
loginOut, err := exec.Command(
|
|
||||||
"docker", "login", url,
|
|
||||||
"-u", username,
|
|
||||||
"-p", password,
|
|
||||||
).CombinedOutput()
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return ImageDownloadFinishedMsg{
|
|
||||||
Message: string(loginOut),
|
|
||||||
Err: fmt.Errorf("falha no login: %w", err),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
message, err := PullImage(url)
|
|
||||||
return ImageDownloadFinishedMsg{Message: message, Err: err}
|
return ImageDownloadFinishedMsg{Message: message, Err: err}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -138,3 +114,13 @@ func RunWireguardContainer(path string, cv ConfigValues) tea.Cmd {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func RunUpdaterContainer(appImage, appContainerName, configPath, configDestinationPath string, cv ConfigValues) tea.Cmd {
|
||||||
|
return func() tea.Msg {
|
||||||
|
err := RunUpdaterDockerContainer(appImage, appContainerName, configPath, configDestinationPath, cv)
|
||||||
|
|
||||||
|
return DockerRunMsg{
|
||||||
|
Err: err,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -13,9 +13,14 @@ func GenerateConfigTOML(cv ConfigValues) (string, error) {
|
|||||||
// [server]
|
// [server]
|
||||||
sb.WriteString("# Server Configuration\n")
|
sb.WriteString("# Server Configuration\n")
|
||||||
sb.WriteString("[server]\n")
|
sb.WriteString("[server]\n")
|
||||||
sb.WriteString("port = 8080\n")
|
// Always containerAppPort: the container listens on this port internally; the
|
||||||
|
// user's port is the host-side mapping (see RunAppClienteContainer). Persisted
|
||||||
|
// separately as host_port so it survives as the form default on a re-run.
|
||||||
|
sb.WriteString(fmt.Sprintf("port = %d\n", containerAppPort))
|
||||||
|
sb.WriteString(fmt.Sprintf("host_port = %s\n", cv.Server["port"]))
|
||||||
sb.WriteString(fmt.Sprintf("timeout_seconds = %s\n", cv.Server["timeout"]))
|
sb.WriteString(fmt.Sprintf("timeout_seconds = %s\n", cv.Server["timeout"]))
|
||||||
sb.WriteString(fmt.Sprintf("environment = %q\n", cv.Server["environment"]))
|
sb.WriteString(fmt.Sprintf("environment = %q\n", cv.Server["environment"]))
|
||||||
|
sb.WriteString(fmt.Sprintf("seccomp_unconfined = %t\n", cv.Server["seccomp_unconfined"] == "Sim"))
|
||||||
sb.WriteString("\n")
|
sb.WriteString("\n")
|
||||||
|
|
||||||
// [database]
|
// [database]
|
||||||
|
|||||||
@@ -0,0 +1,253 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/BurntSushi/toml"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fullConfigValues returns a ConfigValues with every field populated with valid data.
|
||||||
|
func fullConfigValues() ConfigValues {
|
||||||
|
return ConfigValues{
|
||||||
|
Login: map[string]string{"user": "u", "password": "p"},
|
||||||
|
Server: map[string]string{
|
||||||
|
"port": "9090",
|
||||||
|
"timeout": "45",
|
||||||
|
"environment": "production",
|
||||||
|
"seccomp_unconfined": "Não",
|
||||||
|
},
|
||||||
|
Database: map[string]string{
|
||||||
|
"database_type": "postgres",
|
||||||
|
"database_url": "postgres://user:pass@db:5432/app_dono_db",
|
||||||
|
"max_conns": "20",
|
||||||
|
"min_conns": "5",
|
||||||
|
},
|
||||||
|
Cert: map[string]string{"cert_dir_path": "/etc/app-dono/certs"},
|
||||||
|
Application: map[string]string{
|
||||||
|
"central_server_url": "https://central.example.com:8443",
|
||||||
|
"enrollment_token": "tok-123",
|
||||||
|
},
|
||||||
|
Wireguard: map[string]string{
|
||||||
|
"privkey": "PRIVKEY_VALUE",
|
||||||
|
"vip": "127.0.0.1",
|
||||||
|
"psk": "PSK_VALUE",
|
||||||
|
"proxy_edps": "22:127.0.0.1:22",
|
||||||
|
"mtu": "1380",
|
||||||
|
"proto": "UDP",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenerateConfigTOML_RoundTrip(t *testing.T) {
|
||||||
|
cv := fullConfigValues()
|
||||||
|
|
||||||
|
out, err := GenerateConfigTOML(cv)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GenerateConfigTOML returned error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var cfg AppConfig
|
||||||
|
if _, err := toml.Decode(out, &cfg); err != nil {
|
||||||
|
t.Fatalf("generated output is not valid TOML / failed to decode: %v\n---\n%s", err, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.Server.Timeout != 45 {
|
||||||
|
t.Errorf("timeout_seconds = %d, want 45", cfg.Server.Timeout)
|
||||||
|
}
|
||||||
|
if cfg.Server.Environment != "production" {
|
||||||
|
t.Errorf("environment = %q, want %q", cfg.Server.Environment, "production")
|
||||||
|
}
|
||||||
|
if cfg.Server.HostPort != 9090 {
|
||||||
|
t.Errorf("host_port = %d, want 9090", cfg.Server.HostPort)
|
||||||
|
}
|
||||||
|
if cfg.Server.SeccompUnconfined {
|
||||||
|
t.Errorf("seccomp_unconfined = true, want false")
|
||||||
|
}
|
||||||
|
if cfg.Database.Type != "postgres" {
|
||||||
|
t.Errorf("database type = %q, want %q", cfg.Database.Type, "postgres")
|
||||||
|
}
|
||||||
|
if cfg.Database.URL != "postgres://user:pass@db:5432/app_dono_db" {
|
||||||
|
t.Errorf("database url = %q", cfg.Database.URL)
|
||||||
|
}
|
||||||
|
if cfg.Database.MaxConns != 20 {
|
||||||
|
t.Errorf("max_conns = %d, want 20", cfg.Database.MaxConns)
|
||||||
|
}
|
||||||
|
if cfg.Database.MinConns != 5 {
|
||||||
|
t.Errorf("min_conns = %d, want 5", cfg.Database.MinConns)
|
||||||
|
}
|
||||||
|
if cfg.Certificates.DirPath != "/etc/app-dono/certs" {
|
||||||
|
t.Errorf("mapped_dir = %q", cfg.Certificates.DirPath)
|
||||||
|
}
|
||||||
|
if cfg.Application.CentralServerURL != "https://central.example.com:8443" {
|
||||||
|
t.Errorf("central_server_url = %q", cfg.Application.CentralServerURL)
|
||||||
|
}
|
||||||
|
if cfg.Application.EnrollmentToken != "tok-123" {
|
||||||
|
t.Errorf("enrollment_token = %q", cfg.Application.EnrollmentToken)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The container always listens on containerAppPort internally; the user-provided
|
||||||
|
// "Porta (host)" value is only the host-side mapping and must never leak into the
|
||||||
|
// generated config.toml. This guard fails loudly if that invariant is reverted.
|
||||||
|
func TestGenerateConfigTOML_PortIsAlwaysContainerPort(t *testing.T) {
|
||||||
|
cv := fullConfigValues()
|
||||||
|
cv.Server["port"] = "9090" // host port, must NOT appear as the config port
|
||||||
|
|
||||||
|
out, err := GenerateConfigTOML(cv)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GenerateConfigTOML returned error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var cfg AppConfig
|
||||||
|
if _, err := toml.Decode(out, &cfg); err != nil {
|
||||||
|
t.Fatalf("failed to decode: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.Server.Port != containerAppPort {
|
||||||
|
t.Errorf("config port = %d, want fixed containerAppPort %d", cfg.Server.Port, containerAppPort)
|
||||||
|
}
|
||||||
|
if cfg.Server.HostPort != 9090 {
|
||||||
|
t.Errorf("host_port = %d, want 9090", cfg.Server.HostPort)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenerateWireguardConfig(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
wireguard map[string]string
|
||||||
|
wantContains []string
|
||||||
|
wantNotContns []string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "all fields set",
|
||||||
|
wireguard: map[string]string{
|
||||||
|
"privkey": "PK", "vip": "10.0.0.1", "psk": "PSK",
|
||||||
|
"proxy_edps": "22:127.0.0.1:22", "mtu": "1400", "proto": "TCP",
|
||||||
|
},
|
||||||
|
wantContains: []string{
|
||||||
|
"PRIVKEY=PK", "VIP=10.0.0.1", "PSK=PSK",
|
||||||
|
"PROXY_EDPS=22:127.0.0.1:22", "MTU=1400", "PROTO=TCP",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty mtu is commented out",
|
||||||
|
wireguard: map[string]string{
|
||||||
|
"privkey": "PK", "vip": "10.0.0.1", "psk": "PSK",
|
||||||
|
"proxy_edps": "22:127.0.0.1:22", "mtu": "", "proto": "UDP",
|
||||||
|
},
|
||||||
|
wantContains: []string{"# MTU=1380", "PROTO=UDP"},
|
||||||
|
wantNotContns: []string{"\nMTU="},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty proto defaults to UDP",
|
||||||
|
wireguard: map[string]string{
|
||||||
|
"privkey": "PK", "vip": "10.0.0.1", "psk": "PSK",
|
||||||
|
"proxy_edps": "22:127.0.0.1:22", "proto": "",
|
||||||
|
},
|
||||||
|
wantContains: []string{"PROTO=UDP"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
out, err := GenerateWireguardConfig(ConfigValues{Wireguard: tt.wireguard})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GenerateWireguardConfig returned error: %v", err)
|
||||||
|
}
|
||||||
|
for _, want := range tt.wantContains {
|
||||||
|
if !strings.Contains(out, want) {
|
||||||
|
t.Errorf("output missing %q:\n%s", want, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, notWant := range tt.wantNotContns {
|
||||||
|
if strings.Contains(out, notWant) {
|
||||||
|
t.Errorf("output should not contain %q:\n%s", notWant, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWriteConfigFile_NumericValidation(t *testing.T) {
|
||||||
|
numeric := []string{"port", "timeout", "max_conns", "min_conns"}
|
||||||
|
|
||||||
|
for _, field := range numeric {
|
||||||
|
t.Run("invalid_"+field, func(t *testing.T) {
|
||||||
|
cv := fullConfigValues()
|
||||||
|
switch field {
|
||||||
|
case "port", "timeout":
|
||||||
|
cv.Server[field] = "abc"
|
||||||
|
case "max_conns", "min_conns":
|
||||||
|
cv.Database[field] = "abc"
|
||||||
|
}
|
||||||
|
|
||||||
|
path := filepath.Join(t.TempDir(), "config.toml")
|
||||||
|
err := WriteConfigFile(cv, path)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("expected error for non-numeric %q, got nil", field)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), field) {
|
||||||
|
t.Errorf("error %q does not mention field %q", err.Error(), field)
|
||||||
|
}
|
||||||
|
if _, statErr := os.Stat(path); statErr == nil {
|
||||||
|
t.Errorf("file should not have been written on validation failure")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWriteConfigFile_ValidWritesFile(t *testing.T) {
|
||||||
|
cv := fullConfigValues()
|
||||||
|
path := filepath.Join(t.TempDir(), "config.toml")
|
||||||
|
|
||||||
|
if err := WriteConfigFile(cv, path); err != nil {
|
||||||
|
t.Fatalf("WriteConfigFile returned error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("config file was not written: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var cfg AppConfig
|
||||||
|
if _, err := toml.Decode(string(data), &cfg); err != nil {
|
||||||
|
t.Fatalf("written file is not valid TOML: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWriteWireguardConfigFile_MTUValidation(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
mtu string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{name: "valid mtu", mtu: "1380", wantErr: false},
|
||||||
|
{name: "empty mtu allowed", mtu: "", wantErr: false},
|
||||||
|
{name: "non-numeric mtu rejected", mtu: "big", wantErr: true},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
cv := fullConfigValues()
|
||||||
|
cv.Wireguard["mtu"] = tt.mtu
|
||||||
|
|
||||||
|
path := filepath.Join(t.TempDir(), "envs")
|
||||||
|
err := WriteWireguardConfigFile(cv, path)
|
||||||
|
|
||||||
|
if tt.wantErr && err == nil {
|
||||||
|
t.Fatalf("expected error for mtu %q, got nil", tt.mtu)
|
||||||
|
}
|
||||||
|
if !tt.wantErr && err != nil {
|
||||||
|
t.Fatalf("unexpected error for mtu %q: %v", tt.mtu, err)
|
||||||
|
}
|
||||||
|
if !tt.wantErr {
|
||||||
|
if _, statErr := os.Stat(path); statErr != nil {
|
||||||
|
t.Errorf("envs file should have been written: %v", statErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+137
-12
@@ -2,6 +2,7 @@ package tui
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"os/user"
|
"os/user"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
@@ -11,6 +12,10 @@ import (
|
|||||||
|
|
||||||
const networkName = "app-dono_app"
|
const networkName = "app-dono_app"
|
||||||
|
|
||||||
|
// containerAppPort is the port the app cliente container listens on internally.
|
||||||
|
// The user-provided port is only the host-side mapping (<host port>:containerAppPort).
|
||||||
|
const containerAppPort = 8080
|
||||||
|
|
||||||
func RunContainer(image string, name string, port int) error {
|
func RunContainer(image string, name string, port int) error {
|
||||||
|
|
||||||
cmd := exec.Command(
|
cmd := exec.Command(
|
||||||
@@ -56,7 +61,7 @@ func EnsureNetwork(name string) error {
|
|||||||
cmd = exec.Command("docker", "network", "create", name)
|
cmd = exec.Command("docker", "network", "create", name)
|
||||||
out, err := cmd.CombinedOutput()
|
out, err := cmd.CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("erro ao criar network %s: %w\noutput", name, err, string(out))
|
return fmt.Errorf("erro ao criar network %s: %w\noutput: %s", name, err, string(out))
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -102,30 +107,27 @@ func RunWireguardDockerContainer(envFilePath string, cv ConfigValues) error {
|
|||||||
return verifyContainerRunning(containerID)
|
return verifyContainerRunning(containerID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func RunAppClienteContainer(image, containerName, configPath, configDestinationPath string, cv ConfigValues) error {
|
// appClienteRunArgs builds the `docker run` argv for the app-dono-cliente container.
|
||||||
removeExistingContainer(containerName)
|
// Shared by RunAppClienteContainer (initial start) and RunUpdaterDockerContainer (which
|
||||||
|
// re-embeds the same argv in its recreate script), so the two never drift apart.
|
||||||
if err := EnsureNetwork(networkName); err != nil {
|
func appClienteRunArgs(image, containerName, configPath, configDestinationPath string, cv ConfigValues) ([]string, error) {
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
absPath, err := filepath.Abs(configPath)
|
absPath, err := filepath.Abs(configPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("erro ao resolver caminho absoluto: %w", err)
|
return nil, fmt.Errorf("erro ao resolver caminho absoluto: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
currentUser, err := user.Current()
|
currentUser, err := user.Current()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
uidGid := fmt.Sprintf("%s:%s", currentUser.Uid, currentUser.Gid)
|
uidGid := fmt.Sprintf("%s:%s", currentUser.Uid, currentUser.Gid)
|
||||||
|
|
||||||
args := []string{
|
args := []string{
|
||||||
"run", "-d",
|
"run", "-d",
|
||||||
"-u", uidGid,
|
"-u", uidGid,
|
||||||
"-p", fmt.Sprintf("%s:8080", cv.Server["port"]),
|
"-p", fmt.Sprintf("%s:%d", cv.Server["port"], containerAppPort),
|
||||||
"--name", containerName,
|
"--name", containerName,
|
||||||
"--network", "app-dono_app",
|
"--network", networkName,
|
||||||
"--restart", "unless-stopped",
|
"--restart", "unless-stopped",
|
||||||
"-v", fmt.Sprintf("%s:%s", absPath, configDestinationPath),
|
"-v", fmt.Sprintf("%s:%s", absPath, configDestinationPath),
|
||||||
"-v", fmt.Sprintf("%s:/app/certs", cv.Cert["cert_dir_path"]),
|
"-v", fmt.Sprintf("%s:/app/certs", cv.Cert["cert_dir_path"]),
|
||||||
@@ -134,6 +136,129 @@ func RunAppClienteContainer(image, containerName, configPath, configDestinationP
|
|||||||
args = append(args, "--security-opt", "seccomp=unconfined")
|
args = append(args, "--security-opt", "seccomp=unconfined")
|
||||||
}
|
}
|
||||||
args = append(args, image)
|
args = append(args, image)
|
||||||
|
return args, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func RunAppClienteContainer(image, containerName, configPath, configDestinationPath string, cv ConfigValues) error {
|
||||||
|
removeExistingContainer(containerName)
|
||||||
|
|
||||||
|
if err := EnsureNetwork(networkName); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
args, err := appClienteRunArgs(image, containerName, configPath, configDestinationPath, cv)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
cmd := exec.Command("docker", args...)
|
||||||
|
|
||||||
|
out, err := cmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("docker run falhou: %w\noutput: %s", err, string(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
time.Sleep(2 * time.Second)
|
||||||
|
containerID := strings.TrimSpace(string(out))
|
||||||
|
return verifyContainerRunning(containerID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// shellQuote POSIX single-quotes s for safe embedding in the updater's poll script:
|
||||||
|
// wrap in '...', escaping any embedded ' as '\''. Needed because cv fields (e.g.
|
||||||
|
// cert_dir_path) are operator-entered and end up inside a shell script, not a plain
|
||||||
|
// argv slot.
|
||||||
|
func shellQuote(s string) string {
|
||||||
|
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
|
||||||
|
}
|
||||||
|
|
||||||
|
func shellQuoteArgs(args []string) string {
|
||||||
|
quoted := make([]string, len(args))
|
||||||
|
for i, a := range args {
|
||||||
|
quoted[i] = shellQuote(a)
|
||||||
|
}
|
||||||
|
return strings.Join(quoted, " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// updaterPollIntervalSeconds is how often the updater checks the registry for a new
|
||||||
|
// app-cliente image.
|
||||||
|
const updaterPollIntervalSeconds = 300
|
||||||
|
|
||||||
|
// buildRecreateCmd takes the app-cliente run argv (built with the wizard-time port) and
|
||||||
|
// swaps the baked-in port for a `$PORT` shell reference, so the poll script's recreate
|
||||||
|
// step uses whatever port it reads live from the container (see the PORT= line in
|
||||||
|
// RunUpdaterDockerContainer) instead of always replaying the port typed into the wizard.
|
||||||
|
func buildRecreateCmd(recreateArgs []string, wizardPort string) string {
|
||||||
|
wizardPortArg := shellQuote(fmt.Sprintf("%s:%d", wizardPort, containerAppPort))
|
||||||
|
livePortArg := fmt.Sprintf(`"$PORT:%d"`, containerAppPort)
|
||||||
|
return strings.Replace("docker "+shellQuoteArgs(recreateArgs), wizardPortArg, livePortArg, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunUpdaterDockerContainer starts a tiny self-contained auto-updater for the
|
||||||
|
// app-dono-cliente container: no third-party updater project, just the official
|
||||||
|
// `docker:cli` image running a poll loop (docker pull, compare image IDs, recreate on
|
||||||
|
// change) written in Go and handed to it via `sh -c`. This exists because Watchtower
|
||||||
|
// (the previous approach) was archived upstream with no maintained drop-in successor
|
||||||
|
// recommended for production use — see StepRunUpdater in update.go.
|
||||||
|
//
|
||||||
|
// It mounts the docker socket (to pull/recreate) and the host's docker config.json
|
||||||
|
// (written by the StepDockerLogin `docker login`) so `docker pull` can authenticate
|
||||||
|
// against the private registry.
|
||||||
|
//
|
||||||
|
// The recreate command reuses appClienteRunArgs' host port only as a fallback: at
|
||||||
|
// recreate time the script re-reads the live container's actual published port via
|
||||||
|
// `docker inspect`, so a port changed by hand after install survives an auto-update
|
||||||
|
// instead of being silently reverted to whatever was typed into the wizard.
|
||||||
|
func RunUpdaterDockerContainer(appImage, appContainerName, configPath, configDestinationPath string, cv ConfigValues) error {
|
||||||
|
updaterName := "app-dono-updater"
|
||||||
|
|
||||||
|
removeExistingContainer(updaterName)
|
||||||
|
|
||||||
|
if out, err := PullImage(updaterImageName); err != nil {
|
||||||
|
return fmt.Errorf("erro ao baixar imagem do atualizador: %w\noutput: %s", err, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
home, err := os.UserHomeDir()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("erro ao localizar diretório home: %w", err)
|
||||||
|
}
|
||||||
|
dockerConfigPath := filepath.Join(home, ".docker", "config.json")
|
||||||
|
|
||||||
|
recreateArgs, err := appClienteRunArgs(appImage, appContainerName, configPath, configDestinationPath, cv)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
recreateCmd := buildRecreateCmd(recreateArgs, cv.Server["port"])
|
||||||
|
|
||||||
|
script := fmt.Sprintf(`set -e
|
||||||
|
IMAGE=%s
|
||||||
|
NAME=%s
|
||||||
|
while true; do
|
||||||
|
docker pull "$IMAGE" >/dev/null 2>&1 || true
|
||||||
|
CURRENT=$(docker inspect --format '{{.Image}}' "$NAME" 2>/dev/null || true)
|
||||||
|
LATEST=$(docker inspect --format '{{.Id}}' "$IMAGE" 2>/dev/null || true)
|
||||||
|
if [ -n "$LATEST" ] && [ "$CURRENT" != "$LATEST" ]; then
|
||||||
|
PORT=$(docker inspect --format '{{(index (index .NetworkSettings.Ports "%d/tcp") 0).HostPort}}' "$NAME" 2>/dev/null || true)
|
||||||
|
if [ -z "$PORT" ]; then PORT=%s; fi
|
||||||
|
docker stop "$NAME" >/dev/null 2>&1 || true
|
||||||
|
docker rm "$NAME" >/dev/null 2>&1 || true
|
||||||
|
%s
|
||||||
|
fi
|
||||||
|
sleep %d
|
||||||
|
done
|
||||||
|
`, shellQuote(appImage), shellQuote(appContainerName), containerAppPort, shellQuote(cv.Server["port"]), recreateCmd, updaterPollIntervalSeconds)
|
||||||
|
|
||||||
|
args := []string{
|
||||||
|
"run", "-d",
|
||||||
|
"--name", updaterName,
|
||||||
|
"--restart", "unless-stopped",
|
||||||
|
"-v", "/var/run/docker.sock:/var/run/docker.sock",
|
||||||
|
"-v", fmt.Sprintf("%s:/config.json", dockerConfigPath),
|
||||||
|
"-e", "DOCKER_CONFIG=/",
|
||||||
|
"--log-opt", "max-size=5m",
|
||||||
|
"--log-opt", "max-file=1",
|
||||||
|
"--entrypoint", "sh",
|
||||||
|
updaterImageName,
|
||||||
|
"-c", script,
|
||||||
|
}
|
||||||
cmd := exec.Command("docker", args...)
|
cmd := exec.Command("docker", args...)
|
||||||
|
|
||||||
out, err := cmd.CombinedOutput()
|
out, err := cmd.CombinedOutput()
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os/exec"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestShellQuoteArgsRoundTrip guards the updater's poll-script generation: cv fields
|
||||||
|
// (e.g. cert_dir_path) are operator-entered and get embedded into a shell script run
|
||||||
|
// inside the updater container. If shellQuote/shellQuoteArgs mis-escapes a value, that's
|
||||||
|
// a command-injection bug, not just a cosmetic one. This feeds tricky values through a
|
||||||
|
// real `sh` and checks they come back out exactly as they went in.
|
||||||
|
func TestShellQuoteArgsRoundTrip(t *testing.T) {
|
||||||
|
if _, err := exec.LookPath("sh"); err != nil {
|
||||||
|
t.Skip("sh not available")
|
||||||
|
}
|
||||||
|
|
||||||
|
cases := [][]string{
|
||||||
|
{"simple"},
|
||||||
|
{"has space"},
|
||||||
|
{"it's got a quote"},
|
||||||
|
{"$(echo injected)"},
|
||||||
|
{"a;b|c&d"},
|
||||||
|
{"back`tick`"},
|
||||||
|
{"multi", "arg space", "o'clock", "$HOME", "'"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, args := range cases {
|
||||||
|
script := "printf '%s\\n' " + shellQuoteArgs(args)
|
||||||
|
out, err := exec.Command("sh", "-c", script).Output()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sh failed for %v: %v", args, err)
|
||||||
|
}
|
||||||
|
got := strings.Split(strings.TrimRight(string(out), "\n"), "\n")
|
||||||
|
if !reflect.DeepEqual(got, args) {
|
||||||
|
t.Errorf("round trip mismatch for %v: got %v", args, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBuildRecreateCmdUsesLivePort guards against the updater silently reverting a host
|
||||||
|
// port that was changed by hand after install: the recreate command must reference the
|
||||||
|
// live $PORT read at recreate time, not replay the port typed into the wizard.
|
||||||
|
func TestBuildRecreateCmdUsesLivePort(t *testing.T) {
|
||||||
|
if _, err := exec.LookPath("sh"); err != nil {
|
||||||
|
t.Skip("sh not available")
|
||||||
|
}
|
||||||
|
|
||||||
|
args := []string{"run", "-d", "-p", "9999:8080", "--name", "app-dono-cliente"}
|
||||||
|
cmd := buildRecreateCmd(args, "9999")
|
||||||
|
|
||||||
|
if strings.Contains(cmd, "9999:8080") {
|
||||||
|
t.Fatalf("recreate command still contains the wizard-time port literal: %s", cmd)
|
||||||
|
}
|
||||||
|
if !strings.Contains(cmd, `"$PORT:8080"`) {
|
||||||
|
t.Fatalf("recreate command missing live $PORT reference: %s", cmd)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Swap the leading `docker` for `printf` so we can inspect the argv sh would have
|
||||||
|
// passed to docker, with PORT set as the poll script would set it live.
|
||||||
|
script := "PORT=8081\n" + strings.Replace(cmd, "docker ", "printf '%s\\n' ", 1)
|
||||||
|
out, err := exec.Command("sh", "-c", script).Output()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sh failed: %v", err)
|
||||||
|
}
|
||||||
|
got := strings.Split(strings.TrimRight(string(out), "\n"), "\n")
|
||||||
|
want := []string{"run", "-d", "-p", "8081:8080", "--name", "app-dono-cliente"}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Errorf("got %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,6 +17,11 @@ const (
|
|||||||
FieldTypeNumber
|
FieldTypeNumber
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// defaultInputWidth is the visible width of text inputs before the first window-size
|
||||||
|
// message arrives. It must be > 0 (and ideally >= the longest placeholder) so the
|
||||||
|
// placeholder renders in full; it is overridden responsively via FormStep.SetWidth.
|
||||||
|
const defaultInputWidth = 50
|
||||||
|
|
||||||
type FormField struct {
|
type FormField struct {
|
||||||
Id string
|
Id string
|
||||||
Label string
|
Label string
|
||||||
@@ -51,6 +56,9 @@ func NewFormStep(title string, fields []FormField) FormStep {
|
|||||||
|
|
||||||
ti := textinput.New()
|
ti := textinput.New()
|
||||||
ti.Placeholder = f.Fields[i].Placeholder
|
ti.Placeholder = f.Fields[i].Placeholder
|
||||||
|
// A non-zero width is required for the placeholder to render in full: with the
|
||||||
|
// default width of 0 the textinput truncates the placeholder to its first rune.
|
||||||
|
ti.SetWidth(defaultInputWidth)
|
||||||
if f.Fields[i].Default != "" {
|
if f.Fields[i].Default != "" {
|
||||||
ti.SetValue(f.Fields[i].Default)
|
ti.SetValue(f.Fields[i].Default)
|
||||||
}
|
}
|
||||||
@@ -129,6 +137,17 @@ func (f *FormStep) Values() map[string]string {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetWidth resizes every text input to w (selects are unaffected). Called on window
|
||||||
|
// resize so inputs fill the available terminal width and placeholders render in full.
|
||||||
|
func (f *FormStep) SetWidth(w int) {
|
||||||
|
for i := range f.Fields {
|
||||||
|
if f.Fields[i].Type == FieldTypeSelect {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
f.Fields[i].input.SetWidth(w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// View
|
// View
|
||||||
func (f FormStep) View() string {
|
func (f FormStep) View() string {
|
||||||
pad := strings.Repeat(" ", padding)
|
pad := strings.Repeat(" ", padding)
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Guards against the bubbles bug where a text input with width 0 renders only the
|
||||||
|
// first rune of its placeholder. NewFormStep must set a non-zero width.
|
||||||
|
func TestPlaceholderRendersBeyondFirstRune(t *testing.T) {
|
||||||
|
const placeholder = "postgres://user@host/db"
|
||||||
|
f := NewFormStep("t", []FormField{
|
||||||
|
{Id: "url", Label: "URL", Placeholder: placeholder, Type: FieldTypeText},
|
||||||
|
})
|
||||||
|
|
||||||
|
view := f.Fields[0].input.View()
|
||||||
|
if !strings.Contains(view, "ostgres://user@host/db") {
|
||||||
|
t.Errorf("placeholder appears truncated; rendered view = %q", view)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFormStepValues(t *testing.T) {
|
||||||
|
f := NewFormStep("Test", []FormField{
|
||||||
|
{
|
||||||
|
Id: "name",
|
||||||
|
Label: "Name",
|
||||||
|
Default: "john",
|
||||||
|
Type: FieldTypeText,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Id: "secret",
|
||||||
|
Label: "Secret",
|
||||||
|
Default: "hunter2",
|
||||||
|
Type: FieldTypePassword,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Id: "proto",
|
||||||
|
Label: "Protocol",
|
||||||
|
Default: "TCP",
|
||||||
|
Type: FieldTypeSelect,
|
||||||
|
Options: []string{"UDP", "TCP"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Id: "mode",
|
||||||
|
Label: "Mode",
|
||||||
|
Type: FieldTypeSelect,
|
||||||
|
Options: []string{"a", "b", "c"},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
values := f.Values()
|
||||||
|
|
||||||
|
want := map[string]string{
|
||||||
|
"name": "john", // text default
|
||||||
|
"secret": "hunter2",
|
||||||
|
"proto": "TCP", // select default resolves to the matching option
|
||||||
|
"mode": "a", // select with no default falls back to first option
|
||||||
|
}
|
||||||
|
|
||||||
|
for id, exp := range want {
|
||||||
|
if got := values[id]; got != exp {
|
||||||
|
t.Errorf("Values()[%q] = %q, want %q", id, got, exp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFormStepValues_SelectInvalidDefaultFallsBackToFirst(t *testing.T) {
|
||||||
|
f := NewFormStep("Test", []FormField{
|
||||||
|
{
|
||||||
|
Id: "proto",
|
||||||
|
Label: "Protocol",
|
||||||
|
Default: "NOPE", // not among options
|
||||||
|
Type: FieldTypeSelect,
|
||||||
|
Options: []string{"UDP", "TCP"},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if got := f.Values()["proto"]; got != "UDP" {
|
||||||
|
t.Errorf("Values()[proto] = %q, want first option %q", got, "UDP")
|
||||||
|
}
|
||||||
|
}
|
||||||
+45
-8
@@ -12,6 +12,7 @@ import (
|
|||||||
|
|
||||||
type Model struct {
|
type Model struct {
|
||||||
currentStep step
|
currentStep step
|
||||||
|
history []step // stack of input steps visited, for back navigation
|
||||||
cursor int
|
cursor int
|
||||||
width int
|
width int
|
||||||
height int
|
height int
|
||||||
@@ -61,8 +62,10 @@ type ConfigValues struct {
|
|||||||
type AppConfig struct {
|
type AppConfig struct {
|
||||||
Server struct {
|
Server struct {
|
||||||
Port int64 `toml:"port"`
|
Port int64 `toml:"port"`
|
||||||
|
HostPort int64 `toml:"host_port"`
|
||||||
Timeout int64 `toml:"timeout_seconds"`
|
Timeout int64 `toml:"timeout_seconds"`
|
||||||
Environment string `toml:"environment"`
|
Environment string `toml:"environment"`
|
||||||
|
SeccompUnconfined bool `toml:"seccomp_unconfined"`
|
||||||
} `toml:"server"`
|
} `toml:"server"`
|
||||||
Database struct {
|
Database struct {
|
||||||
Type string `toml:"type"`
|
Type string `toml:"type"`
|
||||||
@@ -82,18 +85,19 @@ type AppConfig struct {
|
|||||||
func loadConfig() AppConfig {
|
func loadConfig() AppConfig {
|
||||||
var config AppConfig
|
var config AppConfig
|
||||||
|
|
||||||
config.Server.Port = 8081
|
config.Server.Port = containerAppPort
|
||||||
|
config.Server.HostPort = 8081
|
||||||
config.Server.Timeout = 30
|
config.Server.Timeout = 30
|
||||||
config.Server.Environment = "production"
|
config.Server.Environment = "production"
|
||||||
|
|
||||||
config.Database.Type = "postgres"
|
config.Database.Type = "postgres"
|
||||||
config.Database.URL = "postgres://usuario:senha@banco:5432/app_dono_db"
|
|
||||||
config.Database.MaxConns = 10
|
config.Database.MaxConns = 10
|
||||||
config.Database.MinConns = 2
|
config.Database.MinConns = 2
|
||||||
|
|
||||||
config.Certificates.DirPath = "/caminho/para/diretorio"
|
// Database.URL, Certificates.DirPath and Application.CentralServerURL are
|
||||||
|
// intentionally left empty so the fields show their placeholder instead of a
|
||||||
config.Application.CentralServerURL = "https://servidor:8443"
|
// pre-filled dummy. A real config.toml (re-run) still seeds them through the
|
||||||
|
// decode below.
|
||||||
|
|
||||||
_, err := os.Stat("config.toml")
|
_, err := os.Stat("config.toml")
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -112,6 +116,11 @@ func InitialModel() Model {
|
|||||||
s.Spinner = spinner.Dot
|
s.Spinner = spinner.Dot
|
||||||
s.Style = SpinnerStyle
|
s.Style = SpinnerStyle
|
||||||
|
|
||||||
|
seccompDefault := "Não"
|
||||||
|
if cfg.Server.SeccompUnconfined {
|
||||||
|
seccompDefault = "Sim"
|
||||||
|
}
|
||||||
|
|
||||||
return Model{
|
return Model{
|
||||||
currentStep: StepCheckDocker,
|
currentStep: StepCheckDocker,
|
||||||
loginForm: NewFormStep("Login no Repositório Docker", []FormField{
|
loginForm: NewFormStep("Login no Repositório Docker", []FormField{
|
||||||
@@ -172,9 +181,9 @@ func InitialModel() Model {
|
|||||||
serverForm: NewFormStep("Servidor", []FormField{
|
serverForm: NewFormStep("Servidor", []FormField{
|
||||||
{
|
{
|
||||||
Id: "port",
|
Id: "port",
|
||||||
Label: "Porta",
|
Label: "Porta (host)",
|
||||||
Placeholder: "8081",
|
Placeholder: "8081",
|
||||||
Default: strconv.FormatInt(cfg.Server.Port, 10),
|
Default: strconv.FormatInt(cfg.Server.HostPort, 10),
|
||||||
Type: FieldTypeNumber,
|
Type: FieldTypeNumber,
|
||||||
CharLimit: 4,
|
CharLimit: 4,
|
||||||
},
|
},
|
||||||
@@ -196,7 +205,7 @@ func InitialModel() Model {
|
|||||||
{
|
{
|
||||||
Id: "seccomp_unconfined",
|
Id: "seccomp_unconfined",
|
||||||
Label: "Modo Compatibilidade (máquinas antigas)",
|
Label: "Modo Compatibilidade (máquinas antigas)",
|
||||||
Default: "Não",
|
Default: seccompDefault,
|
||||||
Type: FieldTypeSelect,
|
Type: FieldTypeSelect,
|
||||||
Options: []string{"Não", "Sim"},
|
Options: []string{"Não", "Sim"},
|
||||||
},
|
},
|
||||||
@@ -263,3 +272,31 @@ func InitialModel() Model {
|
|||||||
func (m Model) Init() tea.Cmd {
|
func (m Model) Init() tea.Cmd {
|
||||||
return tea.Batch(CheckDockerCmd(), TickCmd(), m.spinner.Tick)
|
return tea.Batch(CheckDockerCmd(), TickCmd(), m.spinner.Tick)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// advance moves to the next step, recording the current step on the history stack when
|
||||||
|
// it is an input step so that Esc can return to it. Consecutive duplicates are skipped.
|
||||||
|
func (m *Model) advance(next step) {
|
||||||
|
if isInputStep(m.currentStep) {
|
||||||
|
if n := len(m.history); n == 0 || m.history[n-1] != m.currentStep {
|
||||||
|
m.history = append(m.history, m.currentStep)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m.currentStep = next
|
||||||
|
}
|
||||||
|
|
||||||
|
// goBack returns to the previous input step on the history stack, if any. It reports
|
||||||
|
// whether the step changed.
|
||||||
|
func (m *Model) goBack() bool {
|
||||||
|
if len(m.history) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
last := m.history[len(m.history)-1]
|
||||||
|
m.history = m.history[:len(m.history)-1]
|
||||||
|
m.currentStep = last
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// canGoBack reports whether Esc would return to a previous step from the current one.
|
||||||
|
func (m Model) canGoBack() bool {
|
||||||
|
return isInputStep(m.currentStep) && len(m.history) > 0
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestIsInputStep(t *testing.T) {
|
||||||
|
input := []step{
|
||||||
|
StepDockerLogin, StepIPQuestion, StepWireguardConfig,
|
||||||
|
StepAppConfig, StepServerConfig, StepDatabaseConfig,
|
||||||
|
StepCertConfig, StepReview,
|
||||||
|
}
|
||||||
|
for _, s := range input {
|
||||||
|
if !isInputStep(s) {
|
||||||
|
t.Errorf("isInputStep(%d) = false, want true", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
action := []step{
|
||||||
|
StepCheckDocker, StepDockerInstall, StepDownloadImage,
|
||||||
|
StepGenerateWireguardFile, StepDownloadWireguard, StepRunWireguard,
|
||||||
|
StepGenerateFile, StepRunDocker, StepDone,
|
||||||
|
}
|
||||||
|
for _, s := range action {
|
||||||
|
if isInputStep(s) {
|
||||||
|
t.Errorf("isInputStep(%d) = true, want false", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAdvancePushesInputSteps(t *testing.T) {
|
||||||
|
m := Model{currentStep: StepAppConfig}
|
||||||
|
|
||||||
|
m.advance(StepServerConfig)
|
||||||
|
if m.currentStep != StepServerConfig {
|
||||||
|
t.Fatalf("currentStep = %d, want StepServerConfig", m.currentStep)
|
||||||
|
}
|
||||||
|
if len(m.history) != 1 || m.history[0] != StepAppConfig {
|
||||||
|
t.Fatalf("history = %v, want [StepAppConfig]", m.history)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAdvanceSkipsActionSteps(t *testing.T) {
|
||||||
|
// Advancing away from an action step must not record it on the stack.
|
||||||
|
m := Model{currentStep: StepDownloadImage}
|
||||||
|
|
||||||
|
m.advance(StepIPQuestion)
|
||||||
|
if len(m.history) != 0 {
|
||||||
|
t.Fatalf("history = %v, want empty (action step not recorded)", m.history)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAdvanceDedupesConsecutive(t *testing.T) {
|
||||||
|
m := Model{currentStep: StepIPQuestion}
|
||||||
|
|
||||||
|
m.advance(StepIPQuestion) // self-advance (e.g. re-entering) must not duplicate
|
||||||
|
m.currentStep = StepIPQuestion
|
||||||
|
m.advance(StepIPQuestion)
|
||||||
|
|
||||||
|
if len(m.history) > 1 {
|
||||||
|
t.Fatalf("history = %v, want at most one entry", m.history)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGoBack(t *testing.T) {
|
||||||
|
m := Model{currentStep: StepCertConfig, history: []step{StepAppConfig, StepServerConfig, StepDatabaseConfig}}
|
||||||
|
|
||||||
|
if !m.goBack() {
|
||||||
|
t.Fatal("goBack() = false, want true")
|
||||||
|
}
|
||||||
|
if m.currentStep != StepDatabaseConfig {
|
||||||
|
t.Errorf("currentStep = %d, want StepDatabaseConfig", m.currentStep)
|
||||||
|
}
|
||||||
|
if len(m.history) != 2 {
|
||||||
|
t.Errorf("history len = %d, want 2", len(m.history))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGoBackEmptyHistory(t *testing.T) {
|
||||||
|
m := Model{currentStep: StepDockerLogin}
|
||||||
|
if m.goBack() {
|
||||||
|
t.Error("goBack() = true on empty history, want false")
|
||||||
|
}
|
||||||
|
if m.currentStep != StepDockerLogin {
|
||||||
|
t.Error("currentStep changed on empty goBack")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCanGoBack(t *testing.T) {
|
||||||
|
// Input step with history -> can go back.
|
||||||
|
m := Model{currentStep: StepServerConfig, history: []step{StepAppConfig}}
|
||||||
|
if !m.canGoBack() {
|
||||||
|
t.Error("canGoBack() = false, want true for input step with history")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Input step, empty history -> cannot.
|
||||||
|
m = Model{currentStep: StepDockerLogin}
|
||||||
|
if m.canGoBack() {
|
||||||
|
t.Error("canGoBack() = true, want false with empty history")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Action step with history -> cannot (esc handled by the step, not global back).
|
||||||
|
m = Model{currentStep: StepDownloadImage, history: []step{StepDockerLogin}}
|
||||||
|
if m.canGoBack() {
|
||||||
|
t.Error("canGoBack() = true on action step, want false")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,8 +24,25 @@ const (
|
|||||||
StepDatabaseConfig
|
StepDatabaseConfig
|
||||||
StepCertConfig
|
StepCertConfig
|
||||||
|
|
||||||
|
// Review
|
||||||
|
StepReview
|
||||||
|
|
||||||
// Finalizing
|
// Finalizing
|
||||||
StepGenerateFile
|
StepGenerateFile
|
||||||
StepRunDocker
|
StepRunDocker
|
||||||
|
StepRunUpdater
|
||||||
StepDone
|
StepDone
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// isInputStep reports whether a step collects user input and therefore participates
|
||||||
|
// in back navigation. Action/wait steps (downloads, file generation, container runs)
|
||||||
|
// are excluded so that "back" never re-enters a side-effecting step.
|
||||||
|
func isInputStep(s step) bool {
|
||||||
|
switch s {
|
||||||
|
case StepDockerLogin, StepIPQuestion, StepWireguardConfig,
|
||||||
|
StepAppConfig, StepServerConfig, StepDatabaseConfig,
|
||||||
|
StepCertConfig, StepReview:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|||||||
+149
-22
@@ -11,6 +11,7 @@ import (
|
|||||||
const (
|
const (
|
||||||
imageName = "hub.davinti.com.br:443/app-dono/app-cliente:latest"
|
imageName = "hub.davinti.com.br:443/app-dono/app-cliente:latest"
|
||||||
wireguardImageName = "hub.davinti.com.br:443/davinti-vproxy:latest"
|
wireguardImageName = "hub.davinti.com.br:443/davinti-vproxy:latest"
|
||||||
|
updaterImageName = "docker:cli"
|
||||||
configPath = "config.toml"
|
configPath = "config.toml"
|
||||||
wireguardConfigPath = "envs"
|
wireguardConfigPath = "envs"
|
||||||
)
|
)
|
||||||
@@ -20,6 +21,12 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
switch key.String() {
|
switch key.String() {
|
||||||
case "ctrl+c":
|
case "ctrl+c":
|
||||||
return m, tea.Quit
|
return m, tea.Quit
|
||||||
|
case "esc":
|
||||||
|
// Global "back" on input steps. Action/wait steps handle esc themselves.
|
||||||
|
if m.canGoBack() {
|
||||||
|
m.goBack()
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,6 +34,19 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
case tea.WindowSizeMsg:
|
case tea.WindowSizeMsg:
|
||||||
m.width = msg.Width
|
m.width = msg.Width
|
||||||
m.height = msg.Height
|
m.height = msg.Height
|
||||||
|
|
||||||
|
// Fit inputs to the terminal: subtract the left padding, the "> " prompt and
|
||||||
|
// the cursor cell, with a sensible floor for very narrow terminals.
|
||||||
|
inputWidth := msg.Width - (padding * 2) - 4
|
||||||
|
if inputWidth < 20 {
|
||||||
|
inputWidth = 20
|
||||||
|
}
|
||||||
|
for _, f := range []*FormStep{
|
||||||
|
&m.loginForm, &m.wireguardForm, &m.appForm,
|
||||||
|
&m.serverForm, &m.dbForm, &m.certForm,
|
||||||
|
} {
|
||||||
|
f.SetWidth(inputWidth)
|
||||||
|
}
|
||||||
case spinner.TickMsg:
|
case spinner.TickMsg:
|
||||||
var cmd tea.Cmd
|
var cmd tea.Cmd
|
||||||
m.spinner, cmd = m.spinner.Update(msg)
|
m.spinner, cmd = m.spinner.Update(msg)
|
||||||
@@ -43,9 +63,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
if done {
|
if done {
|
||||||
m.configValues.Login = m.loginForm.Values()
|
m.configValues.Login = m.loginForm.Values()
|
||||||
m.currentStep = StepDownloadImage
|
m.advance(StepDownloadImage)
|
||||||
|
|
||||||
return m, DownloadImageCmd(m.configValues.Login["user"], m.configValues.Login["password"])
|
return m, DownloadImageCmd(imageName, m.configValues.Login["user"], m.configValues.Login["password"])
|
||||||
}
|
}
|
||||||
|
|
||||||
return m, cmd
|
return m, cmd
|
||||||
@@ -64,7 +84,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
m.downloadDone = false
|
m.downloadDone = false
|
||||||
m.downloadMessage = ""
|
m.downloadMessage = ""
|
||||||
m.downloadError = nil
|
m.downloadError = nil
|
||||||
m.currentStep = StepGenerateWireguardFile
|
m.advance(StepGenerateWireguardFile)
|
||||||
|
|
||||||
return m, GenerateWireguardConfigFile(m.configValues, wireguardConfigPath)
|
return m, GenerateWireguardConfigFile(m.configValues, wireguardConfigPath)
|
||||||
}
|
}
|
||||||
@@ -82,7 +102,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
if done {
|
if done {
|
||||||
m.configValues.Application = m.appForm.Values()
|
m.configValues.Application = m.appForm.Values()
|
||||||
m.currentStep = StepServerConfig
|
m.advance(StepServerConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
return m, cmd
|
return m, cmd
|
||||||
@@ -91,7 +111,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
if done {
|
if done {
|
||||||
m.configValues.Server = m.serverForm.Values()
|
m.configValues.Server = m.serverForm.Values()
|
||||||
m.currentStep = StepDatabaseConfig
|
m.advance(StepDatabaseConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
return m, cmd
|
return m, cmd
|
||||||
@@ -100,7 +120,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
if done {
|
if done {
|
||||||
m.configValues.Database = m.dbForm.Values()
|
m.configValues.Database = m.dbForm.Values()
|
||||||
m.currentStep = StepCertConfig
|
m.advance(StepCertConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
return m, cmd
|
return m, cmd
|
||||||
@@ -109,19 +129,18 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
if done {
|
if done {
|
||||||
m.configValues.Cert = m.certForm.Values()
|
m.configValues.Cert = m.certForm.Values()
|
||||||
m.currentStep = StepGenerateFile
|
m.advance(StepReview)
|
||||||
|
|
||||||
m.finishedFile = false
|
|
||||||
m.configFileError = nil
|
|
||||||
|
|
||||||
return m, GenerateConfigFile(m.configValues, configPath)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return m, cmd
|
return m, cmd
|
||||||
|
case StepReview:
|
||||||
|
return m.updateReview(msg)
|
||||||
case StepGenerateFile:
|
case StepGenerateFile:
|
||||||
return m.updateGenerateFile(msg)
|
return m.updateGenerateFile(msg)
|
||||||
case StepRunDocker:
|
case StepRunDocker:
|
||||||
return m.updateRunDocker(msg)
|
return m.updateRunDocker(msg)
|
||||||
|
case StepRunUpdater:
|
||||||
|
return m.updateRunUpdater(msg)
|
||||||
case StepDone:
|
case StepDone:
|
||||||
return m, tea.Quit
|
return m, tea.Quit
|
||||||
}
|
}
|
||||||
@@ -146,9 +165,9 @@ func (m Model) updateCheckDocker(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
if m.checkDockerDone && m.checkProgress == 1 {
|
if m.checkDockerDone && m.checkProgress == 1 {
|
||||||
if m.dockerInstalled {
|
if m.dockerInstalled {
|
||||||
m.loading = true
|
m.loading = true
|
||||||
m.currentStep = StepDockerLogin
|
m.advance(StepDockerLogin)
|
||||||
} else {
|
} else {
|
||||||
m.currentStep = StepDockerInstall
|
m.advance(StepDockerInstall)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -175,11 +194,19 @@ func (m Model) updateDownloadImage(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
case tea.KeyPressMsg:
|
case tea.KeyPressMsg:
|
||||||
if m.downloadDone && m.downloadError == nil {
|
if m.downloadDone && m.downloadError == nil {
|
||||||
m.currentStep = StepIPQuestion
|
m.advance(StepIPQuestion)
|
||||||
} else if m.downloadDone {
|
} else if m.downloadDone {
|
||||||
|
switch msg.String() {
|
||||||
|
case "r":
|
||||||
|
m.downloadDone = false
|
||||||
|
m.downloadMessage = ""
|
||||||
|
m.downloadError = nil
|
||||||
|
return m, DownloadImageCmd(imageName, m.configValues.Login["user"], m.configValues.Login["password"])
|
||||||
|
default:
|
||||||
return m, tea.Quit
|
return m, tea.Quit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
@@ -201,11 +228,11 @@ func (m Model) updateIPQuestion(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
case "enter":
|
case "enter":
|
||||||
// Yes
|
// Yes
|
||||||
if m.cursor == 0 {
|
if m.cursor == 0 {
|
||||||
m.currentStep = StepAppConfig
|
m.advance(StepAppConfig)
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
m.currentStep = StepWireguardConfig
|
m.advance(StepWireguardConfig)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,9 +256,17 @@ func (m Model) updateDownloadWireguard(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
if m.downloadDone && m.downloadError == nil {
|
if m.downloadDone && m.downloadError == nil {
|
||||||
m.currentStep = StepRunWireguard
|
m.currentStep = StepRunWireguard
|
||||||
} else if m.downloadDone {
|
} else if m.downloadDone {
|
||||||
|
switch msg.String() {
|
||||||
|
case "r":
|
||||||
|
m.downloadDone = false
|
||||||
|
m.downloadMessage = ""
|
||||||
|
m.downloadError = nil
|
||||||
|
return m, DownloadImageCmd(wireguardImageName, m.configValues.Login["user"], m.configValues.Login["password"])
|
||||||
|
default:
|
||||||
return m, tea.Quit
|
return m, tea.Quit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
@@ -245,16 +280,21 @@ func (m Model) updateGenerateWireguardFile(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
if msg.Err == nil {
|
if msg.Err == nil {
|
||||||
m.currentStep = StepDownloadWireguard
|
m.currentStep = StepDownloadWireguard
|
||||||
|
|
||||||
return m, DownloadWireguardImageCmd(m.configValues.Login["user"], m.configValues.Login["password"])
|
return m, DownloadImageCmd(wireguardImageName, m.configValues.Login["user"], m.configValues.Login["password"])
|
||||||
}
|
}
|
||||||
|
|
||||||
case tea.KeyPressMsg:
|
case tea.KeyPressMsg:
|
||||||
if m.finishedFile && m.configFileError != nil {
|
if m.finishedFile && m.configFileError != nil {
|
||||||
return m, tea.Quit
|
// Validation error (e.g. MTU): go back to the form to correct it. The form
|
||||||
|
// is the top of the history stack, so goBack lands on it without leaving a
|
||||||
|
// duplicate entry; fall back to a direct set if history is unexpectedly empty.
|
||||||
|
if !m.goBack() {
|
||||||
|
m.currentStep = StepWireguardConfig
|
||||||
|
}
|
||||||
} else if m.finishedFile && m.configFileError == nil {
|
} else if m.finishedFile && m.configFileError == nil {
|
||||||
m.currentStep = StepDownloadWireguard
|
m.currentStep = StepDownloadWireguard
|
||||||
|
|
||||||
return m, DownloadWireguardImageCmd(m.configValues.Login["user"], m.configValues.Login["password"])
|
return m, DownloadImageCmd(wireguardImageName, m.configValues.Login["user"], m.configValues.Login["password"])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -269,9 +309,36 @@ func (m Model) updateRunWireguardDocker(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
case tea.KeyPressMsg:
|
case tea.KeyPressMsg:
|
||||||
if m.finishedDockerRun && m.dockerRunError != nil {
|
if m.finishedDockerRun && m.dockerRunError != nil {
|
||||||
|
switch msg.String() {
|
||||||
|
case "r":
|
||||||
|
m.finishedDockerRun = false
|
||||||
|
m.dockerRunError = nil
|
||||||
|
return m, RunWireguardContainer(wireguardConfigPath, m.configValues)
|
||||||
|
default:
|
||||||
return m, tea.Quit
|
return m, tea.Quit
|
||||||
|
}
|
||||||
} else if m.finishedDockerRun && m.dockerRunError == nil {
|
} else if m.finishedDockerRun && m.dockerRunError == nil {
|
||||||
m.currentStep = StepAppConfig
|
m.advance(StepAppConfig)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// updateReview shows the collected configuration for confirmation before any files are
|
||||||
|
// written. Enter confirms and generates config.toml; Esc (handled globally) goes back
|
||||||
|
// to the previous form to edit.
|
||||||
|
func (m Model) updateReview(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||||
|
switch msg := msg.(type) {
|
||||||
|
case tea.KeyPressMsg:
|
||||||
|
switch msg.String() {
|
||||||
|
case "enter":
|
||||||
|
m.advance(StepGenerateFile)
|
||||||
|
|
||||||
|
m.finishedFile = false
|
||||||
|
m.configFileError = nil
|
||||||
|
|
||||||
|
return m, GenerateConfigFile(m.configValues, configPath)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -286,7 +353,11 @@ func (m Model) updateGenerateFile(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
case tea.KeyPressMsg:
|
case tea.KeyPressMsg:
|
||||||
if m.finishedFile && m.configFileError != nil {
|
if m.finishedFile && m.configFileError != nil {
|
||||||
return m, tea.Quit
|
// Validation error: return to the review (top of the stack) so the user can
|
||||||
|
// navigate back to the forms; direct set as a fallback.
|
||||||
|
if !m.goBack() {
|
||||||
|
m.currentStep = StepReview
|
||||||
|
}
|
||||||
} else if m.finishedFile && m.configFileError == nil {
|
} else if m.finishedFile && m.configFileError == nil {
|
||||||
m.currentStep = StepRunDocker
|
m.currentStep = StepRunDocker
|
||||||
|
|
||||||
@@ -314,7 +385,63 @@ func (m Model) updateRunDocker(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
case tea.KeyPressMsg:
|
case tea.KeyPressMsg:
|
||||||
if m.finishedDockerRun && m.dockerRunError != nil {
|
if m.finishedDockerRun && m.dockerRunError != nil {
|
||||||
|
switch msg.String() {
|
||||||
|
case "r":
|
||||||
|
m.finishedDockerRun = false
|
||||||
|
m.dockerRunError = nil
|
||||||
|
return m, RunAppContainer(
|
||||||
|
imageName,
|
||||||
|
"app-dono-cliente",
|
||||||
|
configPath,
|
||||||
|
fmt.Sprintf("/app/%s", configPath),
|
||||||
|
m.configValues,
|
||||||
|
)
|
||||||
|
default:
|
||||||
return m, tea.Quit
|
return m, tea.Quit
|
||||||
|
}
|
||||||
|
} else if m.finishedDockerRun && m.dockerRunError == nil {
|
||||||
|
m.currentStep = StepRunUpdater
|
||||||
|
|
||||||
|
m.finishedDockerRun = false
|
||||||
|
m.dockerRunError = nil
|
||||||
|
|
||||||
|
return m, RunUpdaterContainer(
|
||||||
|
imageName,
|
||||||
|
"app-dono-cliente",
|
||||||
|
configPath,
|
||||||
|
fmt.Sprintf("/app/%s", configPath),
|
||||||
|
m.configValues,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// updateRunUpdater starts the auto-update agent that watches the app-dono-cliente
|
||||||
|
// container and pulls/recreates it whenever a new image is pushed to :latest.
|
||||||
|
func (m Model) updateRunUpdater(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||||
|
switch msg := msg.(type) {
|
||||||
|
case DockerRunMsg:
|
||||||
|
m.finishedDockerRun = true
|
||||||
|
m.dockerRunError = msg.Err
|
||||||
|
|
||||||
|
case tea.KeyPressMsg:
|
||||||
|
if m.finishedDockerRun && m.dockerRunError != nil {
|
||||||
|
switch msg.String() {
|
||||||
|
case "r":
|
||||||
|
m.finishedDockerRun = false
|
||||||
|
m.dockerRunError = nil
|
||||||
|
return m, RunUpdaterContainer(
|
||||||
|
imageName,
|
||||||
|
"app-dono-cliente",
|
||||||
|
configPath,
|
||||||
|
fmt.Sprintf("/app/%s", configPath),
|
||||||
|
m.configValues,
|
||||||
|
)
|
||||||
|
default:
|
||||||
|
return m, tea.Quit
|
||||||
|
}
|
||||||
} else if m.finishedDockerRun && m.dockerRunError == nil {
|
} else if m.finishedDockerRun && m.dockerRunError == nil {
|
||||||
m.currentStep = StepDone
|
m.currentStep = StepDone
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
// Version is the installer version. It is stamped at build time via
|
||||||
|
// -ldflags "-X git.davinti.com.br/davinTI/app-dono/tui/internal/tui.Version=<v>"
|
||||||
|
// (see the Makefile) and defaults to "dev" for local builds.
|
||||||
|
var Version = "dev"
|
||||||
+99
-17
@@ -10,15 +10,33 @@ import (
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
header = "App do Dono - Instalador Cliente"
|
header = "App do Dono - Instalador Cliente"
|
||||||
defaultMsg = "ctrl+c: sair"
|
|
||||||
anyKeyOutMsg = "qualquer tecla: sair"
|
anyKeyOutMsg = "qualquer tecla: sair"
|
||||||
formMsg = "tab: próximo campo • enter: confirmar • ctrl+c: sair"
|
retryMsg = "r: tentar novamente • q: sair"
|
||||||
|
fixMsg = "qualquer tecla: voltar e corrigir"
|
||||||
|
|
||||||
|
formBase = "tab: próximo campo • enter: confirmar"
|
||||||
|
ipBase = "↑/↓: navegar • enter: selecionar"
|
||||||
|
reviewBase = "enter: confirmar e instalar"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// helpFor builds the footer for an input step, appending "esc: voltar" when back
|
||||||
|
// navigation is available and always ending with "ctrl+c: sair".
|
||||||
|
func (m Model) helpFor(base string) string {
|
||||||
|
parts := []string{}
|
||||||
|
if base != "" {
|
||||||
|
parts = append(parts, base)
|
||||||
|
}
|
||||||
|
if m.canGoBack() {
|
||||||
|
parts = append(parts, "esc: voltar")
|
||||||
|
}
|
||||||
|
parts = append(parts, "ctrl+c: sair")
|
||||||
|
return strings.Join(parts, " • ")
|
||||||
|
}
|
||||||
|
|
||||||
func (m Model) View() tea.View {
|
func (m Model) View() tea.View {
|
||||||
pad := strings.Repeat(" ", padding)
|
pad := strings.Repeat(" ", padding)
|
||||||
var body string
|
var body string
|
||||||
helpMsg := defaultMsg
|
helpMsg := m.helpFor("")
|
||||||
|
|
||||||
switch m.currentStep {
|
switch m.currentStep {
|
||||||
// Docker stuff
|
// Docker stuff
|
||||||
@@ -29,53 +47,70 @@ func (m Model) View() tea.View {
|
|||||||
helpMsg = anyKeyOutMsg
|
helpMsg = anyKeyOutMsg
|
||||||
case StepDockerLogin:
|
case StepDockerLogin:
|
||||||
body = m.loginForm.View()
|
body = m.loginForm.View()
|
||||||
helpMsg = formMsg
|
helpMsg = m.helpFor(formBase)
|
||||||
case StepDownloadImage:
|
case StepDownloadImage:
|
||||||
body = m.viewDownloadImage()
|
body = m.viewDownloadImage()
|
||||||
|
if m.downloadDone && m.downloadError != nil {
|
||||||
|
helpMsg = retryMsg
|
||||||
|
}
|
||||||
|
|
||||||
// IP Stuff
|
// IP Stuff
|
||||||
case StepIPQuestion:
|
case StepIPQuestion:
|
||||||
body = m.viewIPQuestion()
|
body = m.viewIPQuestion()
|
||||||
|
helpMsg = m.helpFor(ipBase)
|
||||||
case StepWireguardConfig:
|
case StepWireguardConfig:
|
||||||
body = m.wireguardForm.View()
|
body = m.wireguardForm.View()
|
||||||
helpMsg = formMsg
|
helpMsg = m.helpFor(formBase)
|
||||||
case StepGenerateWireguardFile:
|
case StepGenerateWireguardFile:
|
||||||
body = m.viewGenerateFile()
|
body = m.viewGenerateFile()
|
||||||
if m.finishedFile && m.configFileError != nil {
|
if m.finishedFile && m.configFileError != nil {
|
||||||
helpMsg = anyKeyOutMsg
|
helpMsg = fixMsg
|
||||||
}
|
}
|
||||||
case StepDownloadWireguard:
|
case StepDownloadWireguard:
|
||||||
body = m.viewDownloadImage()
|
body = m.viewDownloadImage()
|
||||||
|
if m.downloadDone && m.downloadError != nil {
|
||||||
|
helpMsg = retryMsg
|
||||||
|
}
|
||||||
case StepRunWireguard:
|
case StepRunWireguard:
|
||||||
body = m.viewDockerRun()
|
body = m.viewDockerRun()
|
||||||
if m.finishedDockerRun && m.dockerRunError != nil {
|
if m.finishedDockerRun && m.dockerRunError != nil {
|
||||||
helpMsg = anyKeyOutMsg
|
helpMsg = retryMsg
|
||||||
}
|
}
|
||||||
|
|
||||||
// App Config Stuff
|
// App Config Stuff
|
||||||
case StepAppConfig:
|
case StepAppConfig:
|
||||||
body = m.appForm.View()
|
body = m.appForm.View()
|
||||||
helpMsg = formMsg
|
helpMsg = m.helpFor(formBase)
|
||||||
case StepServerConfig:
|
case StepServerConfig:
|
||||||
body = m.serverForm.View()
|
body = m.serverForm.View()
|
||||||
helpMsg = formMsg
|
helpMsg = m.helpFor(formBase)
|
||||||
case StepDatabaseConfig:
|
case StepDatabaseConfig:
|
||||||
body = m.dbForm.View()
|
body = m.dbForm.View()
|
||||||
helpMsg = formMsg
|
helpMsg = m.helpFor(formBase)
|
||||||
case StepCertConfig:
|
case StepCertConfig:
|
||||||
body = m.certForm.View()
|
body = m.certForm.View()
|
||||||
helpMsg = formMsg
|
helpMsg = m.helpFor(formBase)
|
||||||
|
|
||||||
|
// Review
|
||||||
|
case StepReview:
|
||||||
|
body = m.viewReview()
|
||||||
|
helpMsg = m.helpFor(reviewBase)
|
||||||
|
|
||||||
// Finalize
|
// Finalize
|
||||||
case StepGenerateFile:
|
case StepGenerateFile:
|
||||||
body = m.viewGenerateFile()
|
body = m.viewGenerateFile()
|
||||||
if m.finishedFile && m.configFileError != nil {
|
if m.finishedFile && m.configFileError != nil {
|
||||||
helpMsg = anyKeyOutMsg
|
helpMsg = fixMsg
|
||||||
}
|
}
|
||||||
case StepRunDocker:
|
case StepRunDocker:
|
||||||
body = m.viewDockerRun()
|
body = m.viewDockerRun()
|
||||||
if m.finishedDockerRun && m.dockerRunError != nil {
|
if m.finishedDockerRun && m.dockerRunError != nil {
|
||||||
helpMsg = anyKeyOutMsg
|
helpMsg = retryMsg
|
||||||
|
}
|
||||||
|
case StepRunUpdater:
|
||||||
|
body = m.viewDockerRun()
|
||||||
|
if m.finishedDockerRun && m.dockerRunError != nil {
|
||||||
|
helpMsg = retryMsg
|
||||||
}
|
}
|
||||||
case StepDone:
|
case StepDone:
|
||||||
body = m.viewDoneMessage()
|
body = m.viewDoneMessage()
|
||||||
@@ -84,8 +119,10 @@ func (m Model) View() tea.View {
|
|||||||
|
|
||||||
help := HelpStyle.Render(helpMsg)
|
help := HelpStyle.Render(helpMsg)
|
||||||
|
|
||||||
|
title := TitleStyle.Render(header) + HelpStyle.Render(" v"+Version)
|
||||||
|
|
||||||
v := tea.NewView(fmt.Sprintf("\n%s%s\n\n%s\n\n%s%s\n",
|
v := tea.NewView(fmt.Sprintf("\n%s%s\n\n%s\n\n%s%s\n",
|
||||||
pad, TitleStyle.Render(header),
|
pad, title,
|
||||||
body,
|
body,
|
||||||
pad, help,
|
pad, help,
|
||||||
))
|
))
|
||||||
@@ -155,7 +192,7 @@ func (m Model) viewDownloadImage() string {
|
|||||||
errText := dualPad + m.downloadMessage + "\n" + dualPad + m.downloadError.Error()
|
errText := dualPad + m.downloadMessage + "\n" + dualPad + m.downloadError.Error()
|
||||||
sb.WriteString(ErrorStyle.Width(m.width - (padding * 2)).Align(lipgloss.Left).Render(errText))
|
sb.WriteString(ErrorStyle.Width(m.width - (padding * 2)).Align(lipgloss.Left).Render(errText))
|
||||||
|
|
||||||
sb.WriteString("\n\n" + pad + "Pressione qualquer tecla para sair.")
|
sb.WriteString("\n\n" + pad + "Pressione 'r' para tentar novamente ou 'q' para sair.")
|
||||||
}
|
}
|
||||||
|
|
||||||
return sb.String()
|
return sb.String()
|
||||||
@@ -187,6 +224,51 @@ func (m Model) viewIPQuestion() string {
|
|||||||
return sb.String()
|
return sb.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m Model) viewReview() string {
|
||||||
|
pad := strings.Repeat(" ", padding)
|
||||||
|
cv := m.configValues
|
||||||
|
|
||||||
|
var sb strings.Builder
|
||||||
|
sb.WriteString(pad + "Revise as configurações antes de instalar:\n")
|
||||||
|
|
||||||
|
section := func(title string, rows [][2]string) {
|
||||||
|
sb.WriteString("\n" + pad + TitleStyle.Render(title) + "\n")
|
||||||
|
for _, r := range rows {
|
||||||
|
sb.WriteString(pad + HelpStyle.Render(r[0]+": ") + r[1] + "\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(cv.Wireguard) > 0 {
|
||||||
|
section("vproxy", [][2]string{
|
||||||
|
{"IP Virtual", cv.Wireguard["vip"]},
|
||||||
|
{"Proxy EDPS", cv.Wireguard["proxy_edps"]},
|
||||||
|
{"MTU", cv.Wireguard["mtu"]},
|
||||||
|
{"Protocolo", cv.Wireguard["proto"]},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
section("Aplicação", [][2]string{
|
||||||
|
{"Servidor Central", cv.Application["central_server_url"]},
|
||||||
|
{"Token de Inscrição", cv.Application["enrollment_token"]},
|
||||||
|
})
|
||||||
|
section("Servidor", [][2]string{
|
||||||
|
{"Porta (host)", cv.Server["port"]},
|
||||||
|
{"Timeout", cv.Server["timeout"]},
|
||||||
|
{"Ambiente", cv.Server["environment"]},
|
||||||
|
{"Modo Compatibilidade", cv.Server["seccomp_unconfined"]},
|
||||||
|
})
|
||||||
|
section("Banco de Dados", [][2]string{
|
||||||
|
{"Tipo", cv.Database["database_type"]},
|
||||||
|
{"URL", cv.Database["database_url"]},
|
||||||
|
{"Conexões (máx/mín)", cv.Database["max_conns"] + "/" + cv.Database["min_conns"]},
|
||||||
|
})
|
||||||
|
section("Certificado", [][2]string{
|
||||||
|
{"Diretório", cv.Cert["cert_dir_path"]},
|
||||||
|
})
|
||||||
|
|
||||||
|
return sb.String()
|
||||||
|
}
|
||||||
|
|
||||||
func (m Model) viewGenerateFile() string {
|
func (m Model) viewGenerateFile() string {
|
||||||
pad := strings.Repeat(" ", padding)
|
pad := strings.Repeat(" ", padding)
|
||||||
var sb strings.Builder
|
var sb strings.Builder
|
||||||
@@ -205,7 +287,7 @@ func (m Model) viewGenerateFile() string {
|
|||||||
errText := dualPad + m.configFileError.Error()
|
errText := dualPad + m.configFileError.Error()
|
||||||
sb.WriteString(ErrorStyle.Width(m.width - (padding * 2)).Align(lipgloss.Left).Render(errText))
|
sb.WriteString(ErrorStyle.Width(m.width - (padding * 2)).Align(lipgloss.Left).Render(errText))
|
||||||
|
|
||||||
sb.WriteString("\n\n" + pad + "Tente novamente.")
|
sb.WriteString("\n\n" + pad + "Pressione qualquer tecla para voltar e corrigir os dados.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -230,7 +312,7 @@ func (m Model) viewDockerRun() string {
|
|||||||
errText := dualPad + m.dockerRunError.Error()
|
errText := dualPad + m.dockerRunError.Error()
|
||||||
sb.WriteString(ErrorStyle.Width(m.width - (padding * 2)).Align(lipgloss.Left).Render(errText))
|
sb.WriteString(ErrorStyle.Width(m.width - (padding * 2)).Align(lipgloss.Left).Render(errText))
|
||||||
|
|
||||||
sb.WriteString("\n\n" + pad + "Tente novamente.")
|
sb.WriteString("\n\n" + pad + "Pressione 'r' para tentar novamente ou 'q' para sair.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Executable
+76
@@ -0,0 +1,76 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Manual fallback for tenants where the tuio installer's "run updater" step can't be
|
||||||
|
# used. Creates/recreates app-dono-updater: a poll loop (docker:cli, no third-party
|
||||||
|
# updater) that pulls app-dono-cliente's :latest image every 5 minutes and recreates the
|
||||||
|
# container when the image changes. Mirrors tuio's RunUpdaterDockerContainer /
|
||||||
|
# appClienteRunArgs (internal/tui/docker.go) -- keep the two in sync if either changes.
|
||||||
|
#
|
||||||
|
# Run this ON the tenant host, with app-dono-cliente already running. All of its run
|
||||||
|
# args (port, uid:gid, mounts, network, seccomp) are read live from the running
|
||||||
|
# container -- both now and every time the updater recreates it -- so nothing needs
|
||||||
|
# hand-editing per tenant and nothing baked-in goes stale if the container is ever
|
||||||
|
# changed by hand later (e.g. a manually remapped host port survives an auto-update).
|
||||||
|
set -e
|
||||||
|
|
||||||
|
APP_IMAGE="hub.davinti.com.br:443/app-dono/app-cliente:latest"
|
||||||
|
APP_NAME="app-dono-cliente"
|
||||||
|
UPDATER_NAME="app-dono-updater"
|
||||||
|
UPDATER_IMAGE="docker:cli"
|
||||||
|
POLL_INTERVAL="${POLL_INTERVAL:-300}"
|
||||||
|
DOCKER_CONFIG_HOST="${DOCKER_CONFIG_HOST:-$HOME/.docker/config.json}"
|
||||||
|
|
||||||
|
if ! docker inspect "$APP_NAME" >/dev/null 2>&1; then
|
||||||
|
echo "error: $APP_NAME is not running here -- start it first" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -f "$DOCKER_CONFIG_HOST" ]; then
|
||||||
|
echo "error: $DOCKER_CONFIG_HOST not found -- run 'docker login' for the registry first" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
docker rm -f "$UPDATER_NAME" >/dev/null 2>&1 || true
|
||||||
|
docker pull "$UPDATER_IMAGE" >/dev/null
|
||||||
|
|
||||||
|
# The container is inspected again inside the poll loop on every recreate (not just
|
||||||
|
# here), so this whole block runs live in the updater container, not just once now.
|
||||||
|
POLL_SCRIPT=$(cat <<SCRIPT
|
||||||
|
set -e
|
||||||
|
IMAGE='$APP_IMAGE'
|
||||||
|
NAME='$APP_NAME'
|
||||||
|
while true; do
|
||||||
|
docker pull "\$IMAGE" >/dev/null 2>&1 || true
|
||||||
|
CURRENT=\$(docker inspect --format '{{.Image}}' "\$NAME" 2>/dev/null || true)
|
||||||
|
LATEST=\$(docker inspect --format '{{.Id}}' "\$IMAGE" 2>/dev/null || true)
|
||||||
|
if [ -n "\$LATEST" ] && [ "\$CURRENT" != "\$LATEST" ]; then
|
||||||
|
PORT=\$(docker inspect --format '{{(index (index .NetworkSettings.Ports "8080/tcp") 0).HostPort}}' "\$NAME")
|
||||||
|
UIDGID=\$(docker inspect --format '{{.Config.User}}' "\$NAME")
|
||||||
|
NET=\$(docker inspect --format '{{range \$k, \$v := .NetworkSettings.Networks}}{{\$k}}{{end}}' "\$NAME")
|
||||||
|
CONFMNT=\$(docker inspect --format '{{range .Mounts}}{{if eq .Destination "/app/config.toml"}}{{.Source}}{{end}}{{end}}' "\$NAME")
|
||||||
|
CERTMNT=\$(docker inspect --format '{{range .Mounts}}{{if eq .Destination "/app/certs"}}{{.Source}}{{end}}{{end}}' "\$NAME")
|
||||||
|
SECFLAG=""
|
||||||
|
case \$(docker inspect --format '{{json .HostConfig.SecurityOpt}}' "\$NAME") in
|
||||||
|
*seccomp=unconfined*) SECFLAG="--security-opt seccomp=unconfined" ;;
|
||||||
|
esac
|
||||||
|
docker stop "\$NAME" >/dev/null 2>&1 || true
|
||||||
|
docker rm "\$NAME" >/dev/null 2>&1 || true
|
||||||
|
docker run -d -u "\$UIDGID" -p "\$PORT:8080" --name "\$NAME" --network "\$NET" --restart unless-stopped -v "\$CONFMNT:/app/config.toml" -v "\$CERTMNT:/app/certs" \$SECFLAG "\$IMAGE"
|
||||||
|
fi
|
||||||
|
sleep $POLL_INTERVAL
|
||||||
|
done
|
||||||
|
SCRIPT
|
||||||
|
)
|
||||||
|
|
||||||
|
docker run -d \
|
||||||
|
--name "$UPDATER_NAME" \
|
||||||
|
--restart unless-stopped \
|
||||||
|
-v /var/run/docker.sock:/var/run/docker.sock \
|
||||||
|
-v "$DOCKER_CONFIG_HOST:/config.json" \
|
||||||
|
-e DOCKER_CONFIG=/ \
|
||||||
|
--log-opt max-size=5m \
|
||||||
|
--log-opt max-file=1 \
|
||||||
|
--entrypoint sh \
|
||||||
|
"$UPDATER_IMAGE" \
|
||||||
|
-c "$POLL_SCRIPT"
|
||||||
|
|
||||||
|
echo "app-dono-updater created for $APP_NAME."
|
||||||
Reference in New Issue
Block a user