Sfoglia il codice sorgente

don't panic when prometheus data is empty

Signed-off-by: r2k1 <yokree@gmail.com>
r2k1 3 anni fa
parent
commit
e9e1054891
2 ha cambiato i file con 14 aggiunte e 2 eliminazioni
  1. 7 1
      pkg/cmd/costmodel/costmodel.go
  2. 7 1
      pkg/costmodel/allocation.go

+ 7 - 1
pkg/cmd/costmodel/costmodel.go

@@ -49,7 +49,6 @@ func Execute(opts *CostModelOpts) error {
 }
 
 func StartExportWorker(ctx context.Context, model costmodel.AllocationModel) {
-	// TODO: there should be a better way to load the configuration
 	exportPath := os.Getenv(env.ExportCSVFile)
 	if exportPath == "" {
 		log.Infof("%s is not set, skipping CSV exporter", env.ExportCSVFile)
@@ -62,6 +61,13 @@ func StartExportWorker(ctx context.Context, model costmodel.AllocationModel) {
 		return
 	}
 	go func() {
+		// panic in a goroutine will crash the application. Log it and carry on.
+		defer func() {
+			if r := recover(); r != nil {
+				log.Errorf("panic in CSV Export Worker, stopping: %v", r)
+			}
+		}()
+
 		log.Info("Starting CSV exporter worker...")
 
 		// perform first update immediately

+ 7 - 1
pkg/costmodel/allocation.go

@@ -290,11 +290,17 @@ func (cm *CostModel) DateRange() (time.Time, time.Time, error) {
 	if err != nil {
 		return time.Time{}, time.Time{}, fmt.Errorf("querying oldest sample: %w", err)
 	}
+	if len(resOldest) == 0 || len(resOldest[0].Values) == 0 {
+		return time.Time{}, time.Time{}, fmt.Errorf("querying oldest sample: no results")
+	}
 	oldest := time.Unix(int64(resOldest[0].Values[0].Value), 0)
 
 	resNewest, _, err := ctx.QuerySync(fmt.Sprintf(queryFmtNewestSample, "90d", "1h"))
 	if err != nil {
-		return time.Time{}, time.Time{}, fmt.Errorf("querying oldest sample: %w", err)
+		return time.Time{}, time.Time{}, fmt.Errorf("querying newest sample: %w", err)
+	}
+	if len(resNewest) == 0 || len(resNewest[0].Values) == 0 {
+		return time.Time{}, time.Time{}, fmt.Errorf("querying newest sample: no results")
 	}
 	newest := time.Unix(int64(resNewest[0].Values[0].Value), 0)