Improve server shutdown process

This commit is contained in:
2025-12-06 19:52:40 +01:00
parent 99927160c2
commit fa311c46ac
4 changed files with 20 additions and 7 deletions

1
.vscode/launch.json vendored
View File

@@ -14,6 +14,7 @@
"GO_ENV": "development", "GO_ENV": "development",
"LLAMACTL_CONFIG_PATH": "${workspaceFolder}/llamactl.dev.yaml" "LLAMACTL_CONFIG_PATH": "${workspaceFolder}/llamactl.dev.yaml"
}, },
"console": "integratedTerminal",
} }
] ]
} }

View File

@@ -1,6 +1,7 @@
package main package main
import ( import (
"context"
"fmt" "fmt"
"llamactl/pkg/config" "llamactl/pkg/config"
"llamactl/pkg/database" "llamactl/pkg/database"
@@ -11,6 +12,7 @@ import (
"os" "os"
"os/signal" "os/signal"
"syscall" "syscall"
"time"
) )
// version is set at build time using -ldflags "-X main.version=1.0.0" // version is set at build time using -ldflags "-X main.version=1.0.0"
@@ -116,14 +118,23 @@ func main() {
<-stop <-stop
fmt.Println("Shutting down server...") fmt.Println("Shutting down server...")
if err := server.Close(); err != nil { // Create shutdown context with timeout
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 30*time.Second)
defer shutdownCancel()
// Shutdown HTTP server gracefully
if err := server.Shutdown(shutdownCtx); err != nil {
log.Printf("Error shutting down server: %v\n", err) log.Printf("Error shutting down server: %v\n", err)
} else { } else {
fmt.Println("Server shut down gracefully.") fmt.Println("Server shut down gracefully.")
} }
// Wait for all instances to stop // Stop all instances and cleanup
instanceManager.Shutdown() instanceManager.Shutdown()
if err := db.Close(); err != nil {
log.Printf("Error closing database: %v\n", err)
}
fmt.Println("Exiting llamactl.") fmt.Println("Exiting llamactl.")
} }

View File

@@ -107,6 +107,12 @@ func Open(config *Config) (*sqliteDB, error) {
func (db *sqliteDB) Close() error { func (db *sqliteDB) Close() error {
if db.DB != nil { if db.DB != nil {
log.Println("Closing database connection") log.Println("Closing database connection")
// Checkpoint WAL to merge changes back to main database file
if _, err := db.DB.Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil {
log.Printf("Warning: Failed to checkpoint WAL: %v", err)
}
return db.DB.Close() return db.DB.Close()
} }
return nil return nil

View File

@@ -114,11 +114,6 @@ func (im *instanceManager) Shutdown() {
} }
wg.Wait() wg.Wait()
fmt.Println("All instances stopped.") fmt.Println("All instances stopped.")
// 4. Close database connection
if err := im.db.Close(); err != nil {
log.Printf("Error closing database: %v\n", err)
}
}) })
} }