Files
vctp2/server/handler/vmModify.go
Nathan Coad afb85ff34a
Some checks are pending
continuous-integration/drone/push Build is passing
CI / Lint (push) Waiting to run
CI / Test (push) Waiting to run
CI / End-to-End (push) Waiting to run
CI / Publish Docker (push) Blocked by required conditions
more cleanup
2024-09-16 12:07:33 +10:00

127 lines
3.9 KiB
Go

package handler
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"io"
"net/http"
"regexp"
"strconv"
"strings"
"vctp/db/queries"
models "vctp/server/models"
)
// VmModify receives the CloudEvent for a VM modification or move
func (h *Handler) VmModify(w http.ResponseWriter, r *http.Request) {
var configChanges []map[string]string
params := queries.CreateUpdateParams{}
reqBody, err := io.ReadAll(r.Body)
if err != nil {
h.Logger.Error("Invalid data received", "error", err)
fmt.Fprintf(w, "Invalid data received")
w.WriteHeader(http.StatusInternalServerError)
return
} else {
h.Logger.Debug("received input data", "length", len(reqBody))
}
// Decode the JSON body into CloudEventReceived struct
var event models.CloudEventReceived
if err := json.Unmarshal(reqBody, &event); err != nil {
h.Logger.Error("unable to decode json", "error", err)
http.Error(w, "Invalid JSON body", http.StatusBadRequest)
return
} else {
h.Logger.Debug("successfully decoded JSON")
prettyPrint(event)
}
if event.CloudEvent.Data.ConfigChanges == nil {
h.Logger.Warn("Received event contains no config change")
prettyPrint(event)
} else {
h.Logger.Debug("Received event contains config change info")
configChanges = h.processConfigChanges(event.CloudEvent.Data.ConfigChanges.Modified)
prettyPrint(configChanges)
var found = false
// Only interested in vCPU or ram changes currently
for _, change := range configChanges {
//fmt.Printf("Type: %s, New Value: %s\n", change["type"], change["newValue"])
switch change["type"] {
case "config.hardware.numCPU":
i, err := strconv.ParseInt(change["newValue"], 10, 64)
if err != nil {
h.Logger.Error("Unable to convert new value to int64", "new_value", change["newValue"])
} else {
found = true
params.NewVcpus = sql.NullInt64{Int64: i, Valid: i > 0}
}
case "config.hardware.memoryMB":
i, err := strconv.ParseInt(change["newValue"], 10, 64)
if err != nil {
h.Logger.Error("Unable to convert new value to int64", "new_value", change["newValue"])
} else {
found = true
params.NewRam = sql.NullInt64{Int64: i, Valid: i > 0}
}
}
}
// Only create a database record if we found one of the config changes we were interested in
if found {
result, err := h.Database.Queries().CreateUpdate(context.Background(), params)
if err != nil {
h.Logger.Error("unable to perform database insert", "error", err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Error : %v\n", err)
return
} else {
h.Logger.Debug("created database record", "insert_result", result)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Update Request (%d): %v\n", len(reqBody), string(reqBody))
}
}
}
}
func (h *Handler) processConfigChanges(configChanges string) []map[string]string {
// Split the string on one or more consecutive newline characters
changes := regexp.MustCompile(`\n+`).Split(configChanges, -1)
// Regular expression to match config type and the new value after '->' or '<-'
re := regexp.MustCompile(`(?P<type>[^\s]+): [^\s]+ -[><] (?P<newValue>[^;]+);`)
// Result will hold a list of changes with type and new value
var result []map[string]string
for _, change := range changes {
// Trim any extra spaces and skip empty lines
change = strings.TrimSpace(change)
h.Logger.Debug("Processing config change element", "substring", change)
if change == "" {
continue
}
// Find the matches using the regex
match := re.FindStringSubmatch(change)
if len(match) > 0 {
// Create a map with 'type' and 'newValue'
changeMap := map[string]string{
"type": match[1], // config type
"newValue": match[2], // new value after -> or <-
}
h.Logger.Debug("Adding new entry to output", "map", changeMap)
result = append(result, changeMap)
} else {
h.Logger.Warn("No regex matches for string", "input", change)
}
}
return result
}