|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "net/http" |
| 6 | + |
| 7 | + "github.com/easy-cloud-Knet/KWS_Control/service" |
| 8 | + "github.com/easy-cloud-Knet/KWS_Control/structure" |
| 9 | + "github.com/easy-cloud-Knet/KWS_Control/util" |
| 10 | +) |
| 11 | + |
| 12 | +type ApiVmStatusRequest struct { |
| 13 | + UUID structure.UUID `json:"uuid"` |
| 14 | + Type string `json:"type"` // "cpu", "memory", or "disk" |
| 15 | +} |
| 16 | + |
| 17 | +func (c *handlerContext) vmStatus(w http.ResponseWriter, r *http.Request) { |
| 18 | + log := util.GetLogger() |
| 19 | + |
| 20 | + var req ApiVmStatusRequest |
| 21 | + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
| 22 | + http.Error(w, "Invalid request body", http.StatusBadRequest) |
| 23 | + log.Error("Failed to decode request body: %v", err, true) |
| 24 | + return |
| 25 | + } |
| 26 | + defer r.Body.Close() |
| 27 | + |
| 28 | + statusType := req.Type |
| 29 | + if statusType != "cpu" && statusType != "memory" && statusType != "disk" { |
| 30 | + http.Error(w, "Invalid status type. Must be 'cpu', 'memory', or 'disk'", http.StatusBadRequest) |
| 31 | + return |
| 32 | + } |
| 33 | + |
| 34 | + var data any |
| 35 | + var err error |
| 36 | + |
| 37 | + switch statusType { |
| 38 | + case "cpu": |
| 39 | + data, err = service.GetVMCpuInfo(req.UUID, c.context) |
| 40 | + case "memory": |
| 41 | + data, err = service.GetVMMemoryInfo(req.UUID, c.context) |
| 42 | + case "disk": |
| 43 | + data, err = service.GetVMDiskInfo(req.UUID, c.context) |
| 44 | + } |
| 45 | + |
| 46 | + if err != nil { |
| 47 | + http.Error(w, err.Error(), http.StatusInternalServerError) |
| 48 | + log.Error("Failed to get VM status: %v", err, true) |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + w.Header().Set("Content-Type", "application/json") |
| 53 | + if err := json.NewEncoder(w).Encode(data); err != nil { |
| 54 | + log.Error("Failed to encode response: %v", err, true) |
| 55 | + http.Error(w, "Failed to encode response", http.StatusInternalServerError) |
| 56 | + return |
| 57 | + } |
| 58 | +} |
0 commit comments