feat: initial commit of mini-paas engine and documentation
This commit is contained in:
8
.dockerignore
Normal file
8
.dockerignore
Normal file
@@ -0,0 +1,8 @@
|
||||
.git
|
||||
.github
|
||||
apps/
|
||||
examples/
|
||||
*.log
|
||||
*.exe
|
||||
app
|
||||
paas-engine
|
||||
19
.gitignore
vendored
Normal file
19
.gitignore
vendored
Normal file
@@ -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/
|
||||
50
Dockerfile
Normal file
50
Dockerfile
Normal file
@@ -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"]
|
||||
374
GUIA_CRIACAO_APPS.md
Normal file
374
GUIA_CRIACAO_APPS.md
Normal file
@@ -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 `<a href="./contato">` 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, `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head><title>Meu App</title></head>
|
||||
<body style="font-family:sans-serif; padding:2rem;">
|
||||
<h1>Olá do Mini PaaS! 🚀</h1>
|
||||
<p>Esta página está rodando nativamente em Go.</p>
|
||||
<!-- Repare no link relativo com ./ -->
|
||||
<p><a href="./sobre">Ir para a página Sobre →</a></p>
|
||||
</body>
|
||||
</html>
|
||||
`)
|
||||
})
|
||||
|
||||
http.HandleFunc("/sobre", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
fmt.Fprintf(w, `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head><title>Sobre</title></head>
|
||||
<body style="font-family:sans-serif; padding:2rem;">
|
||||
<h1>Página Sobre</h1>
|
||||
<p><a href="./">← Voltar para a Home</a></p>
|
||||
</body>
|
||||
</html>
|
||||
`)
|
||||
})
|
||||
|
||||
// 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, `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<!-- Importando CSS relativo -->
|
||||
<link rel="stylesheet" href="./static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<h1>Página com CSS Embutido</h1>
|
||||
<button onclick="dizerOla()">Clique aqui</button>
|
||||
<script src="./static/script.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
`)
|
||||
})
|
||||
|
||||
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
|
||||
<!-- Ruim: A barra no início faz o navegador buscar na raiz do domínio principal! -->
|
||||
<a href="/sobre">Sobre</a> <!-- Vai para paas.weltonmoura.com.br/sobre (404) -->
|
||||
<link rel="stylesheet" href="/app.css"> <!-- Vai para paas.weltonmoura.com.br/app.css (404) -->
|
||||
```
|
||||
|
||||
### ✅ O que fazer:
|
||||
```html
|
||||
<!-- Bom: Caminho relativo mantém o usuário dentro do subcaminho do app! -->
|
||||
<a href="./sobre">Sobre</a> <!-- Vai para paas.weltonmoura.com.br/page_teste/sobre -->
|
||||
<a href="sobre">Sobre</a> <!-- Equivalente e funciona perfeitamente -->
|
||||
<link rel="stylesheet" href="./app.css">
|
||||
<script src="./js/main.js"></script>
|
||||
```
|
||||
|
||||
> **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/<nome_do_app>/app.log`.
|
||||
- Você pode visualizá-lo via SSH com:
|
||||
```bash
|
||||
tail -f /DATA/AppData/mini-paas/apps/<nome_do_app>/app.log
|
||||
```
|
||||
156
README.md
Normal file
156
README.md
Normal file
@@ -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: `<a href="./sobre">Sobre</a>` ou `<a href="sobre">Sobre</a>`
|
||||
* ✅ Correto: `<script src="./assets/app.js"></script>`
|
||||
* ❌ Evite: `<a href="/sobre">` (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/<nome_do_app>/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.
|
||||
77
cmd/paas/main.go
Normal file
77
cmd/paas/main.go
Normal file
@@ -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.")
|
||||
}
|
||||
43
docker-compose.yml
Normal file
43
docker-compose.yml
Normal file
@@ -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"
|
||||
13
examples/page_teste/build.ps1
Normal file
13
examples/page_teste/build.ps1
Normal file
@@ -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
|
||||
}
|
||||
10
examples/page_teste/build.sh
Normal file
10
examples/page_teste/build.sh
Normal file
@@ -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
|
||||
167
examples/page_teste/main.go
Normal file
167
examples/page_teste/main.go
Normal file
@@ -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, `
|
||||
<!DOCTYPE html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>App: %s</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
background: #0f172a;
|
||||
color: #f8fafc;
|
||||
padding: 2rem;
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.card {
|
||||
background: #1e293b;
|
||||
border: 1px solid #334155;
|
||||
border-radius: 12px;
|
||||
padding: 2rem;
|
||||
margin-top: 1.5rem;
|
||||
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
h1 { color: #38bdf8; margin-bottom: 0.5rem; }
|
||||
.badge {
|
||||
background: #0284c7;
|
||||
color: #fff;
|
||||
padding: 0.2rem 0.6rem;
|
||||
border-radius: 6px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: bold;
|
||||
}
|
||||
pre {
|
||||
background: #020617;
|
||||
padding: 1rem;
|
||||
border-radius: 8px;
|
||||
color: #a5f3fc;
|
||||
overflow-x: auto;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.nav {
|
||||
margin-top: 1.5rem;
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
}
|
||||
.nav a {
|
||||
color: #38bdf8;
|
||||
text-decoration: none;
|
||||
background: #0f172a;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 6px;
|
||||
border: 1px solid #334155;
|
||||
}
|
||||
.nav a:hover {
|
||||
background: #38bdf8;
|
||||
color: #0f172a;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>🚀 Olá! Eu sou o app '%s'</h1>
|
||||
<p>Esta página está sendo servida por um binário nativo em Go gerenciado pelo <strong>Mini PaaS</strong>.</p>
|
||||
|
||||
<p style="margin-top: 1rem;">
|
||||
Status: <span class="badge">Ativo & Saudável</span>
|
||||
• Requisições atendidas: <strong>%d</strong>
|
||||
</p>
|
||||
|
||||
<h3 style="margin-top: 1.5rem; margin-bottom: 0.5rem;">Informações do Ambiente:</h3>
|
||||
<pre>
|
||||
Porta interna alocada: :%s
|
||||
Hora atual do servidor: %s
|
||||
Host da requisição: %s
|
||||
X-Forwarded-Prefix: %s
|
||||
X-Forwarded-Host: %s
|
||||
</pre>
|
||||
|
||||
<div class="nav">
|
||||
<a href="./sobre">Ir para Página Sobre (Link Relativo)</a>
|
||||
<a href="./api/health">API Healthcheck (JSON)</a>
|
||||
<a href="/">Dashboard do PaaS</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`, 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, `
|
||||
<!DOCTYPE html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Sobre - %s</title>
|
||||
<style>
|
||||
body { font-family: sans-serif; background: #0f172a; color: #fff; padding: 2rem; max-width: 600px; margin: 0 auto; }
|
||||
.card { background: #1e293b; padding: 2rem; border-radius: 8px; border: 1px solid #334155; }
|
||||
a { color: #38bdf8; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h2>Página "Sobre" de Exemplo</h2>
|
||||
<p>Perceba que você navegou para <code>/sobre</code> usando um link relativo e continuou dentro do subcaminho do seu app!</p>
|
||||
<p style="margin-top: 1.5rem;"><a href="./">← Voltar para a página inicial do app</a></p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`, 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)
|
||||
}
|
||||
}
|
||||
67
internal/config/config.go
Normal file
67
internal/config/config.go
Normal file
@@ -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
|
||||
}
|
||||
254
internal/proxy/proxy.go
Normal file
254
internal/proxy/proxy.go
Normal file
@@ -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, `
|
||||
<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8"><title>Erro 502</title>
|
||||
<style>body{background:#090d16;color:#f3f4f6;font-family:sans-serif;padding:3rem;text-align:center;}</style></head>
|
||||
<body>
|
||||
<h1>502 Bad Gateway</h1>
|
||||
<p>Não foi possível conectar ao app <strong>%s</strong> na porta interna <strong>:%d</strong>.</p>
|
||||
<p><a href="/" style="color:#38bdf8;">Voltar ao Dashboard</a></p>
|
||||
</body></html>
|
||||
`, 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, `
|
||||
<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8"><title>Iniciando...</title>
|
||||
<style>body{background:#090d16;color:#f3f4f6;font-family:sans-serif;padding:3rem;text-align:center;}</style></head>
|
||||
<body>
|
||||
<h2>🚀 Aplicação '%s' está iniciando...</h2>
|
||||
<p>Aguarde um instante. Esta página será recarregada automaticamente.</p>
|
||||
</body></html>
|
||||
`, 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, `
|
||||
<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8"><title>App Crashed</title>
|
||||
<style>body{background:#090d16;color:#f3f4f6;font-family:sans-serif;padding:2rem;}pre{background:#111827;padding:1rem;border-radius:8px;color:#f87171;overflow:auto;}</style></head>
|
||||
<body>
|
||||
<h2>❌ O app '%s' encerrou inesperadamente (Crash)</h2>
|
||||
<p>Verifique se o binário está escutando na variável de ambiente <code>PORT</code>.</p>
|
||||
<p><a href="/" style="color:#38bdf8;">← Voltar ao Dashboard</a></p>
|
||||
</body></html>
|
||||
`, 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, `
|
||||
<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8"><title>App Não Encontrado</title>
|
||||
<style>body{background:#090d16;color:#f3f4f6;font-family:sans-serif;padding:3rem;text-align:center;}a{color:#38bdf8;}</style></head>
|
||||
<body>
|
||||
<h1>404 - Aplicação Não Encontrada</h1>
|
||||
<p>Não há nenhum binário ativo na pasta <code>%s/%s</code>.</p>
|
||||
<p style="margin-top:1.5rem;"><a href="/">← Ir para o Dashboard do Mini PaaS</a></p>
|
||||
</body></html>
|
||||
`, 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 ""
|
||||
}
|
||||
337
internal/supervisor/supervisor.go
Normal file
337
internal/supervisor/supervisor.go
Normal file
@@ -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
|
||||
}
|
||||
474
internal/ui/dashboard.html
Normal file
474
internal/ui/dashboard.html
Normal file
@@ -0,0 +1,474 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Mini PaaS Dashboard</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
:root {
|
||||
--bg-base: #090d16;
|
||||
--bg-card: #111827;
|
||||
--bg-card-hover: #172033;
|
||||
--border: #1f293d;
|
||||
--text-main: #f3f4f6;
|
||||
--text-muted: #9ca3af;
|
||||
--primary: #3b82f6;
|
||||
--primary-glow: rgba(59, 130, 246, 0.2);
|
||||
--success: #10b981;
|
||||
--warning: #f59e0b;
|
||||
--danger: #ef4444;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Plus Jakarta Sans', sans-serif;
|
||||
background-color: var(--bg-base);
|
||||
color: var(--text-main);
|
||||
min-height: 100vh;
|
||||
padding: 2.5rem 1.5rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 1000px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 2.5rem;
|
||||
padding-bottom: 1.5rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.logo-area h1 {
|
||||
font-size: 1.75rem;
|
||||
font-weight: 700;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.logo-badge {
|
||||
background: linear-gradient(135deg, #2563eb, #3b82f6);
|
||||
color: white;
|
||||
font-size: 0.75rem;
|
||||
padding: 0.2rem 0.6rem;
|
||||
border-radius: 9999px;
|
||||
text-transform: uppercase;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.header-meta {
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-muted);
|
||||
background: #131c2e;
|
||||
padding: 0.4rem 0.8rem;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 1rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 1.25rem;
|
||||
}
|
||||
|
||||
.stat-title {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
margin-bottom: 0.35rem;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 1.75rem;
|
||||
font-weight: 700;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: 1.15rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 1rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.apps-list {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
margin-bottom: 2.5rem;
|
||||
}
|
||||
|
||||
.app-card {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 1.25rem 1.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.app-card:hover {
|
||||
border-color: #2b3952;
|
||||
background: var(--bg-card-hover);
|
||||
}
|
||||
|
||||
.app-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.app-icon {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 10px;
|
||||
background: #1e293b;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.app-details h3 {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.2rem;
|
||||
}
|
||||
|
||||
.app-meta {
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.badge {
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 0.72rem;
|
||||
padding: 0.25rem 0.6rem;
|
||||
border-radius: 9999px;
|
||||
font-weight: 600;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.badge-running {
|
||||
background: rgba(16, 185, 129, 0.15);
|
||||
color: #34d399;
|
||||
border: 1px solid rgba(16, 185, 129, 0.3);
|
||||
}
|
||||
.badge-running::before {
|
||||
content: '';
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
background: #34d399;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 0 6px #34d399;
|
||||
}
|
||||
|
||||
.badge-starting {
|
||||
background: rgba(245, 158, 11, 0.15);
|
||||
color: #fbbf24;
|
||||
border: 1px solid rgba(245, 158, 11, 0.3);
|
||||
}
|
||||
|
||||
.badge-crashed {
|
||||
background: rgba(239, 68, 68, 0.15);
|
||||
color: #f87171;
|
||||
border: 1px solid rgba(239, 68, 68, 0.3);
|
||||
}
|
||||
|
||||
.app-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 8px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
}
|
||||
.btn-primary:hover {
|
||||
background: #2563eb;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #1e293b;
|
||||
color: var(--text-main);
|
||||
border-color: var(--border);
|
||||
}
|
||||
.btn-secondary:hover {
|
||||
background: #283548;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 3.5rem 1.5rem;
|
||||
background: var(--bg-card);
|
||||
border: 1px dashed var(--border);
|
||||
border-radius: 12px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.guide-box {
|
||||
background: #0d131f;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 1.5rem;
|
||||
}
|
||||
|
||||
.guide-box h4 {
|
||||
font-size: 0.95rem;
|
||||
margin-bottom: 0.75rem;
|
||||
color: #93c5fd;
|
||||
}
|
||||
|
||||
.guide-code {
|
||||
background: #06090e;
|
||||
padding: 0.85rem 1rem;
|
||||
border-radius: 6px;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 0.82rem;
|
||||
color: #e2e8f0;
|
||||
overflow-x: auto;
|
||||
margin-bottom: 0.75rem;
|
||||
border: 1px solid #1a2233;
|
||||
}
|
||||
|
||||
/* Modal Logs */
|
||||
.modal-backdrop {
|
||||
display: none;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.75);
|
||||
backdrop-filter: blur(4px);
|
||||
z-index: 999;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.modal {
|
||||
background: #0d131f;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
width: 90%;
|
||||
max-width: 800px;
|
||||
max-height: 80vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
padding: 1rem 1.5rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.modal-header h3 {
|
||||
font-size: 1.1rem;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
font-size: 1.5rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.modal-body {
|
||||
padding: 1rem;
|
||||
overflow-y: auto;
|
||||
background: #06090e;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 0.8rem;
|
||||
color: #38bdf8;
|
||||
flex: 1;
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.4;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="container">
|
||||
<header>
|
||||
<div class="logo-area">
|
||||
<h1>Mini PaaS <span class="logo-badge">Go Engine</span></h1>
|
||||
</div>
|
||||
<div class="header-meta">
|
||||
Host: <strong>{{.Domain}}</strong>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="stats-grid">
|
||||
<div class="stat-card">
|
||||
<div class="stat-title">Aplicações Ativas</div>
|
||||
<div class="stat-value" style="color: var(--success)">{{.ActiveCount}}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-title">Porta do PaaS</div>
|
||||
<div class="stat-value">{{.Port}}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-title">Diretório de Apps</div>
|
||||
<div class="stat-value" style="font-size: 1rem; padding-top: 0.5rem; word-break: break-all;">{{.AppsDir}}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-title">
|
||||
<span>Aplicações Instaladas</span>
|
||||
<button onclick="location.reload()" class="btn btn-secondary" style="font-size: 0.75rem; padding: 0.35rem 0.75rem;">Atualizar</button>
|
||||
</div>
|
||||
|
||||
<div class="apps-list">
|
||||
{{if not .Apps}}
|
||||
<div class="empty-state">
|
||||
<p style="font-size: 1.1rem; margin-bottom: 0.5rem; color: #fff;">Nenhum binário detectado em <code>{{.AppsDir}}</code></p>
|
||||
<p>Crie uma subpasta (ex: <code>{{.AppsDir}}/page_teste</code>) e coloque um binário Go lá dentro.</p>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
{{range .Apps}}
|
||||
<div class="app-card">
|
||||
<div class="app-info">
|
||||
<div class="app-icon">📦</div>
|
||||
<div class="app-details">
|
||||
<h3>{{.Name}}</h3>
|
||||
<div class="app-meta">
|
||||
<span>Porta: <strong>:{{.Port}}</strong></span>
|
||||
<span>PID: <strong>{{.PID}}</strong></span>
|
||||
<span>Uptime: <strong>{{.Uptime}}</strong></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="app-actions">
|
||||
{{if eq .Status "RUNNING"}}
|
||||
<span class="badge badge-running">RUNNING</span>
|
||||
{{else if eq .Status "STARTING"}}
|
||||
<span class="badge badge-starting">STARTING</span>
|
||||
{{else}}
|
||||
<span class="badge badge-crashed">CRASHED ({{.CrashCount}})</span>
|
||||
{{end}}
|
||||
|
||||
<button onclick="viewLogs('{{.Name}}')" class="btn btn-secondary">Logs</button>
|
||||
<a href="/{{.Name}}/" class="btn btn-primary" target="_blank">Acessar →</a>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
|
||||
<div class="guide-box">
|
||||
<h4>Como subir uma nova aplicação Go?</h4>
|
||||
<p style="font-size: 0.85rem; color: var(--text-muted); margin-bottom: 0.75rem;">
|
||||
Compile seu binário para Linux 64-bit e coloque na pasta correspondente do volume no CasaOS:
|
||||
</p>
|
||||
<div class="guide-code">
|
||||
# 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/
|
||||
</div>
|
||||
<p style="font-size: 0.82rem; color: var(--text-muted);">
|
||||
Seu app deve escutar na variável de ambiente <code>PORT</code>: <code>http.ListenAndServe(":" + os.Getenv("PORT"), nil)</code>.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Logs -->
|
||||
<div id="modalLogs" class="modal-backdrop">
|
||||
<div class="modal">
|
||||
<div class="modal-header">
|
||||
<h3 id="modalAppName">Logs da Aplicação</h3>
|
||||
<button class="close-btn" onclick="closeLogs()">×</button>
|
||||
</div>
|
||||
<pre id="modalLogsContent" class="modal-body">Carregando logs...</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function viewLogs(appName) {
|
||||
document.getElementById('modalAppName').innerText = 'Logs: ' + appName;
|
||||
document.getElementById('modalLogsContent').innerText = 'Carregando logs...';
|
||||
document.getElementById('modalLogs').style.display = 'flex';
|
||||
|
||||
fetch('/_paas/api/logs?app=' + encodeURIComponent(appName))
|
||||
.then(res => res.text())
|
||||
.then(data => {
|
||||
document.getElementById('modalLogsContent').innerText = data || '(Nenhum log registrado ainda)';
|
||||
})
|
||||
.catch(err => {
|
||||
document.getElementById('modalLogsContent').innerText = 'Erro ao carregar logs: ' + err;
|
||||
});
|
||||
}
|
||||
|
||||
function closeLogs() {
|
||||
document.getElementById('modalLogs').style.display = 'none';
|
||||
}
|
||||
|
||||
window.onclick = function(event) {
|
||||
const modal = document.getElementById('modalLogs');
|
||||
if (event.target === modal) {
|
||||
closeLogs();
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
24
internal/ui/ui.go
Normal file
24
internal/ui/ui.go
Normal file
@@ -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)
|
||||
}
|
||||
186
internal/watcher/watcher.go
Normal file
186
internal/watcher/watcher.go
Normal file
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user