Refactor code to use 'any' type and improve context handling
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
@@ -1,7 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -42,7 +41,7 @@ func (h *Handler) DailyCreationDiagnostics(w http.ResponseWriter, r *http.Reques
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
ctx, cancel := withRequestTimeout(r, 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dbConn := h.Database.DB()
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"vctp/internal/report"
|
||||
@@ -16,8 +15,8 @@ import (
|
||||
// @Failure 500 {object} models.ErrorResponse "Report generation failed"
|
||||
// @Router /api/report/inventory [get]
|
||||
func (h *Handler) InventoryReportDownload(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := withRequestTimeout(r, reportRequestTimeout)
|
||||
defer cancel()
|
||||
|
||||
// Generate the XLSX report
|
||||
reportData, err := report.CreateInventoryReport(h.Logger, h.Database, ctx)
|
||||
@@ -45,8 +44,8 @@ func (h *Handler) InventoryReportDownload(w http.ResponseWriter, r *http.Request
|
||||
// @Failure 500 {object} models.ErrorResponse "Report generation failed"
|
||||
// @Router /api/report/updates [get]
|
||||
func (h *Handler) UpdateReportDownload(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := withRequestTimeout(r, reportRequestTimeout)
|
||||
defer cancel()
|
||||
|
||||
// Generate the XLSX report
|
||||
reportData, err := report.CreateUpdatesReport(h.Logger, h.Database, ctx)
|
||||
|
||||
24
server/handler/request_context.go
Normal file
24
server/handler/request_context.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultRequestTimeout = 2 * time.Minute
|
||||
reportRequestTimeout = 10 * time.Minute
|
||||
longRunningRequestTimeout = 2 * time.Hour
|
||||
)
|
||||
|
||||
func withRequestTimeout(r *http.Request, timeout time.Duration) (context.Context, context.CancelFunc) {
|
||||
base := context.Background()
|
||||
if r != nil {
|
||||
base = r.Context()
|
||||
}
|
||||
if timeout <= 0 {
|
||||
return base, func() {}
|
||||
}
|
||||
return context.WithTimeout(base, timeout)
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -50,7 +49,8 @@ func (h *Handler) SnapshotAggregateForce(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := withRequestTimeout(r, longRunningRequestTimeout)
|
||||
defer cancel()
|
||||
settingsCopy := *h.Settings.Values
|
||||
if granularity != "" {
|
||||
settingsCopy.Settings.MonthlyAggregationGranularity = granularity
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -26,7 +25,8 @@ func (h *Handler) SnapshotForceHourly(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := withRequestTimeout(r, longRunningRequestTimeout)
|
||||
defer cancel()
|
||||
ct := &tasks.CronTask{
|
||||
Logger: h.Logger,
|
||||
Database: h.Database,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"vctp/internal/report"
|
||||
"vctp/server/models"
|
||||
@@ -16,7 +15,8 @@ import (
|
||||
// @Failure 500 {object} models.SnapshotMigrationResponse "Server error"
|
||||
// @Router /api/snapshots/migrate [post]
|
||||
func (h *Handler) SnapshotMigrate(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := context.Background()
|
||||
ctx, cancel := withRequestTimeout(r, reportRequestTimeout)
|
||||
defer cancel()
|
||||
stats, err := report.MigrateSnapshotRegistry(ctx, h.Database)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, models.SnapshotMigrationResponse{
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -58,7 +57,8 @@ func (h *Handler) SnapshotMonthlyList(w http.ResponseWriter, r *http.Request) {
|
||||
// @Failure 500 {object} models.ErrorResponse "Server error"
|
||||
// @Router /api/report/snapshot [get]
|
||||
func (h *Handler) SnapshotReportDownload(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := context.Background()
|
||||
ctx, cancel := withRequestTimeout(r, reportRequestTimeout)
|
||||
defer cancel()
|
||||
tableName := r.URL.Query().Get("table")
|
||||
if tableName == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Missing table parameter")
|
||||
@@ -80,7 +80,8 @@ func (h *Handler) SnapshotReportDownload(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
|
||||
func (h *Handler) renderSnapshotList(w http.ResponseWriter, r *http.Request, snapshotType string, title string, renderer func([]views.SnapshotEntry) templ.Component) {
|
||||
ctx := context.Background()
|
||||
ctx, cancel := withRequestTimeout(r, defaultRequestTimeout)
|
||||
defer cancel()
|
||||
if err := report.EnsureSnapshotRegistry(ctx, h.Database); err != nil {
|
||||
h.Logger.Error("Failed to ensure snapshot registry", "error", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
@@ -107,10 +108,7 @@ func (h *Handler) renderSnapshotList(w http.ResponseWriter, r *http.Request, sna
|
||||
case "monthly":
|
||||
group = record.SnapshotTime.Format("2006")
|
||||
}
|
||||
count := record.SnapshotCount
|
||||
if count < 0 {
|
||||
count = 0
|
||||
}
|
||||
count := max(record.SnapshotCount, 0)
|
||||
entries = append(entries, views.SnapshotEntry{
|
||||
Label: label,
|
||||
Link: "/reports/" + url.PathEscape(record.TableName) + ".xlsx",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
@@ -19,6 +18,8 @@ func (h *Handler) UpdateCleanup(w http.ResponseWriter, r *http.Request) {
|
||||
if h.denyLegacyAPI(w, "/api/cleanup/updates") {
|
||||
return
|
||||
}
|
||||
ctx, cancel := withRequestTimeout(r, defaultRequestTimeout)
|
||||
defer cancel()
|
||||
|
||||
/*
|
||||
// Get the current time
|
||||
@@ -35,11 +36,11 @@ func (h *Handler) UpdateCleanup(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
h.Logger.Debug("database params", "params", params)
|
||||
err := h.Database.Queries().CleanupUpdates(context.Background(), params)
|
||||
err := h.Database.Queries().CleanupUpdates(ctx, params)
|
||||
*/
|
||||
|
||||
//err := h.Database.Queries().InventoryCleanupTemplates(context.Background())
|
||||
err := h.Database.Queries().CleanupUpdatesNullVm(context.Background())
|
||||
//err := h.Database.Queries().InventoryCleanupTemplates(ctx)
|
||||
err := h.Database.Queries().CleanupUpdatesNullVm(ctx)
|
||||
|
||||
if err != nil {
|
||||
h.Logger.Error("Error received cleaning updates table", "error", err)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -23,7 +22,8 @@ func (h *Handler) VcCleanup(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := withRequestTimeout(r, defaultRequestTimeout)
|
||||
defer cancel()
|
||||
|
||||
// Get the parameters
|
||||
vcUrl := r.URL.Query().Get("vc_url")
|
||||
|
||||
@@ -108,7 +108,7 @@ func (h *Handler) rebuildOneVcenterCache(ctx context.Context, vcURL string) (int
|
||||
return 0, 0, 0, fmt.Errorf("unable to connect to vcenter: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
logoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
logoutCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := vc.Logout(logoutCtx); err != nil {
|
||||
h.Logger.Warn("vcenter cache rebuild logout failed", "vcenter", vcURL, "error", err)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -25,7 +24,8 @@ func (h *Handler) VmCleanup(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := withRequestTimeout(r, defaultRequestTimeout)
|
||||
defer cancel()
|
||||
|
||||
// Get the parameters
|
||||
vmId := r.URL.Query().Get("vm_id")
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -30,6 +29,8 @@ func (h *Handler) VmCreateEvent(w http.ResponseWriter, r *http.Request) {
|
||||
if h.denyLegacyAPI(w, "/api/event/vm/create") {
|
||||
return
|
||||
}
|
||||
ctx, cancel := withRequestTimeout(r, defaultRequestTimeout)
|
||||
defer cancel()
|
||||
|
||||
var (
|
||||
unixTimestamp int64
|
||||
@@ -96,7 +97,7 @@ func (h *Handler) VmCreateEvent(w http.ResponseWriter, r *http.Request) {
|
||||
h.Logger.Debug("database params", "params", params)
|
||||
|
||||
// Insert the new inventory record into the database
|
||||
result, err := h.Database.Queries().CreateEvent(context.Background(), params)
|
||||
result, err := h.Database.Queries().CreateEvent(ctx, params)
|
||||
if err != nil {
|
||||
h.Logger.Error("unable to perform database insert", "error", err)
|
||||
writeJSONError(w, http.StatusInternalServerError, fmt.Sprintf("Error: %v", err))
|
||||
@@ -109,7 +110,7 @@ func (h *Handler) VmCreateEvent(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// prettyPrint comes from https://gist.github.com/sfate/9d45f6c5405dc4c9bf63bf95fe6d1a7c
|
||||
func prettyPrint(args ...interface{}) {
|
||||
func prettyPrint(args ...any) {
|
||||
var caller string
|
||||
|
||||
timeNow := time.Now().Format("01-02-2006 15:04:05")
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -28,6 +27,8 @@ func (h *Handler) VmDeleteEvent(w http.ResponseWriter, r *http.Request) {
|
||||
if h.denyLegacyAPI(w, "/api/event/vm/delete") {
|
||||
return
|
||||
}
|
||||
ctx, cancel := withRequestTimeout(r, defaultRequestTimeout)
|
||||
defer cancel()
|
||||
|
||||
var (
|
||||
deletedTimestamp int64
|
||||
@@ -71,7 +72,7 @@ func (h *Handler) VmDeleteEvent(w http.ResponseWriter, r *http.Request) {
|
||||
DatacenterName: sql.NullString{String: event.CloudEvent.Data.Datacenter.Name, Valid: event.CloudEvent.Data.Datacenter.Name != ""},
|
||||
}
|
||||
h.Logger.Debug("database params", "params", params)
|
||||
err = h.Database.Queries().InventoryMarkDeleted(context.Background(), params)
|
||||
err = h.Database.Queries().InventoryMarkDeleted(ctx, params)
|
||||
|
||||
if err != nil {
|
||||
h.Logger.Error("Error received marking VM as deleted", "error", err)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -58,7 +57,8 @@ func (h *Handler) VmImport(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := withRequestTimeout(r, defaultRequestTimeout)
|
||||
defer cancel()
|
||||
|
||||
// Query Inventory table for this VM before adding it
|
||||
h.Logger.Debug("Checking inventory table for VM record")
|
||||
|
||||
@@ -41,7 +41,8 @@ func (h *Handler) VmModifyEvent(w http.ResponseWriter, r *http.Request) {
|
||||
var unixTimestamp int64
|
||||
|
||||
re := regexp.MustCompile(`/([^/]+)/[^/]+\.vmdk$`)
|
||||
ctx := context.Background()
|
||||
ctx, cancel := withRequestTimeout(r, defaultRequestTimeout)
|
||||
defer cancel()
|
||||
|
||||
reqBody, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
@@ -189,7 +190,7 @@ func (h *Handler) VmModifyEvent(w http.ResponseWriter, r *http.Request) {
|
||||
// If we found a disk change belonging to this VM then recalculate the disk size
|
||||
if diskChangeFound {
|
||||
params.UpdateType = "diskchange"
|
||||
diskSize := h.calculateNewDiskSize(event)
|
||||
diskSize := h.calculateNewDiskSize(ctx, event)
|
||||
params.NewProvisionedDisk = sql.NullFloat64{Float64: diskSize, Valid: diskSize > 0}
|
||||
}
|
||||
}
|
||||
@@ -333,7 +334,7 @@ func (h *Handler) processConfigChanges(configChanges string) []map[string]string
|
||||
return result
|
||||
}
|
||||
|
||||
func (h *Handler) calculateNewDiskSize(event models.CloudEventReceived) float64 {
|
||||
func (h *Handler) calculateNewDiskSize(ctx context.Context, event models.CloudEventReceived) float64 {
|
||||
var diskSize float64
|
||||
var totalDiskBytes int64
|
||||
h.Logger.Debug("connecting to vcenter")
|
||||
@@ -368,7 +369,9 @@ func (h *Handler) calculateNewDiskSize(event models.CloudEventReceived) float64
|
||||
}
|
||||
}
|
||||
|
||||
_ = vc.Logout(context.Background())
|
||||
logoutCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = vc.Logout(logoutCtx)
|
||||
|
||||
h.Logger.Debug("Calculated new disk size", "value", diskSize)
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -34,7 +33,8 @@ func (h *Handler) VmMoveEvent(w http.ResponseWriter, r *http.Request) {
|
||||
params := queries.CreateUpdateParams{}
|
||||
var unixTimestamp int64
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := withRequestTimeout(r, defaultRequestTimeout)
|
||||
defer cancel()
|
||||
|
||||
reqBody, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"vctp/db/queries"
|
||||
@@ -28,7 +27,8 @@ func (h *Handler) VmUpdateDetails(w http.ResponseWriter, r *http.Request) {
|
||||
var vmUuid string
|
||||
var dbUuid string
|
||||
|
||||
ctx := context.Background()
|
||||
ctx, cancel := withRequestTimeout(r, longRunningRequestTimeout)
|
||||
defer cancel()
|
||||
|
||||
// reload settings in case vcenter list has changed
|
||||
h.Settings.ReadYMLSettings()
|
||||
@@ -101,7 +101,7 @@ func (h *Handler) VmUpdateDetails(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
h.Logger.Debug("database params", "params", params)
|
||||
err := h.Database.Queries().InventoryUpdate(context.Background(), params)
|
||||
err := h.Database.Queries().InventoryUpdate(ctx, params)
|
||||
|
||||
if err != nil {
|
||||
h.Logger.Error("Error received updating inventory for VM", "name", vmObj.Name, "error", err)
|
||||
|
||||
@@ -31,9 +31,9 @@ type CloudEventReceived struct {
|
||||
} `json:"Datacenter"`
|
||||
Name string `json:"Name"`
|
||||
} `json:"Datacenter"`
|
||||
Ds interface{} `json:"Ds"`
|
||||
Dvs interface{} `json:"Dvs"`
|
||||
FullFormattedMessage string `json:"FullFormattedMessage"`
|
||||
Ds any `json:"Ds"`
|
||||
Dvs any `json:"Dvs"`
|
||||
FullFormattedMessage string `json:"FullFormattedMessage"`
|
||||
Host struct {
|
||||
Host struct {
|
||||
Type string `json:"Type"`
|
||||
@@ -42,7 +42,7 @@ type CloudEventReceived struct {
|
||||
Name string `json:"Name"`
|
||||
} `json:"Host"`
|
||||
Key int `json:"Key"`
|
||||
Net interface{} `json:"Net"`
|
||||
Net any `json:"Net"`
|
||||
NewParent *CloudEventResourcePool `json:"NewParent"`
|
||||
OldParent *CloudEventResourcePool `json:"OldParent"`
|
||||
SrcTemplate *CloudEventVm `json:"SrcTemplate"`
|
||||
@@ -158,7 +158,7 @@ type ConfigSpec struct {
|
||||
} `json:"StorageIOAllocation"`
|
||||
VDiskID any `json:"VDiskId"`
|
||||
VFlashCacheConfigInfo any `json:"VFlashCacheConfigInfo"`
|
||||
} `json:"Device,omitempty"`
|
||||
} `json:"Device"`
|
||||
FileOperation string `json:"FileOperation"`
|
||||
Operation string `json:"Operation"`
|
||||
Profile []struct {
|
||||
|
||||
Reference in New Issue
Block a user