Procházet zdrojové kódy

fix(panic): Handle case where key "default" doesn't exist

There is a scenario on bootup where the app can crash due to a panic.
An easy way to replicate the panic is to not set `CONFIG_PATH`.
This change will handle this scenario better and set the cpu, memory and
gpu prices to "0.0".

Signed-off-by: pokom <mark.poko@grafana.com>
pokom před 3 roky
rodič
revize
9eeeae4112
1 změnil soubory, kde provedl 19 přidání a 4 odebrání
  1. 19 4
      pkg/cloud/customprovider.go

+ 19 - 4
pkg/cloud/customprovider.go

@@ -3,7 +3,6 @@ package cloud
 import (
 import (
 	"errors"
 	"errors"
 	"fmt"
 	"fmt"
-	"github.com/opencost/opencost/pkg/kubecost"
 	"io"
 	"io"
 	"strconv"
 	"strconv"
 	"sync"
 	"sync"
@@ -11,6 +10,8 @@ import (
 
 
 	"github.com/opencost/opencost/pkg/clustercache"
 	"github.com/opencost/opencost/pkg/clustercache"
 	"github.com/opencost/opencost/pkg/env"
 	"github.com/opencost/opencost/pkg/env"
+	"github.com/opencost/opencost/pkg/kubecost"
+	"github.com/opencost/opencost/pkg/log"
 	"github.com/opencost/opencost/pkg/util/json"
 	"github.com/opencost/opencost/pkg/util/json"
 
 
 	v1 "k8s.io/api/core/v1"
 	v1 "k8s.io/api/core/v1"
@@ -139,6 +140,8 @@ func (cp *CustomProvider) NodePricing(key Key) (*Node, error) {
 	k := key.Features()
 	k := key.Features()
 	var gpuCount string
 	var gpuCount string
 	if _, ok := cp.Pricing[k]; !ok {
 	if _, ok := cp.Pricing[k]; !ok {
+		// Default is saying that there is no pricing info for the cluster and we should fall back to the defualt values.
+		// An interesting case is if the default values weren't loaded.
 		k = "default"
 		k = "default"
 	}
 	}
 	if key.GPUType() != "" {
 	if key.GPUType() != "" {
@@ -146,10 +149,22 @@ func (cp *CustomProvider) NodePricing(key Key) (*Node, error) {
 		gpuCount = "1" // TODO: support more than one gpu.
 		gpuCount = "1" // TODO: support more than one gpu.
 	}
 	}
 
 
+	var cpuCost, ramCost, gpuCost string
+	if pricing, ok := cp.Pricing[k]; !ok {
+		log.Warnf("No pricing found for key=%s, setting values to 0", k)
+		cpuCost = "0.0"
+		ramCost = "0.0"
+		gpuCost = "0.0"
+	} else {
+		cpuCost = pricing.CPU
+		ramCost = pricing.RAM
+		gpuCost = pricing.GPU
+	}
+
 	return &Node{
 	return &Node{
-		VCPUCost: cp.Pricing[k].CPU,
-		RAMCost:  cp.Pricing[k].RAM,
-		GPUCost:  cp.Pricing[k].GPU,
+		VCPUCost: cpuCost,
+		RAMCost:  ramCost,
+		GPUCost:  gpuCost,
 		GPU:      gpuCount,
 		GPU:      gpuCount,
 	}, nil
 	}, nil
 }
 }