77 lines
2.4 KiB
Go
77 lines
2.4 KiB
Go
package handler
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
)
|
|
|
|
// Remove a specified VM from the inventory
|
|
func (h *Handler) VcCleanup(w http.ResponseWriter, r *http.Request) {
|
|
ctx := context.Background()
|
|
|
|
// Get the parameters
|
|
vcUrl := r.URL.Query().Get("vc_url")
|
|
if vcUrl != "" {
|
|
h.Logger.Debug("Checking inventory table for vCenter", "url", vcUrl)
|
|
_, err := h.Database.Queries().GetInventoryVcUrl(ctx, vcUrl)
|
|
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
h.Logger.Error("No VMs found for vcenter", "url", vcUrl)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
json.NewEncoder(w).Encode(map[string]string{
|
|
"status": "ERROR",
|
|
"message": fmt.Sprintf("No match to vcenter details specified. vc_url: '%s'", vcUrl),
|
|
})
|
|
return
|
|
} else {
|
|
h.Logger.Error("Error checking for vcenter to cleanup", "error", err, "url", vcUrl)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
json.NewEncoder(w).Encode(map[string]string{
|
|
"status": "ERROR",
|
|
"message": fmt.Sprintf("Error checking for vcenter to cleanup. error: '%s'", err),
|
|
})
|
|
return
|
|
}
|
|
} else {
|
|
// delete the VMs
|
|
err = h.Database.Queries().InventoryCleanupVcenter(ctx, vcUrl)
|
|
if err != nil {
|
|
h.Logger.Error("Error cleaning up VMs from Inventory table", "error", err, "url", vcUrl)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
json.NewEncoder(w).Encode(map[string]string{
|
|
"status": "ERROR",
|
|
"message": fmt.Sprintf("Error cleaning up VMs from Inventory table. error: '%s'", err),
|
|
})
|
|
return
|
|
} else {
|
|
// Successful cleanup
|
|
h.Logger.Debug("VMs successfully removed from inventory for vcenter", "url", vcUrl)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusOK)
|
|
json.NewEncoder(w).Encode(map[string]string{
|
|
"status": "OK",
|
|
"message": fmt.Sprintf("Removed VMs from Inventory table for vcenter '%s'", vcUrl),
|
|
})
|
|
return
|
|
}
|
|
}
|
|
} else {
|
|
h.Logger.Error("Parameters not correctly specified", "url", vcUrl)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
json.NewEncoder(w).Encode(map[string]string{
|
|
"status": "ERROR",
|
|
"message": fmt.Sprintf("Parameters not correctly specified. vc_url: '%s'", vcUrl),
|
|
})
|
|
return
|
|
}
|
|
}
|