250 lines
6.9 KiB
Go
250 lines
6.9 KiB
Go
package routes
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
func (rt *Router) CreateSimulation(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
|
|
bodyBytes, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
http.Error(w, "Failed to read request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
defer r.Body.Close()
|
|
configStr := string(bodyBytes)
|
|
|
|
if configStr == "" {
|
|
http.Error(w, "Config cannot be empty", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
hasPattern := false
|
|
var jsonParsed map[string]interface{}
|
|
err = json.Unmarshal(bodyBytes, &jsonParsed)
|
|
if err != nil {
|
|
http.Error(w, "Invalid configuration format: must be valid JSON", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
for k, v := range jsonParsed {
|
|
if k == "search.yaml" || k == "search" {
|
|
if searchMap, ok := v.(map[string]interface{}); ok {
|
|
if _, ok := searchMap["spiral"]; ok {
|
|
hasPattern = true
|
|
}
|
|
if _, ok := searchMap["lawnmower"]; ok {
|
|
hasPattern = true
|
|
}
|
|
if _, ok := searchMap["levy"]; ok {
|
|
hasPattern = true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if !hasPattern {
|
|
http.Error(w, "Simulation configuration must include a search pattern (spiral, lawnmower, or levy)", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
|
|
|
|
var count int
|
|
rt.DB.QueryRow("SELECT COUNT(*) FROM simulations").Scan(&count)
|
|
newName := fmt.Sprintf("simulation_%d", count+1)
|
|
|
|
for {
|
|
var temp int
|
|
err := rt.DB.QueryRow("SELECT id FROM simulations WHERE name = ?", newName).Scan(&temp)
|
|
if err == sql.ErrNoRows {
|
|
break
|
|
}
|
|
count++
|
|
newName = fmt.Sprintf("simulation_%d", count+1)
|
|
}
|
|
|
|
res, err := rt.DB.Exec("INSERT INTO simulations(name, config) VALUES(?, ?)", newName, configStr)
|
|
if err != nil {
|
|
log.Println("Insert simulation error:", err)
|
|
http.Error(w, "Failed to create", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
newID, _ := res.LastInsertId()
|
|
|
|
resultsDir := filepath.Join("../results", newName)
|
|
os.MkdirAll(resultsDir, 0755)
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
|
"id": newID,
|
|
"name": newName,
|
|
})
|
|
}
|
|
|
|
func (rt *Router) GetSimulations(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
|
|
rows, err := rt.DB.Query("SELECT id, name, config, created_at, search_time, total_time, cpu_info, gpu_info, ram_info FROM simulations")
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
|
|
var sims []Simulation
|
|
for rows.Next() {
|
|
var s Simulation
|
|
err = rows.Scan(&s.ID, &s.Name, &s.Config, &s.CreatedAt, &s.SearchTime, &s.TotalTime, &s.CPUInfo, &s.GPUInfo, &s.RAMInfo)
|
|
if err != nil {
|
|
log.Println("Row scan error:", err)
|
|
continue
|
|
}
|
|
sims = append(sims, s)
|
|
}
|
|
|
|
if sims == nil {
|
|
sims = []Simulation{}
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(sims)
|
|
}
|
|
|
|
func (rt *Router) GetSimulationDetails(w http.ResponseWriter, r *http.Request, idStr string) {
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
|
|
var s Simulation
|
|
err := rt.DB.QueryRow("SELECT id, name, config, created_at, search_time, total_time, cpu_info, gpu_info, ram_info FROM simulations WHERE id = ?", idStr).Scan(&s.ID, &s.Name, &s.Config, &s.CreatedAt, &s.SearchTime, &s.TotalTime, &s.CPUInfo, &s.GPUInfo, &s.RAMInfo)
|
|
if err != nil {
|
|
if err == sql.ErrNoRows {
|
|
http.Error(w, "Simulation not found", http.StatusNotFound)
|
|
} else {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
}
|
|
return
|
|
}
|
|
|
|
rows, err := rt.DB.Query("SELECT filename FROM resources WHERE simulation_id = ?", s.ID)
|
|
if err == nil {
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var fname string
|
|
if err := rows.Scan(&fname); err == nil {
|
|
s.Resources = append(s.Resources, fname)
|
|
if stat, err := os.Stat(filepath.Join("../results", s.Name, fname)); err == nil {
|
|
s.TotalSizeBytes += stat.Size()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if s.Resources == nil {
|
|
s.Resources = []string{}
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(s)
|
|
}
|
|
|
|
func (rt *Router) RenameSimulation(w http.ResponseWriter, r *http.Request, idStr string) {
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
|
|
var reqBody struct {
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
err := json.NewDecoder(r.Body).Decode(&reqBody)
|
|
if err != nil || strings.TrimSpace(reqBody.Name) == "" {
|
|
http.Error(w, "Invalid request body or missing name", http.StatusBadRequest)
|
|
return
|
|
}
|
|
defer r.Body.Close()
|
|
|
|
newName := strings.TrimSpace(reqBody.Name)
|
|
|
|
var oldName string
|
|
err = rt.DB.QueryRow("SELECT name FROM simulations WHERE id = ?", idStr).Scan(&oldName)
|
|
if err != nil {
|
|
http.Error(w, "Simulation not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
var tempID int
|
|
err = rt.DB.QueryRow("SELECT id FROM simulations WHERE name = ?", newName).Scan(&tempID)
|
|
if err == nil {
|
|
http.Error(w, "A simulation with that name already exists", http.StatusConflict)
|
|
return
|
|
}
|
|
|
|
oldDirPath := filepath.Join("../results", oldName)
|
|
newDirPath := filepath.Join("../results", newName)
|
|
if _, statErr := os.Stat(oldDirPath); statErr == nil {
|
|
err = os.Rename(oldDirPath, newDirPath)
|
|
if err != nil {
|
|
log.Println("Error renaming directory:", err)
|
|
http.Error(w, "Failed to rename results directory", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
} else {
|
|
os.MkdirAll(newDirPath, 0755)
|
|
}
|
|
|
|
_, err = rt.DB.Exec("UPDATE simulations SET name = ? WHERE id = ?", newName, idStr)
|
|
if err != nil {
|
|
os.Rename(newDirPath, oldDirPath)
|
|
log.Println("Update simulation name error:", err)
|
|
http.Error(w, "Failed to update database", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]string{"status": "success", "new_name": newName})
|
|
}
|
|
|
|
func (rt *Router) DeleteSimulation(w http.ResponseWriter, r *http.Request, idStr string) {
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
|
|
var name string
|
|
err := rt.DB.QueryRow("SELECT name FROM simulations WHERE id = ?", idStr).Scan(&name)
|
|
if err != nil {
|
|
if err == sql.ErrNoRows {
|
|
http.Error(w, "Simulation not found", http.StatusNotFound)
|
|
} else {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
}
|
|
return
|
|
}
|
|
|
|
_, err = rt.DB.Exec("DELETE FROM resources WHERE simulation_id = ?", idStr)
|
|
if err != nil {
|
|
log.Println("Warning: Error deleting resources map from DB:", err)
|
|
}
|
|
|
|
_, err = rt.DB.Exec("DELETE FROM simulations WHERE id = ?", idStr)
|
|
if err != nil {
|
|
log.Println("Error deleting simulation from DB:", err)
|
|
http.Error(w, "Failed to delete from database", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
dirPath := filepath.Join("../results", name)
|
|
if _, statErr := os.Stat(dirPath); statErr == nil {
|
|
err = os.RemoveAll(dirPath)
|
|
if err != nil {
|
|
log.Println("Warning: Failed fully deleting physical directory items:", err)
|
|
}
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]string{"status": "success"})
|
|
}
|