github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/internal/k8s/env.go (about) 1 package k8s 2 3 import ( 4 "github.com/pkg/errors" 5 "k8s.io/client-go/tools/clientcmd" 6 "k8s.io/client-go/tools/clientcmd/api" 7 8 "github.com/tilt-dev/clusterid" 9 ) 10 11 type ClusterName string 12 13 func ProvideKubeContext(configOrError APIConfigOrError) KubeContext { 14 config := configOrError.Config 15 if config == nil { 16 return "" 17 } 18 return KubeContext(config.CurrentContext) 19 } 20 21 type APIConfigOrError struct { 22 Config *api.Config 23 Error error 24 } 25 26 func ProvideAPIConfig(clientLoader clientcmd.ClientConfig, contextOverride KubeContextOverride, namespaceOverride NamespaceOverride) APIConfigOrError { 27 config, err := clientLoader.RawConfig() 28 if err != nil { 29 return APIConfigOrError{Error: errors.Wrap(err, "Loading Kubernetes config")} 30 } 31 32 // NOTE(nick): The RawConfig() accessor doesn't handle overrides. 33 // The other accessors do. So we do what ClientConfig does internally, and 34 // apply the overrides ourselves. 35 if contextOverride != "" { 36 config.CurrentContext = string(contextOverride) 37 } 38 39 if namespaceOverride != "" { 40 context, ok := config.Contexts[config.CurrentContext] 41 if ok { 42 context.Namespace = string(namespaceOverride) 43 } 44 } 45 46 // Use ClientConfig() to workaround bugs in the validation api. 47 // See: https://github.com/tilt-dev/tilt/issues/5831 48 _, err = clientcmd.NewDefaultClientConfig(config, nil).ClientConfig() 49 if err != nil { 50 return APIConfigOrError{Error: errors.Wrap(err, "Loading Kubernetes config")} 51 } 52 53 return APIConfigOrError{Config: &config} 54 } 55 56 func ProvideClusterName(configOrError APIConfigOrError) ClusterName { 57 config := configOrError.Config 58 if config == nil { 59 return "" 60 } 61 n := config.CurrentContext 62 c, ok := config.Contexts[n] 63 if !ok { 64 return "" 65 } 66 return ClusterName(c.Cluster) 67 } 68 69 const ProductNone = clusterid.Product("") 70 71 func ProvideClusterProduct(configOrError APIConfigOrError) clusterid.Product { 72 config := configOrError.Config 73 if config == nil { 74 return ProductNone 75 } 76 return ClusterProductFromAPIConfig(config) 77 } 78 79 func ClusterProductFromAPIConfig(config *api.Config) clusterid.Product { 80 n := config.CurrentContext 81 82 c, ok := config.Contexts[n] 83 if !ok { 84 if n == "" { 85 return ProductNone 86 } 87 return clusterid.ProductUnknown 88 } 89 90 cn := c.Cluster 91 cl := config.Clusters[cn] 92 return clusterid.ProductFromContext(c, cl) 93 } 94 95 // Convert the current cluster type to an analytics env, for backwards compatibility. 96 func AnalyticsEnv(p clusterid.Product) string { 97 if p == clusterid.ProductDockerDesktop { 98 return "docker-for-desktop" 99 } 100 if p == clusterid.ProductKIND { 101 return "kind-0.6+" 102 } 103 return string(p) 104 }