feat: initial commit of mini-paas engine and documentation
This commit is contained in:
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
|
||||
}
|
||||
Reference in New Issue
Block a user