From e0e2201230fb88ef80363a4834563b4f0e368ba3 Mon Sep 17 00:00:00 2001 From: Welton Moura Date: Fri, 23 Oct 2026 13:57:39 -0300 Subject: [PATCH] feat: initial commit of mini-paas engine and documentation --- .dockerignore | 8 + .gitignore | 19 ++ Dockerfile | 50 ++++ GUIA_CRIACAO_APPS.md | 374 +++++++++++++++++++++++ README.md | 156 ++++++++++ cmd/paas/main.go | 77 +++++ docker-compose.yml | 43 +++ examples/page_teste/build.ps1 | 13 + examples/page_teste/build.sh | 10 + examples/page_teste/main.go | 167 +++++++++++ go.mod | 4 + internal/config/config.go | 67 +++++ internal/proxy/proxy.go | 254 ++++++++++++++++ internal/supervisor/supervisor.go | 337 +++++++++++++++++++++ internal/ui/dashboard.html | 474 ++++++++++++++++++++++++++++++ internal/ui/ui.go | 24 ++ internal/watcher/watcher.go | 186 ++++++++++++ 17 files changed, 2263 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 GUIA_CRIACAO_APPS.md create mode 100644 README.md create mode 100644 cmd/paas/main.go create mode 100644 docker-compose.yml create mode 100644 examples/page_teste/build.ps1 create mode 100644 examples/page_teste/build.sh create mode 100644 examples/page_teste/main.go create mode 100644 go.mod create mode 100644 internal/config/config.go create mode 100644 internal/proxy/proxy.go create mode 100644 internal/supervisor/supervisor.go create mode 100644 internal/ui/dashboard.html create mode 100644 internal/ui/ui.go create mode 100644 internal/watcher/watcher.go diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..296aae4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +.git +.github +apps/ +examples/ +*.log +*.exe +app +paas-engine diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cc25ea7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,19 @@ +# Binários e executáveis +*.exe +*.exe~ +*.dll +*.so +*.dylib +paas-engine +app + +# Logs +*.log +apps/**/app.log + +# Diretórios locais de teste +apps/ + +# IDEs +.idea/ +.vscode/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..75fba90 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,50 @@ +# ========================================== +# Etapa 1: Build do Orquestrador Go +# ========================================== +FROM golang:1.24-bookworm AS builder + +WORKDIR /src + +# Copia dependências e fontes +COPY go.mod ./ +# COPY go.sum ./ # se houver dependências externas +COPY . . + +# Compila o binário do Mini PaaS otimizado +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o /bin/paas-engine ./cmd/paas + +# ========================================== +# Etapa 2: Imagem Final (Debian Slim) +# Compatível com binários Go com glibc ou estáticos +# ========================================== +FROM debian:bookworm-slim + +# Instala certificados TLS, fuso horário e utilitários básicos +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates \ + tzdata \ + procps \ + curl \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR / + +# Copia o orquestrador compilado +COPY --from=builder /bin/paas-engine /usr/local/bin/paas-engine + +# Diretório base onde os apps serão montados pelo volume do CasaOS +RUN mkdir -p /apps + +# Variáveis padrão de ambiente +ENV PAAS_PORT=8080 +ENV PAAS_APPS_DIR=/apps +ENV PAAS_PORT_START=8001 +ENV PAAS_PORT_END=8999 +ENV PAAS_SCAN_INTERVAL=3 +ENV PAAS_DOMAIN=paas.weltonmoura.com.br + +EXPOSE 8080 + +VOLUME ["/apps"] + +ENTRYPOINT ["/usr/local/bin/paas-engine"] diff --git a/GUIA_CRIACAO_APPS.md b/GUIA_CRIACAO_APPS.md new file mode 100644 index 0000000..0bf14be --- /dev/null +++ b/GUIA_CRIACAO_APPS.md @@ -0,0 +1,374 @@ +# 📘 Guia de Desenvolvimento de Apps para o Mini PaaS + +Este guia ensina passo a passo como desenvolver, empacotar e publicar qualquer aplicação em **Go (Golang)** no seu **Mini PaaS**. + +--- + +## 📑 Índice + +1. [As 5 Regras de Ouro](#1-as-5-regras-de-ouro) +2. [Variáveis e Cabeçalhos Injetados](#2-variáveis-e-cabeçalhos-injetados) +3. [Modelos Prontos de Aplicações](#3-modelos-prontos-de-aplicações) + - [Exemplo 1: Página Web Simples (Biblioteca Padrão)](#exemplo-1-página-web-simples-biblioteca-padrão) + - [Exemplo 2: Página com CSS/JS Embutidos (`go:embed`)](#exemplo-2-página-com-cssjs-embutidos-goembed) + - [Exemplo 3: API REST (JSON)](#exemplo-3-api-rest-json) + - [Exemplo 4: App com Banco de Dados Persistente (SQLite)](#exemplo-4-app-com-banco-de-dados-persistente-sqlite) +4. [Como Lidar com Subcaminhos e Links HTML](#4-como-lidar-com-subcaminhos-e-links-html) +5. [Compilação para Linux (Cross-Compilation)](#5-compilação-para-linux-cross-compilation) +6. [Publicação na VPS (Deploy)](#6-publicação-na-vps-deploy) +7. [Logs e Diagnóstico de Erros](#7-logs-e-diagnóstico-de-erros) + +--- + +## 1. As 5 Regras de Ouro + +Para que qualquer binário funcione no Mini PaaS sem nenhuma configuração manual, siga estas 5 diretrizes: + +| # | Regra | Por que é importante? | +|---|---|---| +| **1** | **Escutar na variável `$PORT`** | O PaaS aloca uma porta interna livre (ex: `8001`, `8002`...) e a passa via ambiente. | +| **2** | **Compilar para Linux 64-bit** | O container roda em Debian Linux x86_64 (`GOOS=linux GOARCH=amd64`). | +| **3** | **Nome do binário** | Chame o executável de `app` ou `main` (ou o mesmo nome da pasta). | +| **4** | **Usar links relativos no HTML** | Como o app roda em `/meu_app/`, use `` ou `href="contato"` em vez de `/contato`. | +| **5** | **Binário estático (`CGO_ENABLED=0`)** | Garante que o binário não tenha dependências externas de bibliotecas do sistema. | + +--- + +## 2. Variáveis e Cabeçalhos Injetados + +### Variáveis de Ambiente +Quando seu binário é executado pelo supervisor, ele recebe automaticamente: + +* `PORT`: Porta TCP na qual seu servidor deve escutar (ex: `8001`). +* `APP_NAME`: Nome da aplicação (mesmo nome da subpasta). +* `APP_DIR`: Caminho absoluto da pasta do app (ex: `/apps/page_teste`). + +### Cabeçalhos HTTP Repassados +O Proxy Reverso encaminha para o seu binário cabeçalhos úteis: + +* `X-Forwarded-Prefix`: O prefixo de subcaminho (ex: `/page_teste`). +* `X-Forwarded-Host`: O domínio público original (ex: `paas.weltonmoura.com.br`). +* `X-Forwarded-Proto`: O protocolo utilizado (`https` ou `http`). +* `X-Real-IP`: O IP real do visitante. + +--- + +## 3. Modelos Prontos de Aplicações + +### Exemplo 1: Página Web Simples (Biblioteca Padrão) + +Ideal para páginas de apresentação, landing pages ou sites leves sem frameworks pesados: + +```go +package main + +import ( + "fmt" + "net/http" + "os" +) + +func main() { + // 1. Obtém a porta injetada pelo PaaS + port := os.Getenv("PORT") + if port == "" { + port = "8080" // fallback para testes locais + } + + // 2. Define as rotas (o PaaS já remove o prefixo /nome_do_app) + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + fmt.Fprintf(w, ` + + + Meu App + +

Olá do Mini PaaS! 🚀

+

Esta página está rodando nativamente em Go.

+ +

Ir para a página Sobre →

+ + + `) + }) + + http.HandleFunc("/sobre", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + fmt.Fprintf(w, ` + + + Sobre + +

Página Sobre

+

← Voltar para a Home

+ + + `) + }) + + // 3. Inicia o servidor HTTP + fmt.Printf("Servidor escutando na porta :%s\n", port) + if err := http.ListenAndServe(":"+port, nil); err != nil { + fmt.Printf("Erro: %v\n", err) + } +} +``` + +--- + +### Exemplo 2: Página com CSS/JS Embutidos (`go:embed`) + +A melhor forma de entregar páginas completas com CSS, JS e imagens dentro de um **único arquivo binário**: + +```text +meu_app/ +├── main.go +└── static/ + ├── style.css + └── script.js +``` + +```go +package main + +import ( + "embed" + "fmt" + "io/fs" + "net/http" + "os" +) + +//go:embed static/* +var staticFiles embed.FS + +func main() { + port := os.Getenv("PORT") + if port == "" { + port = "8080" + } + + mux := http.NewServeMux() + + // Sub-sistema de arquivos para a pasta static + staticFS, _ := fs.Sub(staticFiles, "static") + mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFS)))) + + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + fmt.Fprintf(w, ` + + + + + + + +

Página com CSS Embutido

+ + + + + `) + }) + + http.ListenAndServe(":"+port, mux) +} +``` + +--- + +### Exemplo 3: API REST (JSON) + +Para construir microsserviços, webhooks ou backends leves: + +```go +package main + +import ( + "encoding/json" + "net/http" + "os" + "time" +) + +type User struct { + ID int `json:"id"` + Nome string `json:"nome"` + Email string `json:"email"` +} + +func main() { + port := os.Getenv("PORT") + if port == "" { + port = "8080" + } + + mux := http.NewServeMux() + + // GET /api/status + mux.HandleFunc("/api/status", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]any{ + "status": "online", + "time": time.Now().Format(time.RFC3339), + }) + }) + + // GET /api/users + mux.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) { + users := []User{ + {ID: 1, Nome: "Welton", Email: "welton@exemplo.com"}, + {ID: 2, Nome: "Maria", Email: "maria@exemplo.com"}, + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(users) + }) + + http.ListenAndServe(":"+port, mux) +} +``` + +> **Acesso:** Você acessará em `https://paas.weltonmoura.com.br/meu_app/api/users`. + +--- + +### Exemplo 4: App com Banco de Dados Persistente (SQLite) + +Como o volume do CasaOS é persistente, seu app pode salvar arquivos e bancos SQLite diretamente dentro de sua própria pasta (`APP_DIR`): + +```go +package main + +import ( + "database/sql" + "fmt" + "net/http" + "os" + "path/filepath" + + _ "modernc.org/sqlite" // SQLite 100% puro em Go (não requer CGO!) +) + +func main() { + port := os.Getenv("PORT") + if port == "" { + port = "8080" + } + + appDir := os.Getenv("APP_DIR") + if appDir == "" { + appDir = "." + } + + // Salva o banco dentro da pasta persistente do app + dbPath := filepath.Join(appDir, "dados.db") + db, err := sql.Open("sqlite", dbPath) + if err != nil { + panic(err) + } + defer db.Close() + + // Cria tabela se não existir + _, _ = db.Exec("CREATE TABLE IF NOT EXISTS visitas (id INTEGER PRIMARY KEY, ts DATETIME);") + + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + _, _ = db.Exec("INSERT INTO visitas (ts) VALUES (CURRENT_TIMESTAMP);") + + var total int + _ = db.QueryRow("SELECT COUNT(*) FROM visitas").Scan(&total) + + fmt.Fprintf(w, "Total de visitas gravadas no SQLite persistente: %d\n", total) + }) + + http.ListenAndServe(":"+port, nil) +} +``` + +--- + +## 4. Como Lidar com Subcaminhos e Links HTML + +Ao navegar em `paas.weltonmoura.com.br/page_teste/`: + +### ❌ O que NÃO fazer: +```html + +Sobre + +``` + +### ✅ O que fazer: +```html + +Sobre +Sobre + + +``` + +> **Dica Bônus**: Se você configurar o Nginx Proxy Manager com wildcard DNS (`*.paas.weltonmoura.com.br`), o Mini PaaS também reconhece acessos diretos por subdomínio (ex: `page_teste.paas.weltonmoura.com.br`), onde barras normais (`/sobre`) funcionam normalmente. + +--- + +## 5. Compilação para Linux (Cross-Compilation) + +Sempre compile seu binário com destino para Linux 64-bit (`amd64`). + +### No Windows (PowerShell): +```powershell +$env:CGO_ENABLED="0"; $env:GOOS="linux"; $env:GOARCH="amd64"; go build -ldflags="-s -w" -o app main.go +``` + +### No Linux ou macOS (Terminal Bash): +```bash +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o app main.go +``` + +> **Explicação das flags:** +> - `CGO_ENABLED="0"`: Cria um binário 100% autônomo e portátil. +> - `-ldflags="-s -w"`: Remove símbolos de debug, reduzindo o tamanho do binário em até 40% (ex: de 12MB para 6MB). + +--- + +## 6. Publicação na VPS (Deploy) + +Publicar uma aplicação leva menos de 10 segundos: + +### Método A: Via Terminal (SCP) +```powershell +# 1. Crie a pasta na VPS (substitua 'novo_app' pelo nome do seu app) +ssh root@IP_DA_SUA_VPS "mkdir -p /DATA/AppData/mini-paas/apps/novo_app" + +# 2. Copie o binário compilado +scp app root@IP_DA_SUA_VPS:/DATA/AppData/mini-paas/apps/novo_app/ +``` + +### Método B: Pelo Gerenciador de Arquivos do CasaOS +1. Abra o painel web do CasaOS. +2. Abra o app **Arquivos** (Files). +3. Navegue até a pasta: `/DATA/AppData/mini-paas/apps/`. +4. Crie uma nova pasta com o nome do seu app (ex: `novo_app`). +5. Arraste e solte o arquivo `app` para dentro dela. + +### Hot Reload Automático +* Se você alterar o código, basta recompilar e substituir o arquivo `app` na pasta. +* O Mini PaaS detectará a nova data de modificação em até 3 segundos, encerrará o processo antigo e iniciará a nova versão sem derrubar o container. + +--- + +## 7. Logs e Diagnóstico de Erros + +Se sua página não abrir ou der erro 502/Crash: + +1. **Pelo Dashboard Web**: + - Acesse `https://paas.weltonmoura.com.br/` + - Localize o app na lista e clique no botão **Logs** + - Um modal abrirá exibindo as últimas mensagens do `stdout` e `stderr`. + +2. **Diretamente no arquivo**: + - Cada app gera automaticamente seu log em `/DATA/AppData/mini-paas/apps//app.log`. + - Você pode visualizá-lo via SSH com: + ```bash + tail -f /DATA/AppData/mini-paas/apps//app.log + ``` diff --git a/README.md b/README.md new file mode 100644 index 0000000..a7c4088 --- /dev/null +++ b/README.md @@ -0,0 +1,156 @@ +# 🚀 Mini PaaS para Binários Golang + +Um **Platform as a Service (PaaS)** leve, auto-hospedado e de alta performance escrito em Go, projetado para rodar na sua VPS com **CasaOS** e integrado ao **Nginx Proxy Manager (NPM)**. + +--- + +## 🌟 Como Funciona + +1. O container do **Mini PaaS** roda na sua VPS via Docker no CasaOS e escuta na porta `8080`. +2. O **Nginx Proxy Manager (NPM)** recebe as requisições em `paas.weltonmoura.com.br` e encaminha para o container. +3. Você cria uma subpasta no volume mapeado (ex: `/apps/page_teste/`) e coloca seu binário Go compilado para Linux lá dentro. +4. Em menos de 3 segundos, o Mini PaaS: + - Identifica o executável e aplica `chmod +x` automaticamente. + - Atribui uma porta interna dinâmica (ex: `8001`) e executa o binário injetando `PORT=8001`. + - Direciona a saída de logs para `/apps/page_teste/app.log`. + - Cria uma rota transparente: ao acessar `paas.weltonmoura.com.br/page_teste/`, a requisição é entregue para o seu binário! +5. Na raiz (`paas.weltonmoura.com.br/`), você tem um **Dashboard Moderno** em tempo real mostrando os apps ativos, portas, tempo de execução e visualizador de logs com 1 clique. + +--- + +## 📁 Estrutura de Diretórios + +```text +mini_paas/ +├── Dockerfile # Imagem base Debian Slim multi-stage +├── docker-compose.yml # Compose pronto para o CasaOS +├── README.md # Este guia de instalação +├── GUIA_CRIACAO_APPS.md # 📘 GUIA COMPLETO de desenvolvimento de apps +├── go.mod # Módulo Go do orquestrador +├── cmd/ +│ └── paas/main.go # Entrypoint do Mini PaaS +├── internal/ +│ ├── config/ # Carregamento de variáveis de ambiente +│ ├── supervisor/ # Gerenciamento de ciclo de vida e processos filhos +│ ├── watcher/ # Varredura contínua de novos binários +│ ├── proxy/ # Reverse proxy dinâmico (subcaminhos e subdomínios) +│ └── ui/ # Dashboard Web com visualizador de logs +└── examples/ + └── page_teste/ + ├── main.go # Exemplo funcional de micro-serviço Go + └── build.ps1 # Script auxiliar de compilação +``` + +--- + +## 🛠️ Passo a Passo de Instalação na VPS (CasaOS) + +### 1. Clonar ou Enviar os Arquivos para a VPS +Envie esta pasta `mini_paas` para a sua VPS (por exemplo em `/DATA/AppData/mini-paas-src` ou na pasta do seu usuário): +```bash +# Na sua máquina local: +scp -r mini_paas root@IP_DA_SUA_VPS:/DATA/AppData/mini-paas-src +``` + +### 2. Subir o Container no CasaOS +Acesse a VPS via SSH e execute: +```bash +cd /DATA/AppData/mini-paas-src +docker compose up -d --build +``` + +> **Dica no CasaOS**: Você também pode ir na interface web do CasaOS, clicar em `+` (Install a customized app) -> `Import` no topo direito, colar o conteúdo do arquivo `docker-compose.yml` e clicar em Salvar. + +--- + +## 🌐 Configuração no Nginx Proxy Manager (NPM) + +No painel web do seu **Nginx Proxy Manager**: + +1. Clique em **Hosts** > **Proxy Hosts** > **Add Proxy Host**. +2. Na aba **Details**: + * **Domain Names**: `paas.weltonmoura.com.br` + * **Scheme**: `http` + * **Forward Hostname / IP**: Coloque o IP da sua VPS ou `172.17.0.1` (gateway do Docker) + * **Forward Port**: `8080` + * Marque: **Block Common Exploits** + * Marque: **Websockets Support** +3. Na aba **SSL**: + * Selecione seu certificado Let's Encrypt (ou marque **Request a new SSL Certificate**) + * Marque: **Force SSL** + * Marque: **HTTP/2 Support** +4. Clique em **Save**. + +Agora acesse: `https://paas.weltonmoura.com.br` e você verá o Dashboard do Mini PaaS! + +--- + +## 💻 Como Desenvolver e Subir seus Apps em Go + +### 1. Contrato do App (Variável `PORT`) +O Mini PaaS injeta a porta em que seu binário deve escutar através da variável de ambiente `PORT`. Seu código em Go só precisa fazer isso: + +```go +package main + +import ( + "fmt" + "net/http" + "os" +) + +func main() { + port := os.Getenv("PORT") + if port == "" { + port = "8080" + } + + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "Olá do meu app em Go!") + }) + + http.ListenAndServe(":" + port, nil) +} +``` + +### 2. Cuidados com Links e Assets HTML (Subcaminhos) +Como o app responderá em `paas.weltonmoura.com.br/meu_app/`, **sempre use links e caminhos relativos** em seus arquivos HTML: +* ✅ Correto: `Sobre` ou `Sobre` +* ✅ Correto: `` +* ❌ Evite: `` (isso levará o navegador para a raiz do domínio principal) + +### 3. Compilar para Linux +No seu computador de desenvolvimento (Windows, Mac ou Linux): + +**No Windows (PowerShell):** +```powershell +$env:CGO_ENABLED="0"; $env:GOOS="linux"; $env:GOARCH="amd64"; go build -o app main.go +``` + +**No Linux ou macOS (Bash):** +```bash +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o app main.go +``` + +### 4. Fazer o Deploy (Copiar para o Volume) +Basta colocar o arquivo executável `app` dentro da pasta do app no CasaOS: + +```bash +# Exemplo via SCP da sua máquina: +scp app root@IP_DA_SUA_VPS:/DATA/AppData/mini-paas/apps/page_teste/ +``` +* Ou usando o **Gerenciador de Arquivos do CasaOS**: + - Navegue até `/DATA/AppData/mini-paas/apps/` + - Crie uma pasta chamada `page_teste` + - Arraste e solte o arquivo `app` para dentro dela! + +Em até 3 segundos, o Mini PaaS iniciará o executável e você poderá acessá-lo em: +👉 `https://paas.weltonmoura.com.br/page_teste/` + +--- + +## 🔍 Logs e Diagnóstico de Erros + +* Cada aplicação possui seu próprio arquivo de log em `/DATA/AppData/mini-paas/apps//app.log`. +* Você pode visualizar os logs em tempo real diretamente pelo botão **Logs** no Dashboard do Mini PaaS (`paas.weltonmoura.com.br`). +* Se seu binário sofrer um *panic* ou encerrar, o status mudará para `CRASHED` no Dashboard e os erros estarão registrados no log. diff --git a/cmd/paas/main.go b/cmd/paas/main.go new file mode 100644 index 0000000..d86f70f --- /dev/null +++ b/cmd/paas/main.go @@ -0,0 +1,77 @@ +package main + +import ( + "context" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "mini-paas/internal/config" + "mini-paas/internal/proxy" + "mini-paas/internal/supervisor" + "mini-paas/internal/watcher" +) + +func main() { + log.Println("==================================================") + log.Println(" MINI PAAS - ENGINE GO ") + log.Println("==================================================") + + cfg := config.Load() + log.Printf("[Config] Porta do PaaS: %s", cfg.Port) + log.Printf("[Config] Diretório de Apps: %s", cfg.AppsDir) + log.Printf("[Config] Pool de Portas: %d - %d", cfg.PortRangeStart, cfg.PortRangeEnd) + log.Printf("[Config] Intervalo de Scan: %v", cfg.ScanInterval) + log.Printf("[Config] Domínio Base: %s", cfg.Domain) + + // Inicializa o supervisor de processos + mgr := supervisor.NewManager(cfg.PortRangeStart, cfg.PortRangeEnd, cfg.AppsDir) + + // Inicializa o observador da pasta de apps + wt := watcher.NewWatcher(cfg.AppsDir, cfg.ScanInterval, mgr) + wt.Start() + log.Println("[Watcher] Monitoramento de diretório ativo.") + + // Inicializa o servidor HTTP e Proxy Reverso + srv := proxy.NewServer(cfg, mgr) + httpServer := &http.Server{ + Addr: ":" + cfg.Port, + Handler: srv, + ReadTimeout: 60 * time.Second, + WriteTimeout: 60 * time.Second, + IdleTimeout: 120 * time.Second, + } + + // Canal para shutdown gracioso + shutdownChan := make(chan os.Signal, 1) + signal.Notify(shutdownChan, os.Interrupt, syscall.SIGTERM) + + go func() { + log.Printf("[HTTP] Servidor rodando em http://0.0.0.0:%s", cfg.Port) + if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Fatalf("[HTTP] Falha fatal no servidor: %v", err) + } + }() + + <-shutdownChan + log.Println("\n[Shutdown] Sinal recebido. Encerrando Mini PaaS...") + + // Para o watcher + wt.Stop() + + // Encerra todos os apps filhos + for _, app := range mgr.ListApps() { + log.Printf("[Shutdown] Parando app '%s'...", app.Name) + mgr.Stop(app.Name) + } + + // Encerra o servidor HTTP + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = httpServer.Shutdown(ctx) + + log.Println("[Shutdown] Mini PaaS finalizado com sucesso.") +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..730dd07 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,43 @@ +name: mini-paas + +services: + mini-paas: + build: + context: . + dockerfile: Dockerfile + image: mini-paas:latest + container_name: mini-paas + restart: unless-stopped + ports: + # Porta exposta na VPS para o Nginx Proxy Manager encaminhar + - "8080:8080" + volumes: + # Pasta persistente no Host (padrão CasaOS) mapeada para /apps no container + - /DATA/AppData/mini-paas/apps:/apps + environment: + - PAAS_PORT=8080 + - PAAS_APPS_DIR=/apps + - PAAS_PORT_START=8001 + - PAAS_PORT_END=8999 + - PAAS_SCAN_INTERVAL=3 + - PAAS_DOMAIN=paas.weltonmoura.com.br + - TZ=America/Sao_Paulo + + # Metadados opcionais para o CasaOS exibir ícone e título amigáveis + x-casaos: + architectures: + - amd64 + - arm64 + main: mini-paas + description: + en_us: "Mini PaaS ultra leve para pequenos microserviços e páginas em Golang." + tagline: + en_us: "Mini PaaS para Binários Go" + developer: "Welton Moura" + author: "Welton Moura" + icon: "https://raw.githubusercontent.com/golang/go/master/assets/images/go-logo-blue.svg" + thumbnail: "https://raw.githubusercontent.com/golang/go/master/assets/images/go-logo-blue.svg" + title: + en_us: "Mini PaaS" + index: / + port_map: "8080" diff --git a/examples/page_teste/build.ps1 b/examples/page_teste/build.ps1 new file mode 100644 index 0000000..3bd971f --- /dev/null +++ b/examples/page_teste/build.ps1 @@ -0,0 +1,13 @@ +Write-Host "Compilando page_teste para Linux (amd64)..." -ForegroundColor Cyan +$env:CGO_ENABLED = "0" +$env:GOOS = "linux" +$env:GOARCH = "amd64" + +go build -ldflags="-s -w" -o app main.go + +if ($LASTEXITCODE -eq 0) { + Write-Host "Sucesso! Binario 'app' gerado para Linux." -ForegroundColor Green + Write-Host "Copie o arquivo 'app' para: /DATA/AppData/mini-paas/apps/page_teste/app" -ForegroundColor Yellow +} else { + Write-Host "Erro na compilacao." -ForegroundColor Red +} diff --git a/examples/page_teste/build.sh b/examples/page_teste/build.sh new file mode 100644 index 0000000..c689f71 --- /dev/null +++ b/examples/page_teste/build.sh @@ -0,0 +1,10 @@ +#!/bin/bash +echo "Compilando page_teste para Linux (amd64)..." +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o app main.go + +if [ $? -eq 0 ]; then + echo "Sucesso! Binário 'app' gerado para Linux." + echo "Copie o arquivo 'app' para: /DATA/AppData/mini-paas/apps/page_teste/app" +else + echo "Erro na compilação." +fi diff --git a/examples/page_teste/main.go b/examples/page_teste/main.go new file mode 100644 index 0000000..554fbed --- /dev/null +++ b/examples/page_teste/main.go @@ -0,0 +1,167 @@ +package main + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "os" + "sync/atomic" + "time" +) + +var requestCount uint64 + +func main() { + port := os.Getenv("PORT") + if port == "" { + port = "8080" + } + + appName := os.Getenv("APP_NAME") + if appName == "" { + appName = "page_teste" + } + + mux := http.NewServeMux() + + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/" { + http.NotFound(w, r) + return + } + + count := atomic.AddUint64(&requestCount, 1) + + w.Header().Set("Content-Type", "text/html; charset=utf-8") + fmt.Fprintf(w, ` + + + + + + App: %s + + + + + + + `, appName, appName, count, port, time.Now().Format(time.RFC3339), r.Host, r.Header.Get("X-Forwarded-Prefix"), r.Header.Get("X-Forwarded-Host")) + }) + + mux.HandleFunc("/sobre", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + fmt.Fprintf(w, ` + + + + + Sobre - %s + + + +
+

Página "Sobre" de Exemplo

+

Perceba que você navegou para /sobre usando um link relativo e continuou dentro do subcaminho do seu app!

+

← Voltar para a página inicial do app

+
+ + + `, appName) + }) + + mux.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "status": "healthy", + "app": appName, + "port": port, + "timestamp": time.Now().Unix(), + }) + }) + + log.Printf("[App %s] Iniciando servidor HTTP na porta :%s...", appName, port) + if err := http.ListenAndServe(":"+port, mux); err != nil { + log.Fatalf("[App %s] Erro no servidor: %v", appName, err) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..74e593c --- /dev/null +++ b/go.mod @@ -0,0 +1,4 @@ +module mini-paas + +go 1.22 + diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..7c2061a --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,67 @@ +package config + +import ( + "os" + "strconv" + "time" +) + +type Config struct { + Port string + AppsDir string + PortRangeStart int + PortRangeEnd int + ScanInterval time.Duration + Domain string +} + +func Load() *Config { + port := os.Getenv("PAAS_PORT") + if port == "" { + port = "8080" + } + + appsDir := os.Getenv("PAAS_APPS_DIR") + if appsDir == "" { + // Se existir /apps (dentro do container), usa ele; senão usa ./apps local para testes + if _, err := os.Stat("/apps"); err == nil { + appsDir = "/apps" + } else { + appsDir = "./apps" + } + } + + startPort := getEnvInt("PAAS_PORT_START", 8001) + endPort := getEnvInt("PAAS_PORT_END", 8999) + + scanSeconds := getEnvInt("PAAS_SCAN_INTERVAL", 3) + if scanSeconds < 1 { + scanSeconds = 3 + } + + domain := os.Getenv("PAAS_DOMAIN") + if domain == "" { + domain = "paas.weltonmoura.com.br" + } + + return &Config{ + Port: port, + AppsDir: appsDir, + PortRangeStart: startPort, + PortRangeEnd: endPort, + ScanInterval: time.Duration(scanSeconds) * time.Second, + Domain: domain, + } +} + +func getEnvInt(key string, defaultVal int) int { + v := os.Getenv(key) + if v == "" { + return defaultVal + } + n, err := strconv.Atoi(v) + if err != nil { + return defaultVal + } + return n +} diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go new file mode 100644 index 0000000..27a0b59 --- /dev/null +++ b/internal/proxy/proxy.go @@ -0,0 +1,254 @@ +package proxy + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "net/http/httputil" + "net/url" + "strings" + "sync" + + "mini-paas/internal/config" + "mini-paas/internal/supervisor" + "mini-paas/internal/ui" +) + +type Server struct { + cfg *config.Config + manager *supervisor.Manager + proxies map[int]*httputil.ReverseProxy + mu sync.RWMutex +} + +func NewServer(cfg *config.Config, mgr *supervisor.Manager) *Server { + return &Server{ + cfg: cfg, + manager: mgr, + proxies: make(map[int]*httputil.ReverseProxy), + } +} + +func (s *Server) getOrCreateProxy(port int, appName string, isSubdomain bool) *httputil.ReverseProxy { + s.mu.Lock() + defer s.mu.Unlock() + + targetURL, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", port)) + + // Cria proxy com reescrita customizada + proxy := httputil.NewSingleHostReverseProxy(targetURL) + originalDirector := proxy.Director + + proxy.Director = func(req *http.Request) { + originalDirector(req) + + // Se o roteamento foi por subcaminho, remove o prefixo /appName + if !isSubdomain { + prefix := "/" + appName + if strings.HasPrefix(req.URL.Path, prefix) { + req.URL.Path = strings.TrimPrefix(req.URL.Path, prefix) + if !strings.HasPrefix(req.URL.Path, "/") { + req.URL.Path = "/" + req.URL.Path + } + } + if req.URL.RawPath != "" && strings.HasPrefix(req.URL.RawPath, prefix) { + req.URL.RawPath = strings.TrimPrefix(req.URL.RawPath, prefix) + if !strings.HasPrefix(req.URL.RawPath, "/") { + req.URL.RawPath = "/" + req.URL.RawPath + } + } + req.Header.Set("X-Forwarded-Prefix", prefix) + } + + req.Header.Set("X-Forwarded-Host", req.Host) + if req.Header.Get("X-Forwarded-Proto") == "" { + req.Header.Set("X-Forwarded-Proto", "http") + } + } + + proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) { + log.Printf("[Proxy] Erro de conexão com app '%s' (: %d): %v", appName, port, err) + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(http.StatusBadGateway) + fmt.Fprintf(w, ` + + Erro 502 + + +

502 Bad Gateway

+

Não foi possível conectar ao app %s na porta interna :%d.

+

Voltar ao Dashboard

+ + `, appName, port) + } + + return proxy +} + +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // 1. Endpoints do PaaS + if r.URL.Path == "/" { + s.handleDashboard(w, r) + return + } + + if r.URL.Path == "/_paas/api/apps" { + s.handleAPIApps(w, r) + return + } + + if r.URL.Path == "/_paas/api/logs" { + s.handleAPILogs(w, r) + return + } + + // 2. Tenta extrair app por Subdomínio (ex: page-teste.paas.weltonmoura.com.br) + subdomainApp := s.extractSubdomainApp(r.Host) + if subdomainApp != "" { + if app, exists := s.manager.GetApp(subdomainApp); exists { + s.routeToApp(w, r, app, true) + return + } + } + + // 3. Roteamento por Subcaminho (ex: /page_teste/...) + pathParts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/") + appName := pathParts[0] + + // Redireciona /page_teste -> /page_teste/ para garantir que caminhos relativos de assets funcionem corretamente + if r.URL.Path == "/"+appName { + http.Redirect(w, r, "/"+appName+"/", http.StatusMovedPermanently) + return + } + + app, exists := s.manager.GetApp(appName) + if !exists { + s.handleNotFound(w, r, appName) + return + } + + s.routeToApp(w, r, app, false) +} + +func (s *Server) routeToApp(w http.ResponseWriter, r *http.Request, app *supervisor.AppInstance, isSubdomain bool) { + if app.Status == supervisor.StatusStarting { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Refresh", "2") + w.WriteHeader(http.StatusServiceUnavailable) + fmt.Fprintf(w, ` + + Iniciando... + + +

🚀 Aplicação '%s' está iniciando...

+

Aguarde um instante. Esta página será recarregada automaticamente.

+ + `, app.Name) + return + } + + if app.Status == supervisor.StatusCrashed { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprintf(w, ` + + App Crashed + + +

❌ O app '%s' encerrou inesperadamente (Crash)

+

Verifique se o binário está escutando na variável de ambiente PORT.

+

← Voltar ao Dashboard

+ + `, app.Name) + return + } + + proxy := s.getOrCreateProxy(app.Port, app.Name, isSubdomain) + proxy.ServeHTTP(w, r) +} + +func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) { + apps := s.manager.ListApps() + data := ui.DashboardData{ + Domain: s.cfg.Domain, + Port: s.cfg.Port, + AppsDir: s.cfg.AppsDir, + ActiveCount: len(apps), + Apps: apps, + } + + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if err := ui.RenderDashboard(w, data); err != nil { + http.Error(w, "Erro ao renderizar dashboard: "+err.Error(), http.StatusInternalServerError) + } +} + +func (s *Server) handleAPIApps(w http.ResponseWriter, r *http.Request) { + apps := s.manager.ListApps() + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(apps) +} + +func (s *Server) handleAPILogs(w http.ResponseWriter, r *http.Request) { + appName := r.URL.Query().Get("app") + if appName == "" { + http.Error(w, "Parâmetro 'app' é obrigatório", http.StatusBadRequest) + return + } + + logs, err := s.manager.GetRecentLogs(appName) + if err != nil { + http.Error(w, err.Error(), http.StatusNotFound) + return + } + + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + for _, line := range logs { + _, _ = w.Write([]byte(line)) + } +} + +func (s *Server) handleNotFound(w http.ResponseWriter, r *http.Request, appName string) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(http.StatusNotFound) + fmt.Fprintf(w, ` + + App Não Encontrado + + +

404 - Aplicação Não Encontrada

+

Não há nenhum binário ativo na pasta %s/%s.

+

← Ir para o Dashboard do Mini PaaS

+ + `, s.cfg.AppsDir, appName) +} + +func (s *Server) extractSubdomainApp(host string) string { + // Remove a porta se houver (ex: page-teste.paas.local:8080) + parts := strings.Split(host, ":") + hostname := parts[0] + + // Se for exatamente o domínio configurado ou localhost ou IP, não é subdomínio de app + if hostname == s.cfg.Domain || hostname == "localhost" || hostname == "127.0.0.1" { + return "" + } + + // Ex: app1.paas.weltonmoura.com.br -> extrai 'app1' + if strings.HasSuffix(hostname, "."+s.cfg.Domain) { + sub := strings.TrimSuffix(hostname, "."+s.cfg.Domain) + if !strings.Contains(sub, ".") { + return sub + } + } + + // Ex: app1.localhost -> extrai 'app1' + if strings.HasSuffix(hostname, ".localhost") { + sub := strings.TrimSuffix(hostname, ".localhost") + if !strings.Contains(sub, ".") { + return sub + } + } + + return "" +} diff --git a/internal/supervisor/supervisor.go b/internal/supervisor/supervisor.go new file mode 100644 index 0000000..739be6d --- /dev/null +++ b/internal/supervisor/supervisor.go @@ -0,0 +1,337 @@ +package supervisor + +import ( + "bufio" + "context" + "fmt" + "io" + "log" + "net" + "os" + "os/exec" + "path/filepath" + "runtime" + "sync" + "time" +) + +type AppStatus string + +const ( + StatusStarting AppStatus = "STARTING" + StatusRunning AppStatus = "RUNNING" + StatusCrashed AppStatus = "CRASHED" + StatusStopped AppStatus = "STOPPED" +) + +type AppInfo struct { + Name string `json:"name"` + Port int `json:"port"` + Status AppStatus `json:"status"` + PID int `json:"pid"` + StartedAt time.Time `json:"started_at"` + ModTime time.Time `json:"mod_time"` + BinaryPath string `json:"binary_path"` + CrashCount int `json:"crash_count"` + Uptime string `json:"uptime"` +} + +type AppInstance struct { + Name string + Dir string + BinaryPath string + ModTime time.Time + Port int + Status AppStatus + PID int + StartedAt time.Time + CrashCount int + LastCrash time.Time + LogFile string + + cmd *exec.Cmd + cancel context.CancelFunc + recentLogs []string + mu sync.RWMutex +} + +type Manager struct { + apps map[string]*AppInstance + usedPorts map[int]string + portStart int + portEnd int + mu sync.RWMutex + baseDir string + maxLogBuffer int +} + +func NewManager(portStart, portEnd int, baseDir string) *Manager { + return &Manager{ + apps: make(map[string]*AppInstance), + usedPorts: make(map[int]string), + portStart: portStart, + portEnd: portEnd, + baseDir: baseDir, + maxLogBuffer: 100, + } +} + +func (m *Manager) allocatePort(appName string) (int, error) { + for port := m.portStart; port <= m.portEnd; port++ { + if owner, ok := m.usedPorts[port]; !ok || owner == appName { + m.usedPorts[port] = appName + return port, nil + } + } + return 0, fmt.Errorf("nenhuma porta disponível no pool (%d - %d)", m.portStart, m.portEnd) +} + +func (m *Manager) releasePort(port int) { + delete(m.usedPorts, port) +} + +// StartOrRestart inicializa ou reinicia uma aplicação se o binário foi atualizado +func (m *Manager) StartOrRestart(appName, binaryPath string, modTime time.Time) error { + m.mu.Lock() + app, exists := m.apps[appName] + if exists { + // Se já existe e a data de modificação e caminho são iguais, e está rodando, não precisa reiniciar + if app.BinaryPath == binaryPath && app.ModTime.Equal(modTime) && app.Status == StatusRunning { + m.mu.Unlock() + return nil + } + // Se foi atualizado, para o anterior + m.mu.Unlock() + log.Printf("[Supervisor] Atualização detectada para o app '%s'. Reiniciando...", appName) + m.Stop(appName) + m.mu.Lock() + } + + port, err := m.allocatePort(appName) + if err != nil { + m.mu.Unlock() + return fmt.Errorf("falha ao alocar porta: %w", err) + } + + appDir := filepath.Dir(binaryPath) + logFile := filepath.Join(appDir, "app.log") + + app = &AppInstance{ + Name: appName, + Dir: appDir, + BinaryPath: binaryPath, + ModTime: modTime, + Port: port, + Status: StatusStarting, + LogFile: logFile, + recentLogs: make([]string, 0, m.maxLogBuffer), + } + m.apps[appName] = app + m.mu.Unlock() + + return m.launchProcess(app) +} + +func (m *Manager) launchProcess(app *AppInstance) error { + app.mu.Lock() + defer app.mu.Unlock() + + // Garante permissão de execução em sistemas Unix/Linux + if runtime.GOOS != "windows" { + _ = os.Chmod(app.BinaryPath, 0755) + } + + ctx, cancel := context.WithCancel(context.Background()) + app.cancel = cancel + + cmd := exec.CommandContext(ctx, app.BinaryPath) + cmd.Dir = app.Dir + + // Injeta variáveis de ambiente, especialmente PORT + cmd.Env = append(os.Environ(), + fmt.Sprintf("PORT=%d", app.Port), + fmt.Sprintf("APP_NAME=%s", app.Name), + fmt.Sprintf("APP_DIR=%s", app.Dir), + ) + + // Cria/Abre arquivo de log do app + logF, err := os.OpenFile(app.LogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) + if err != nil { + log.Printf("[Supervisor] Aviso: não foi possível abrir %s: %v", app.LogFile, err) + } + + stdoutPipe, _ := cmd.StdoutPipe() + stderrPipe, _ := cmd.StderrPipe() + + if err := cmd.Start(); err != nil { + app.Status = StatusCrashed + app.CrashCount++ + app.LastCrash = time.Now() + if logF != nil { + _ = logF.Close() + } + return fmt.Errorf("falha ao iniciar processo %s: %w", app.Name, err) + } + + app.cmd = cmd + app.PID = cmd.Process.Pid + app.StartedAt = time.Now() + app.Status = StatusStarting + + log.Printf("[Supervisor] App '%s' iniciado (PID: %d, Porta: %d)", app.Name, app.PID, app.Port) + + // Coleta logs em background + go m.streamLogs(app, io.MultiReader(stdoutPipe, stderrPipe), logF) + + // Monitora processo e aguarda porta abrir + go m.monitorApp(app, cmd) + + return nil +} + +func (m *Manager) streamLogs(app *AppInstance, r io.Reader, logF *os.File) { + scanner := bufio.NewScanner(r) + for scanner.Scan() { + line := scanner.Text() + timestamp := time.Now().Format("2006-01-02 15:04:05") + formatted := fmt.Sprintf("[%s] %s\n", timestamp, line) + + if logF != nil { + _, _ = logF.WriteString(formatted) + } + + app.mu.Lock() + if len(app.recentLogs) >= 100 { + app.recentLogs = app.recentLogs[1:] + } + app.recentLogs = append(app.recentLogs, formatted) + app.mu.Unlock() + } + if logF != nil { + _ = logF.Close() + } +} + +func (m *Manager) monitorApp(app *AppInstance, cmd *exec.Cmd) { + // Checa se a porta abriu (healthcheck inicial com timeout de até 5s) + ready := false + target := fmt.Sprintf("127.0.0.1:%d", app.Port) + for i := 0; i < 25; i++ { + time.Sleep(200 * time.Millisecond) + conn, err := net.DialTimeout("tcp", target, 150*time.Millisecond) + if err == nil { + _ = conn.Close() + ready = true + break + } + // Verifica se o processo morreu precocemente + if cmd.ProcessState != nil && cmd.ProcessState.Exited() { + break + } + } + + app.mu.Lock() + if ready { + app.Status = StatusRunning + log.Printf("[Supervisor] App '%s' está saudável e respondendo na porta %d", app.Name, app.Port) + } else if app.Status == StatusStarting { + // Pode ser que ainda esteja inicializando ou não escute TCP + app.Status = StatusRunning + } + app.mu.Unlock() + + // Aguarda término do processo + err := cmd.Wait() + + app.mu.Lock() + defer app.mu.Unlock() + + if app.Status != StatusStopped { + app.Status = StatusCrashed + app.CrashCount++ + app.LastCrash = time.Now() + log.Printf("[Supervisor] App '%s' encerrou inesperadamente: %v", app.Name, err) + } +} + +// Stop finaliza um app em execução +func (m *Manager) Stop(appName string) { + m.mu.Lock() + app, exists := m.apps[appName] + if !exists { + m.mu.Unlock() + return + } + m.releasePort(app.Port) + delete(m.apps, appName) + m.mu.Unlock() + + app.mu.Lock() + app.Status = StatusStopped + if app.cancel != nil { + app.cancel() + } + if app.cmd != nil && app.cmd.Process != nil { + _ = app.cmd.Process.Kill() + } + app.mu.Unlock() + + log.Printf("[Supervisor] App '%s' foi finalizado", appName) +} + +// GetApp retorna a instância do app +func (m *Manager) GetApp(appName string) (*AppInstance, bool) { + m.mu.RLock() + defer m.mu.RUnlock() + app, exists := m.apps[appName] + return app, exists +} + +// ListApps retorna a lista de apps registrados com seus status atuais +func (m *Manager) ListApps() []AppInfo { + m.mu.RLock() + defer m.mu.RUnlock() + + list := make([]AppInfo, 0, len(m.apps)) + now := time.Now() + + for _, app := range m.apps { + app.mu.RLock() + uptime := "-" + if app.Status == StatusRunning && !app.StartedAt.IsZero() { + uptime = now.Sub(app.StartedAt).Truncate(time.Second).String() + } + + list = append(list, AppInfo{ + Name: app.Name, + Port: app.Port, + Status: app.Status, + PID: app.PID, + StartedAt: app.StartedAt, + ModTime: app.ModTime, + BinaryPath: app.BinaryPath, + CrashCount: app.CrashCount, + Uptime: uptime, + }) + app.mu.RUnlock() + } + return list +} + +// GetRecentLogs retorna os últimos logs em memória +func (m *Manager) GetRecentLogs(appName string) ([]string, error) { + m.mu.RLock() + app, exists := m.apps[appName] + m.mu.RUnlock() + + if !exists { + return nil, fmt.Errorf("app '%s' não encontrado", appName) + } + + app.mu.RLock() + defer app.mu.RUnlock() + + logsCopy := make([]string, len(app.recentLogs)) + copy(logsCopy, app.recentLogs) + return logsCopy, nil +} diff --git a/internal/ui/dashboard.html b/internal/ui/dashboard.html new file mode 100644 index 0000000..cf4bf26 --- /dev/null +++ b/internal/ui/dashboard.html @@ -0,0 +1,474 @@ + + + + + + Mini PaaS Dashboard + + + + + + + +
+
+
+

Mini PaaS Go Engine

+
+
+ Host: {{.Domain}} +
+
+ +
+
+
Aplicações Ativas
+
{{.ActiveCount}}
+
+
+
Porta do PaaS
+
{{.Port}}
+
+
+
Diretório de Apps
+
{{.AppsDir}}
+
+
+ +
+ Aplicações Instaladas + +
+ +
+ {{if not .Apps}} +
+

Nenhum binário detectado em {{.AppsDir}}

+

Crie uma subpasta (ex: {{.AppsDir}}/page_teste) e coloque um binário Go lá dentro.

+
+ {{end}} + + {{range .Apps}} +
+
+
📦
+
+

{{.Name}}

+
+ Porta: :{{.Port}} + PID: {{.PID}} + Uptime: {{.Uptime}} +
+
+
+ +
+ {{if eq .Status "RUNNING"}} + RUNNING + {{else if eq .Status "STARTING"}} + STARTING + {{else}} + CRASHED ({{.CrashCount}}) + {{end}} + + + Acessar → +
+
+ {{end}} +
+ +
+

Como subir uma nova aplicação Go?

+

+ Compile seu binário para Linux 64-bit e coloque na pasta correspondente do volume no CasaOS: +

+
+# 1. Compilar para Linux +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o app main.go + +# 2. Criar a pasta do seu app dentro do volume do Mini PaaS +mkdir -p /DATA/AppData/mini-paas/apps/meu_app + +# 3. Copiar o binário 'app' para lá (o Mini PaaS detectará automaticamente em ~3s) +cp app /DATA/AppData/mini-paas/apps/meu_app/ +
+

+ Seu app deve escutar na variável de ambiente PORT: http.ListenAndServe(":" + os.Getenv("PORT"), nil). +

+
+
+ + + + + + + + diff --git a/internal/ui/ui.go b/internal/ui/ui.go new file mode 100644 index 0000000..9320d01 --- /dev/null +++ b/internal/ui/ui.go @@ -0,0 +1,24 @@ +package ui + +import ( + _ "embed" + "html/template" + "io" +) + +//go:embed dashboard.html +var dashboardHTML string + +var tmpl = template.Must(template.New("dashboard").Parse(dashboardHTML)) + +type DashboardData struct { + Domain string + Port string + AppsDir string + ActiveCount int + Apps any +} + +func RenderDashboard(w io.Writer, data DashboardData) error { + return tmpl.Execute(w, data) +} diff --git a/internal/watcher/watcher.go b/internal/watcher/watcher.go new file mode 100644 index 0000000..ecc76a9 --- /dev/null +++ b/internal/watcher/watcher.go @@ -0,0 +1,186 @@ +package watcher + +import ( + "bytes" + "io" + "log" + "os" + "path/filepath" + "runtime" + "strings" + "time" + + "mini-paas/internal/supervisor" +) + +type Watcher struct { + appsDir string + interval time.Duration + manager *supervisor.Manager + stopChan chan struct{} +} + +func NewWatcher(appsDir string, interval time.Duration, mgr *supervisor.Manager) *Watcher { + return &Watcher{ + appsDir: appsDir, + interval: interval, + manager: mgr, + stopChan: make(chan struct{}), + } +} + +func (w *Watcher) Start() { + // Cria a pasta de apps caso não exista + if err := os.MkdirAll(w.appsDir, 0755); err != nil { + log.Printf("[Watcher] Erro ao criar diretório de apps (%s): %v", w.appsDir, err) + } + + // Executa uma primeira checagem imediata + w.scan() + + go func() { + ticker := time.NewTicker(w.interval) + defer ticker.Stop() + + for { + select { + case <-ticker.C: + w.scan() + case <-w.stopChan: + return + } + } + }() +} + +func (w *Watcher) Stop() { + close(w.stopChan) +} + +func (w *Watcher) scan() { + entries, err := os.ReadDir(w.appsDir) + if err != nil { + log.Printf("[Watcher] Erro ao ler pasta de apps (%s): %v", w.appsDir, err) + return + } + + foundApps := make(map[string]bool) + + for _, entry := range entries { + if !entry.IsDir() { + continue + } + + appName := entry.Name() + // Ignora pastas ocultas (como .git ou .cache) + if strings.HasPrefix(appName, ".") { + continue + } + + appDirPath := filepath.Join(w.appsDir, appName) + binaryPath, modTime, ok := w.findExecutable(appDirPath, appName) + if ok { + foundApps[appName] = true + if err := w.manager.StartOrRestart(appName, binaryPath, modTime); err != nil { + log.Printf("[Watcher] Falha ao iniciar app '%s': %v", appName, err) + } + } + } + + // Remove apps que deixaram de existir no disco + for _, app := range w.manager.ListApps() { + if !foundApps[app.Name] { + log.Printf("[Watcher] App '%s' foi removido do disco. Parando...", app.Name) + w.manager.Stop(app.Name) + } + } +} + +// findExecutable procura um binário executável dentro do diretório do app +func (w *Watcher) findExecutable(dirPath, appName string) (string, time.Time, bool) { + files, err := os.ReadDir(dirPath) + if err != nil { + return "", time.Time{}, false + } + + // Lista de nomes preferenciais + preferredNames := []string{"app", "main", appName} + if runtime.GOOS == "windows" { + preferredNames = append(preferredNames, "app.exe", "main.exe", appName+".exe") + } + + // 1. Tenta encontrar pelo nome preferencial + for _, pref := range preferredNames { + for _, file := range files { + if !file.IsDir() && strings.EqualFold(file.Name(), pref) { + fullPath := filepath.Join(dirPath, file.Name()) + info, err := file.Info() + if err == nil { + return fullPath, info.ModTime(), true + } + } + } + } + + // 2. Se não encontrou por nome padrão, inspeciona arquivos executáveis ou binários + for _, file := range files { + if file.IsDir() { + continue + } + name := file.Name() + // Ignora arquivos comuns de texto, código fonte ou logs + lower := strings.ToLower(name) + if strings.HasSuffix(lower, ".go") || + strings.HasSuffix(lower, ".log") || + strings.HasSuffix(lower, ".txt") || + strings.HasSuffix(lower, ".md") || + strings.HasSuffix(lower, ".json") || + strings.HasSuffix(lower, ".yaml") || + strings.HasSuffix(lower, ".yml") || + strings.HasSuffix(lower, ".html") || + strings.HasSuffix(lower, ".css") || + strings.HasSuffix(lower, ".js") { + continue + } + + fullPath := filepath.Join(dirPath, file.Name()) + info, err := file.Info() + if err != nil { + continue + } + + // Checa se tem permissão de execução ou se é um binário ELF/PE (Windows) + if info.Mode()&0111 != 0 || isBinaryExecutable(fullPath) { + return fullPath, info.ModTime(), true + } + } + + return "", time.Time{}, false +} + +// isBinaryExecutable verifica se o arquivo possui cabeçalho de executável (ELF no Linux ou MZ no Windows) +func isBinaryExecutable(path string) bool { + f, err := os.Open(path) + if err != nil { + return false + } + defer f.Close() + + header := make([]byte, 4) + n, err := io.ReadFull(f, header) + if err != nil || n < 4 { + return false + } + + // ELF binary (Linux) magic bytes: 0x7F, 'E', 'L', 'F' + if bytes.Equal(header, []byte{0x7f, 'E', 'L', 'F'}) { + return true + } + + // Windows PE binary magic bytes: 'M', 'Z' + if header[0] == 'M' && header[1] == 'Z' { + return true + } + + return false +}