feat: initial commit of mini-paas engine and documentation
This commit is contained in:
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