Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe70100959 | ||
|
|
5ed2d33124 | ||
|
|
2fecad021b | ||
|
|
a05b98fdf5 |
@@ -75,7 +75,9 @@ Makefile Multi-arch build + S3 publish.
|
||||
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. `StepDone`.
|
||||
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
|
||||
|
||||
@@ -95,6 +97,7 @@ 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
|
||||
@@ -115,6 +118,7 @@ Both are gitignored.
|
||||
| ------------------ | -------------------- | -------------------------------------------------------- |
|
||||
| `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.
|
||||
|
||||
@@ -45,7 +45,9 @@ O instalador conduz o operador por um assistente (wizard) no terminal que:
|
||||
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. Exibe a confirmação de sucesso.
|
||||
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
|
||||
|
||||
@@ -131,6 +133,11 @@ go run ./cmd
|
||||
┌──────────────────┐
|
||||
│ Sobe container │ (app-dono-cliente)
|
||||
│ app-dono-cliente │
|
||||
└────────┬─────────┘
|
||||
▼
|
||||
┌──────────────────┐
|
||||
│ Sobe container │ (app-dono-updater,
|
||||
│ de auto-update │ atualiza o app-cliente sozinho)
|
||||
└────────┬─────────┘
|
||||
▼
|
||||
✅ Concluído
|
||||
@@ -161,20 +168,29 @@ o instalador (no caso do `config.toml`).
|
||||
|
||||
## Containers e rede Docker
|
||||
|
||||
Todos os containers são conectados à rede Docker **`app-dono_app`** (criada
|
||||
automaticamente se não existir).
|
||||
`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:
|
||||
|
||||
- Ambos sobem com `--restart unless-stopped`.
|
||||
- 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.
|
||||
|
||||
|
||||
@@ -114,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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,10 +14,13 @@ func GenerateConfigTOML(cv ConfigValues) (string, error) {
|
||||
sb.WriteString("# Server Configuration\n")
|
||||
sb.WriteString("[server]\n")
|
||||
// Always containerAppPort: the container listens on this port internally; the
|
||||
// user's port is the host-side mapping (see RunAppClienteContainer).
|
||||
// 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("environment = %q\n", cv.Server["environment"]))
|
||||
sb.WriteString(fmt.Sprintf("seccomp_unconfined = %t\n", cv.Server["seccomp_unconfined"] == "Sim"))
|
||||
sb.WriteString("\n")
|
||||
|
||||
// [database]
|
||||
|
||||
@@ -60,6 +60,12 @@ func TestGenerateConfigTOML_RoundTrip(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
@@ -103,8 +109,8 @@ func TestGenerateConfigTOML_PortIsAlwaysContainerPort(t *testing.T) {
|
||||
if cfg.Server.Port != containerAppPort {
|
||||
t.Errorf("config port = %d, want fixed containerAppPort %d", cfg.Server.Port, containerAppPort)
|
||||
}
|
||||
if strings.Contains(out, "port = 9090") {
|
||||
t.Errorf("host port 9090 leaked into config.toml:\n%s", out)
|
||||
if cfg.Server.HostPort != 9090 {
|
||||
t.Errorf("host_port = %d, want 9090", cfg.Server.HostPort)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+130
-9
@@ -2,6 +2,7 @@ package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
@@ -106,21 +107,18 @@ func RunWireguardDockerContainer(envFilePath string, cv ConfigValues) error {
|
||||
return verifyContainerRunning(containerID)
|
||||
}
|
||||
|
||||
func RunAppClienteContainer(image, containerName, configPath, configDestinationPath string, cv ConfigValues) error {
|
||||
removeExistingContainer(containerName)
|
||||
|
||||
if err := EnsureNetwork(networkName); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// appClienteRunArgs builds the `docker run` argv for the app-dono-cliente container.
|
||||
// Shared by RunAppClienteContainer (initial start) and RunUpdaterDockerContainer (which
|
||||
// re-embeds the same argv in its recreate script), so the two never drift apart.
|
||||
func appClienteRunArgs(image, containerName, configPath, configDestinationPath string, cv ConfigValues) ([]string, error) {
|
||||
absPath, err := filepath.Abs(configPath)
|
||||
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()
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
uidGid := fmt.Sprintf("%s:%s", currentUser.Uid, currentUser.Gid)
|
||||
|
||||
@@ -138,6 +136,129 @@ func RunAppClienteContainer(image, containerName, configPath, configDestinationP
|
||||
args = append(args, "--security-opt", "seccomp=unconfined")
|
||||
}
|
||||
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...)
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
+11
-3
@@ -62,8 +62,10 @@ type ConfigValues struct {
|
||||
type AppConfig struct {
|
||||
Server struct {
|
||||
Port int64 `toml:"port"`
|
||||
HostPort int64 `toml:"host_port"`
|
||||
Timeout int64 `toml:"timeout_seconds"`
|
||||
Environment string `toml:"environment"`
|
||||
SeccompUnconfined bool `toml:"seccomp_unconfined"`
|
||||
} `toml:"server"`
|
||||
Database struct {
|
||||
Type string `toml:"type"`
|
||||
@@ -83,7 +85,8 @@ type AppConfig struct {
|
||||
func loadConfig() AppConfig {
|
||||
var config AppConfig
|
||||
|
||||
config.Server.Port = 8081
|
||||
config.Server.Port = containerAppPort
|
||||
config.Server.HostPort = 8081
|
||||
config.Server.Timeout = 30
|
||||
config.Server.Environment = "production"
|
||||
|
||||
@@ -113,6 +116,11 @@ func InitialModel() Model {
|
||||
s.Spinner = spinner.Dot
|
||||
s.Style = SpinnerStyle
|
||||
|
||||
seccompDefault := "Não"
|
||||
if cfg.Server.SeccompUnconfined {
|
||||
seccompDefault = "Sim"
|
||||
}
|
||||
|
||||
return Model{
|
||||
currentStep: StepCheckDocker,
|
||||
loginForm: NewFormStep("Login no Repositório Docker", []FormField{
|
||||
@@ -175,7 +183,7 @@ func InitialModel() Model {
|
||||
Id: "port",
|
||||
Label: "Porta (host)",
|
||||
Placeholder: "8081",
|
||||
Default: strconv.FormatInt(cfg.Server.Port, 10),
|
||||
Default: strconv.FormatInt(cfg.Server.HostPort, 10),
|
||||
Type: FieldTypeNumber,
|
||||
CharLimit: 4,
|
||||
},
|
||||
@@ -197,7 +205,7 @@ func InitialModel() Model {
|
||||
{
|
||||
Id: "seccomp_unconfined",
|
||||
Label: "Modo Compatibilidade (máquinas antigas)",
|
||||
Default: "Não",
|
||||
Default: seccompDefault,
|
||||
Type: FieldTypeSelect,
|
||||
Options: []string{"Não", "Sim"},
|
||||
},
|
||||
|
||||
@@ -30,6 +30,7 @@ const (
|
||||
// Finalizing
|
||||
StepGenerateFile
|
||||
StepRunDocker
|
||||
StepRunUpdater
|
||||
StepDone
|
||||
)
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
const (
|
||||
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"
|
||||
)
|
||||
@@ -138,6 +139,8 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
return m.updateGenerateFile(msg)
|
||||
case StepRunDocker:
|
||||
return m.updateRunDocker(msg)
|
||||
case StepRunUpdater:
|
||||
return m.updateRunUpdater(msg)
|
||||
case StepDone:
|
||||
return m, tea.Quit
|
||||
}
|
||||
@@ -396,6 +399,49 @@ func (m Model) updateRunDocker(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
default:
|
||||
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 {
|
||||
m.currentStep = StepDone
|
||||
}
|
||||
|
||||
@@ -107,6 +107,11 @@ func (m Model) View() tea.View {
|
||||
if m.finishedDockerRun && m.dockerRunError != nil {
|
||||
helpMsg = retryMsg
|
||||
}
|
||||
case StepRunUpdater:
|
||||
body = m.viewDockerRun()
|
||||
if m.finishedDockerRun && m.dockerRunError != nil {
|
||||
helpMsg = retryMsg
|
||||
}
|
||||
case StepDone:
|
||||
body = m.viewDoneMessage()
|
||||
helpMsg = anyKeyOutMsg
|
||||
|
||||
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