package handler import ( "context" "database/sql" "encoding/json" "fmt" "io" "net/http" "regexp" "strconv" "strings" "time" "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{} var unixTimestamp int64 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) prettyPrint(reqBody) 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) w.WriteHeader(http.StatusAccepted) fmt.Fprintf(w, "Processed update event but no config changes were found\n") } 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} } } // Check if a disk was added (or maybe removed?) if strings.Contains(change["type"], "config.hardware.device") && strings.Contains(event.CloudEvent.Data.FullFormattedMessage, ".vmdk") { // TODO - recalculate total disk size h.Logger.Debug("Detected config change for VM disk") } } // Only create a database record if we found one of the config changes we were interested in if found { // lookup Iid from Inventory table for this VM // also figure out what to do if we didn't find an entry for this VM in the Inventory table. Create one? h.Logger.Debug("Checking inventory table for VM record") invParams := queries.GetInventoryVmIdParams{ VmId: sql.NullString{String: event.CloudEvent.Data.VM.VM.Value, Valid: event.CloudEvent.Data.VM.VM.Value != ""}, DatacenterName: sql.NullString{String: event.CloudEvent.Data.Datacenter.Name, Valid: event.CloudEvent.Data.Datacenter.Name != ""}, } invResult, err := h.Database.Queries().GetInventoryVmId(context.Background(), invParams) if err != nil { h.Logger.Error("unable to find existing inventory record for this VM", "error", err) // TODO - how to handle? } else { params.InventoryId = sql.NullInt64{Int64: invResult.Iid, Valid: invResult.Iid > 0} } // Parse the datetime string to a time.Time object eventTime, err := time.Parse(time.RFC3339, event.CloudEvent.Data.CreatedTime) if err != nil { h.Logger.Warn("unable to convert cloud event time to timestamp", "error", err) unixTimestamp = time.Now().Unix() } else { // Convert to Unix timestamp unixTimestamp = eventTime.Unix() } // populate other parameters for the Update database record params.EventId = sql.NullString{String: event.CloudEvent.ID, Valid: event.CloudEvent.ID != ""} params.EventKey = sql.NullString{String: strconv.Itoa(event.CloudEvent.Data.Key), Valid: event.CloudEvent.Data.Key > 0} params.UpdateTime = sql.NullInt64{Int64: unixTimestamp, Valid: unixTimestamp > 0} params.UpdateType = "reconfigure" // Create the Update database record 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, "Processed update event: %v\n", result) return } } else { w.WriteHeader(http.StatusAccepted) fmt.Fprintf(w, "Processed update event but no config changes were of interest\n") prettyPrint(configChanges) } } } 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[^\s]+): [^\s]+ -[><] (?P[^;]+);`) // 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 }