Files
mini-paas/internal/watcher/watcher.go

187 lines
4.2 KiB
Go

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
}