Просмотр исходного кода

Avoid nil panic on non-GKE GCP clusters

A user running K3s on GCP is encountering a nil panic
caused by our parsing logic for the node.kubernetes.io/instance-type
label. On GCP, we expect GCP node type formats (xx-xx-xx) with
two dashes. The K3s cluster sets this value as just "k3s" in the
user's cluster.

By adding a guard on the length of the parsed result we avoid the panic.
Michael Dresser 4 лет назад
Родитель
Сommit
e45fa86e40
1 измененных файлов с 19 добавлено и 9 удалено
  1. 19 9
      pkg/cloud/gcpprovider.go

+ 19 - 9
pkg/cloud/gcpprovider.go

@@ -1403,15 +1403,25 @@ func (gcp *gcpKey) Features() string {
 		log.DedupedErrorf(1, "Missing or Unknown 'node.kubernetes.io/instance-type' node label")
 		instanceType = "unknown"
 	} else {
-		instanceType = strings.ToLower(strings.Join(strings.Split(it, "-")[:2], ""))
-		if instanceType == "n1highmem" || instanceType == "n1highcpu" {
-			instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
-		} else if instanceType == "n2highmem" || instanceType == "n2highcpu" {
-			instanceType = "n2standard"
-		} else if instanceType == "e2highmem" || instanceType == "e2highcpu" {
-			instanceType = "e2standard"
-		} else if strings.HasPrefix(instanceType, "custom") {
-			instanceType = "custom" // The suffix of custom does not matter
+		splitByDash := strings.Split(it, "-")
+
+		// GKE nodes are labeled with the GCP instance type, but users can deploy on GCP
+		// with tools like K3s, whose instance type labels will be "k3s". This logic
+		// avoids a panic in the slice operation then there are no dashes (-) in the
+		// instance type label value.
+		if len(splitByDash) < 3 {
+			instanceType = "unknown"
+		} else {
+			instanceType = strings.ToLower(strings.Join(splitByDash[:2], ""))
+			if instanceType == "n1highmem" || instanceType == "n1highcpu" {
+				instanceType = "n1standard" // These are priced the same. TODO: support n1ultrahighmem
+			} else if instanceType == "n2highmem" || instanceType == "n2highcpu" {
+				instanceType = "n2standard"
+			} else if instanceType == "e2highmem" || instanceType == "e2highcpu" {
+				instanceType = "e2standard"
+			} else if strings.HasPrefix(instanceType, "custom") {
+				instanceType = "custom" // The suffix of custom does not matter
+			}
 		}
 	}