diff --git a/go.mod b/go.mod index 5040a40cfc..5984fa024e 100644 --- a/go.mod +++ b/go.mod @@ -45,6 +45,7 @@ require ( github.com/spf13/cobra v1.3.0 github.com/spf13/pflag v1.0.5 github.com/stretchr/testify v1.7.0 + github.com/tilt-dev/clusterid v0.1.2 github.com/tilt-dev/dockerignore v0.1.1 github.com/tilt-dev/fsevents v0.0.0-20200515134857-2efe37af20de github.com/tilt-dev/fsnotify v1.4.8-0.20210701141043-dd524499d3fe @@ -72,7 +73,7 @@ require ( gopkg.in/yaml.v2 v2.4.0 helm.sh/helm/v3 v3.6.2 k8s.io/api v0.23.0 - k8s.io/apimachinery v0.23.0 + k8s.io/apimachinery v0.23.5 k8s.io/apiserver v0.23.0 k8s.io/cli-runtime v0.23.0 k8s.io/client-go v0.23.0 @@ -234,7 +235,7 @@ require ( sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.25 // indirect sigs.k8s.io/json v0.0.0-20211020170558-c049b76a60c6 // indirect sigs.k8s.io/kustomize/kyaml v0.13.0 // indirect - sigs.k8s.io/structured-merge-diff/v4 v4.2.0 // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.2.1 // indirect ) replace ( diff --git a/go.sum b/go.sum index d520123d54..bcc7beeb4b 100644 --- a/go.sum +++ b/go.sum @@ -1576,6 +1576,8 @@ github.com/tilt-dev/apiserver v0.23.0-tilt-20220118 h1:WRYE20MS3RsKiWlkBdRkOiGLo github.com/tilt-dev/apiserver v0.23.0-tilt-20220118/go.mod h1:Cec35u/9zAepDPPFyT+UMrgqOCjgJ5qtfVJDxjZYmt4= github.com/tilt-dev/browser v0.0.1 h1:e+mFToX6A7pkMlGFrXW5VLvS7qS0HVbcXqmR0uPrWUA= github.com/tilt-dev/browser v0.0.1/go.mod h1:2DaMt8P8xEqDFzxaAbraOig5iUmQdd1wtO1Tb6tODHA= +github.com/tilt-dev/clusterid v0.1.2 h1:ch+qLP6y3n6KvuIyovSa030hJuWJ//G8gXqvouxpRSc= +github.com/tilt-dev/clusterid v0.1.2/go.mod h1:QeDTv8HzwdCk6P1WzQXA+wpPSYAniAWipqbTLEF9ets= github.com/tilt-dev/dockerignore v0.1.1 h1:/MPYqcD8qMCMyh3yiHuQdzbMQi9NL4vVopo6/9D/XvE= github.com/tilt-dev/dockerignore v0.1.1/go.mod h1:2ooUDj8B9FNWYvHadA4EKG0JDaeAOjiq5P+mvEzS2eY= github.com/tilt-dev/fsevents v0.0.0-20200515134857-2efe37af20de h1:tG+nJMUUxV7MJm/MeU1Mw7rvmwN9GWyHMMg+wtf9HS4= @@ -2612,8 +2614,9 @@ sigs.k8s.io/structured-merge-diff v0.0.0-20190525122527-15d366b2352e/go.mod h1:w sigs.k8s.io/structured-merge-diff/v4 v4.0.2/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.1.0/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.1.2/go.mod h1:j/nl6xW8vLS49O8YvXW1ocPhZawJtm+Yrr7PPRQ0Vg4= -sigs.k8s.io/structured-merge-diff/v4 v4.2.0 h1:kDvPBbnPk+qYmkHmSo8vKGp438IASWofnbbUKDE/bv0= sigs.k8s.io/structured-merge-diff/v4 v4.2.0/go.mod h1:j/nl6xW8vLS49O8YvXW1ocPhZawJtm+Yrr7PPRQ0Vg4= +sigs.k8s.io/structured-merge-diff/v4 v4.2.1 h1:bKCqE9GvQ5tiVHn5rfn1r+yao3aLQEaLzkkmAkf+A6Y= +sigs.k8s.io/structured-merge-diff/v4 v4.2.1/go.mod h1:j/nl6xW8vLS49O8YvXW1ocPhZawJtm+Yrr7PPRQ0Vg4= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= diff --git a/internal/build/test_utils.go b/internal/build/test_utils.go index 0d92d2e2fc..8cc044177d 100644 --- a/internal/build/test_utils.go +++ b/internal/build/test_utils.go @@ -16,6 +16,7 @@ import ( "github.com/docker/docker/api/types/container" "github.com/stretchr/testify/assert" + "github.com/tilt-dev/clusterid" wmcontainer "github.com/tilt-dev/tilt/internal/container" "github.com/tilt-dev/tilt/internal/docker" "github.com/tilt-dev/tilt/internal/dockerfile" @@ -46,7 +47,7 @@ func (c fakeClock) Now() time.Time { return c.now } func newDockerBuildFixture(t testing.TB) *dockerBuildFixture { ctx, _, _ := testutils.CtxAndAnalyticsForTest() - env := k8s.EnvGKE + env := clusterid.ProductGKE dEnv := docker.ProvideClusterEnv(ctx, "gke", env, wmcontainer.RuntimeDocker, k8s.FakeMinikube{}) dCli := docker.NewDockerClient(ctx, docker.Env(dEnv)) diff --git a/internal/cli/wire.go b/internal/cli/wire.go index 7d314e3762..712ec0d7be 100644 --- a/internal/cli/wire.go +++ b/internal/cli/wire.go @@ -9,6 +9,7 @@ import ( "context" "time" + "github.com/tilt-dev/clusterid" cliclient "github.com/tilt-dev/tilt/internal/cli/client" "github.com/tilt-dev/tilt/internal/controllers/core/filewatch/fsevent" @@ -62,7 +63,7 @@ import ( ) var K8sWireSet = wire.NewSet( - k8s.ProvideEnv, + k8s.ProvideClusterProduct, k8s.ProvideClusterName, k8s.ProvideKubeContext, k8s.ProvideKubeConfig, @@ -238,7 +239,7 @@ func wireKubeConfig(ctx context.Context) (*api.Config, error) { return nil, nil } -func wireEnv(ctx context.Context) (k8s.Env, error) { +func wireEnv(ctx context.Context) (clusterid.Product, error) { wire.Build(K8sWireSet) return "", nil } diff --git a/internal/cli/wire_gen.go b/internal/cli/wire_gen.go index a4437490a3..eb490b17cf 100644 --- a/internal/cli/wire_gen.go +++ b/internal/cli/wire_gen.go @@ -17,6 +17,7 @@ import ( "k8s.io/client-go/tools/clientcmd/api" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/analytics" "github.com/tilt-dev/tilt/internal/build" client2 "github.com/tilt-dev/tilt/internal/cli/client" @@ -101,7 +102,7 @@ func wireTiltfileResult(ctx context.Context, analytics2 *analytics.TiltAnalytics if err != nil { return cmdTiltfileResultDeps{}, err } - env := k8s.ProvideEnv(ctx, apiConfig) + env := k8s.ProvideClusterProduct(ctx, apiConfig) plugin := k8scontext.NewPlugin(kubeContext, env) tiltBuild := provideTiltInfo() versionPlugin := version.NewPlugin(tiltBuild) @@ -155,7 +156,7 @@ func wireDockerPrune(ctx context.Context, analytics2 *analytics.TiltAnalytics, s if err != nil { return dpDeps{}, err } - env := k8s.ProvideEnv(ctx, apiConfig) + env := k8s.ProvideClusterProduct(ctx, apiConfig) restConfigOrError := k8s.ProvideRESTConfig(clientConfig) clientsetOrError := k8s.ProvideClientset(restConfigOrError) portForwardClient := k8s.ProvidePortForwardClient(restConfigOrError, clientsetOrError) @@ -277,7 +278,7 @@ func wireCmdUp(ctx context.Context, analytics3 *analytics.TiltAnalytics, cmdTags if err != nil { return CmdUpDeps{}, err } - k8sEnv := k8s.ProvideEnv(ctx, apiConfig) + k8sEnv := k8s.ProvideClusterProduct(ctx, apiConfig) restConfigOrError := k8s.ProvideRESTConfig(clientConfig) clientsetOrError := k8s.ProvideClientset(restConfigOrError) portForwardClient := k8s.ProvidePortForwardClient(restConfigOrError, clientsetOrError) @@ -490,7 +491,7 @@ func wireCmdCI(ctx context.Context, analytics3 *analytics.TiltAnalytics, subcomm if err != nil { return CmdCIDeps{}, err } - k8sEnv := k8s.ProvideEnv(ctx, apiConfig) + k8sEnv := k8s.ProvideClusterProduct(ctx, apiConfig) restConfigOrError := k8s.ProvideRESTConfig(clientConfig) clientsetOrError := k8s.ProvideClientset(restConfigOrError) portForwardClient := k8s.ProvidePortForwardClient(restConfigOrError, clientsetOrError) @@ -699,7 +700,7 @@ func wireCmdUpdog(ctx context.Context, analytics3 *analytics.TiltAnalytics, cmdT if err != nil { return CmdUpdogDeps{}, err } - k8sEnv := k8s.ProvideEnv(ctx, apiConfig) + k8sEnv := k8s.ProvideClusterProduct(ctx, apiConfig) restConfigOrError := k8s.ProvideRESTConfig(clientConfig) clientsetOrError := k8s.ProvideClientset(restConfigOrError) portForwardClient := k8s.ProvidePortForwardClient(restConfigOrError, clientsetOrError) @@ -818,7 +819,7 @@ func wireKubeConfig(ctx context.Context) (*api.Config, error) { return apiConfig, nil } -func wireEnv(ctx context.Context) (k8s.Env, error) { +func wireEnv(ctx context.Context) (clusterid.Product, error) { k8sKubeContextOverride := ProvideKubeContextOverride() k8sNamespaceOverride := ProvideNamespaceOverride() clientConfig := k8s.ProvideClientConfig(k8sKubeContextOverride, k8sNamespaceOverride) @@ -826,7 +827,7 @@ func wireEnv(ctx context.Context) (k8s.Env, error) { if err != nil { return "", err } - env := k8s.ProvideEnv(ctx, apiConfig) + env := k8s.ProvideClusterProduct(ctx, apiConfig) return env, nil } @@ -858,7 +859,7 @@ func wireRuntime(ctx context.Context) (container.Runtime, error) { if err != nil { return "", err } - env := k8s.ProvideEnv(ctx, apiConfig) + env := k8s.ProvideClusterProduct(ctx, apiConfig) restConfigOrError := k8s.ProvideRESTConfig(clientConfig) clientsetOrError := k8s.ProvideClientset(restConfigOrError) portForwardClient := k8s.ProvidePortForwardClient(restConfigOrError, clientsetOrError) @@ -881,7 +882,7 @@ func wireK8sClient(ctx context.Context) (k8s.Client, error) { if err != nil { return nil, err } - env := k8s.ProvideEnv(ctx, apiConfig) + env := k8s.ProvideClusterProduct(ctx, apiConfig) restConfigOrError := k8s.ProvideRESTConfig(clientConfig) clientsetOrError := k8s.ProvideClientset(restConfigOrError) portForwardClient := k8s.ProvidePortForwardClient(restConfigOrError, clientsetOrError) @@ -920,7 +921,7 @@ func wireDockerClusterClient(ctx context.Context) (docker.ClusterClient, error) if err != nil { return nil, err } - env := k8s.ProvideEnv(ctx, apiConfig) + env := k8s.ProvideClusterProduct(ctx, apiConfig) restConfigOrError := k8s.ProvideRESTConfig(clientConfig) clientsetOrError := k8s.ProvideClientset(restConfigOrError) portForwardClient := k8s.ProvidePortForwardClient(restConfigOrError, clientsetOrError) @@ -950,7 +951,7 @@ func wireDockerLocalClient(ctx context.Context) (docker.LocalClient, error) { if err != nil { return nil, err } - env := k8s.ProvideEnv(ctx, apiConfig) + env := k8s.ProvideClusterProduct(ctx, apiConfig) restConfigOrError := k8s.ProvideRESTConfig(clientConfig) clientsetOrError := k8s.ProvideClientset(restConfigOrError) portForwardClient := k8s.ProvidePortForwardClient(restConfigOrError, clientsetOrError) @@ -976,7 +977,7 @@ func wireDockerCompositeClient(ctx context.Context) (docker.CompositeClient, err if err != nil { return nil, err } - env := k8s.ProvideEnv(ctx, apiConfig) + env := k8s.ProvideClusterProduct(ctx, apiConfig) restConfigOrError := k8s.ProvideRESTConfig(clientConfig) clientsetOrError := k8s.ProvideClientset(restConfigOrError) portForwardClient := k8s.ProvidePortForwardClient(restConfigOrError, clientsetOrError) @@ -1007,7 +1008,7 @@ func wireDownDeps(ctx context.Context, tiltAnalytics *analytics.TiltAnalytics, s if err != nil { return DownDeps{}, err } - env := k8s.ProvideEnv(ctx, apiConfig) + env := k8s.ProvideClusterProduct(ctx, apiConfig) plugin := k8scontext.NewPlugin(kubeContext, env) tiltBuild := provideTiltInfo() versionPlugin := version.NewPlugin(tiltBuild) @@ -1069,7 +1070,7 @@ func wireDumpImageDeployRefDeps(ctx context.Context) (DumpImageDeployRefDeps, er if err != nil { return DumpImageDeployRefDeps{}, err } - env := k8s.ProvideEnv(ctx, apiConfig) + env := k8s.ProvideClusterProduct(ctx, apiConfig) restConfigOrError := k8s.ProvideRESTConfig(clientConfig) clientsetOrError := k8s.ProvideClientset(restConfigOrError) portForwardClient := k8s.ProvidePortForwardClient(restConfigOrError, clientsetOrError) @@ -1122,7 +1123,7 @@ func wireClientGetter(ctx context.Context) (*client2.Getter, error) { // wire.go: -var K8sWireSet = wire.NewSet(k8s.ProvideEnv, k8s.ProvideClusterName, k8s.ProvideKubeContext, k8s.ProvideKubeConfig, k8s.ProvideClientConfig, k8s.ProvideClientset, k8s.ProvideRESTConfig, k8s.ProvidePortForwardClient, k8s.ProvideConfigNamespace, k8s.ProvideContainerRuntime, k8s.ProvideServerVersion, k8s.ProvideK8sClient, ProvideKubeContextOverride, +var K8sWireSet = wire.NewSet(k8s.ProvideClusterProduct, k8s.ProvideClusterName, k8s.ProvideKubeContext, k8s.ProvideKubeConfig, k8s.ProvideClientConfig, k8s.ProvideClientset, k8s.ProvideRESTConfig, k8s.ProvidePortForwardClient, k8s.ProvideConfigNamespace, k8s.ProvideContainerRuntime, k8s.ProvideServerVersion, k8s.ProvideK8sClient, ProvideKubeContextOverride, ProvideNamespaceOverride) var BaseWireSet = wire.NewSet( diff --git a/internal/controllers/core/cluster/client.go b/internal/controllers/core/cluster/client.go index a3fc97e639..2f19306bc0 100644 --- a/internal/controllers/core/cluster/client.go +++ b/internal/controllers/core/cluster/client.go @@ -49,7 +49,7 @@ func KubernetesClientFromEnv(ctx context.Context, contextOverride k8s.KubeContex if err != nil { return nil, err } - env := k8s.ProvideEnv(ctx, apiConfig) + env := k8s.ProvideClusterProduct(ctx, apiConfig) restConfigOrError := k8s.ProvideRESTConfig(clientConfig) clientsetOrError := k8s.ProvideClientset(restConfigOrError) diff --git a/internal/docker/client_integration_test.go b/internal/docker/client_integration_test.go index d3f9561880..670543d49a 100644 --- a/internal/docker/client_integration_test.go +++ b/internal/docker/client_integration_test.go @@ -10,6 +10,7 @@ import ( "github.com/docker/distribution/reference" "github.com/stretchr/testify/require" + "github.com/tilt-dev/clusterid" wmcontainer "github.com/tilt-dev/tilt/internal/container" "github.com/tilt-dev/tilt/internal/k8s" "github.com/tilt-dev/tilt/internal/testutils" @@ -17,7 +18,7 @@ import ( func TestCli_Run(t *testing.T) { ctx, _, _ := testutils.CtxAndAnalyticsForTest() - dEnv := ProvideClusterEnv(ctx, "gke", k8s.EnvGKE, wmcontainer.RuntimeDocker, k8s.FakeMinikube{}) + dEnv := ProvideClusterEnv(ctx, "gke", clusterid.ProductGKE, wmcontainer.RuntimeDocker, k8s.FakeMinikube{}) cli := NewDockerClient(ctx, Env(dEnv)) defer func() { // release any idle connections to avoid out of file errors if running test many times diff --git a/internal/docker/client_test.go b/internal/docker/client_test.go index 989f4f4e85..e7b48b4055 100644 --- a/internal/docker/client_test.go +++ b/internal/docker/client_test.go @@ -9,6 +9,7 @@ import ( "github.com/docker/docker/api/types" "github.com/stretchr/testify/assert" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/container" "github.com/tilt-dev/tilt/internal/k8s" ) @@ -91,7 +92,7 @@ func TestSupported(t *testing.T) { } type provideEnvTestCase struct { - env k8s.Env + env clusterid.Product runtime container.Runtime minikubeV string osEnv map[string]string @@ -100,7 +101,7 @@ type provideEnvTestCase struct { expectedLocal Env } -func TestProvideEnv(t *testing.T) { +func TestProvideClusterProduct(t *testing.T) { envVars := []string{ "DOCKER_TLS_VERIFY", "DOCKER_HOST", @@ -111,7 +112,7 @@ func TestProvideEnv(t *testing.T) { cases := []provideEnvTestCase{ {}, { - env: k8s.EnvUnknown, + env: clusterid.ProductUnknown, osEnv: map[string]string{ "DOCKER_TLS_VERIFY": "1", "DOCKER_HOST": "tcp://192.168.99.100:2376", @@ -132,7 +133,7 @@ func TestProvideEnv(t *testing.T) { }, }, { - env: k8s.EnvMicroK8s, + env: clusterid.ProductMicroK8s, runtime: container.RuntimeDocker, expectedCluster: Env{ Host: microK8sDockerHost, @@ -141,11 +142,11 @@ func TestProvideEnv(t *testing.T) { expectedLocal: Env{}, }, { - env: k8s.EnvMicroK8s, + env: clusterid.ProductMicroK8s, runtime: container.RuntimeCrio, }, { - env: k8s.EnvMinikube, + env: clusterid.ProductMinikube, runtime: container.RuntimeDocker, mkEnv: map[string]string{ "DOCKER_TLS_VERIFY": "1", @@ -163,7 +164,7 @@ func TestProvideEnv(t *testing.T) { }, }, { - env: k8s.EnvMinikube, + env: clusterid.ProductMinikube, runtime: container.RuntimeDocker, minikubeV: "1.8.2", mkEnv: map[string]string{ @@ -181,7 +182,7 @@ func TestProvideEnv(t *testing.T) { }, }, { - env: k8s.EnvMinikube, + env: clusterid.ProductMinikube, runtime: container.RuntimeDocker, mkEnv: map[string]string{ "DOCKER_TLS_VERIFY": "1", @@ -202,7 +203,7 @@ func TestProvideEnv(t *testing.T) { { // Test the case where the user has already run // eval $(minikube docker-env) - env: k8s.EnvMinikube, + env: clusterid.ProductMinikube, runtime: container.RuntimeDocker, mkEnv: map[string]string{ "DOCKER_TLS_VERIFY": "1", @@ -230,7 +231,7 @@ func TestProvideEnv(t *testing.T) { }, }, { - env: k8s.EnvMinikube, + env: clusterid.ProductMinikube, runtime: container.RuntimeCrio, mkEnv: map[string]string{ "DOCKER_TLS_VERIFY": "1", @@ -240,7 +241,7 @@ func TestProvideEnv(t *testing.T) { }, }, { - env: k8s.EnvUnknown, + env: clusterid.ProductUnknown, osEnv: map[string]string{ "DOCKER_TLS_VERIFY": "1", "DOCKER_HOST": "localhost:2376", diff --git a/internal/docker/env.go b/internal/docker/env.go index bd418739de..65124386f4 100644 --- a/internal/docker/env.go +++ b/internal/docker/env.go @@ -9,6 +9,7 @@ import ( "github.com/docker/cli/opts" "github.com/pkg/errors" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/container" "github.com/tilt-dev/tilt/internal/k8s" "github.com/tilt-dev/tilt/pkg/logger" @@ -82,7 +83,7 @@ func (e Env) AsEnviron() []string { type ClusterEnv Env type LocalEnv Env -func ProvideLocalEnv(_ context.Context, kubeContext k8s.KubeContext, env k8s.Env, cEnv ClusterEnv) LocalEnv { +func ProvideLocalEnv(_ context.Context, kubeContext k8s.KubeContext, env clusterid.Product, cEnv ClusterEnv) LocalEnv { result := overlayOSEnvVars(Env{}) // if the ClusterEnv host is the same, use it to infer some properties @@ -95,14 +96,14 @@ func ProvideLocalEnv(_ context.Context, kubeContext k8s.KubeContext, env k8s.Env // kubecontext twice - the logic above should already have copied it // from the cluster env (this is harmless though because // Env::WillBuildToKubeContext still works fine) - if env == k8s.EnvDockerDesktop && isDefaultHost(result) { + if env == clusterid.ProductDockerDesktop && isDefaultHost(result) { result.BuildToKubeContexts = append(result.BuildToKubeContexts, string(kubeContext)) } return LocalEnv(result) } -func ProvideClusterEnv(ctx context.Context, kubeContext k8s.KubeContext, env k8s.Env, runtime container.Runtime, minikubeClient k8s.MinikubeClient) ClusterEnv { +func ProvideClusterEnv(ctx context.Context, kubeContext k8s.KubeContext, env clusterid.Product, runtime container.Runtime, minikubeClient k8s.MinikubeClient) ClusterEnv { // start with an empty env, then populate with cluster-specific values if // available, and then potentially throw that all away if there are OS env // vars overriding those @@ -125,7 +126,7 @@ func ProvideClusterEnv(ctx context.Context, kubeContext k8s.KubeContext, env k8s result := Env{} if runtime == container.RuntimeDocker { - if env == k8s.EnvMinikube { + if env == clusterid.ProductMinikube { // If we're running Minikube with a docker runtime, talk to Minikube's docker socket. envMap, ok, err := minikubeClient.DockerEnv(ctx) if err != nil { @@ -156,7 +157,7 @@ func ProvideClusterEnv(ctx context.Context, kubeContext k8s.KubeContext, env k8s result.IsOldMinikube = isOldMinikube(ctx, minikubeClient) result.BuildToKubeContexts = append(result.BuildToKubeContexts, string(kubeContext)) } - } else if env == k8s.EnvMicroK8s { + } else if env == clusterid.ProductMicroK8s { // If we're running Microk8s with a docker runtime, talk to Microk8s's docker socket. result.Host = microK8sDockerHost result.BuildToKubeContexts = append(result.BuildToKubeContexts, string(kubeContext)) @@ -169,7 +170,7 @@ func ProvideClusterEnv(ctx context.Context, kubeContext k8s.KubeContext, env k8s // currently both Docker Desktop + Rancher Desktop support running a // K8s cluster that shares the default Docker socket (as compared to // minikube/microk8s which maintain their own independent Docker socket) - if env == k8s.EnvDockerDesktop || env == k8s.EnvRancherDesktop { + if env == clusterid.ProductDockerDesktop || env == clusterid.ProductRancherDesktop { result.BuildToKubeContexts = append(result.BuildToKubeContexts, string(kubeContext)) } } diff --git a/internal/engine/analytics/analytics_reporter.go b/internal/engine/analytics/analytics_reporter.go index a8a544abc3..2e2cc776a3 100644 --- a/internal/engine/analytics/analytics_reporter.go +++ b/internal/engine/analytics/analytics_reporter.go @@ -6,6 +6,7 @@ import ( "strconv" "time" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/analytics" "github.com/tilt-dev/tilt/internal/controllers/apis/liveupdate" "github.com/tilt-dev/tilt/internal/feature" @@ -21,7 +22,7 @@ type AnalyticsReporter struct { a *analytics.TiltAnalytics store store.RStore kClient k8s.Client - env k8s.Env + env clusterid.Product featureDefaults feature.Defaults started bool } @@ -66,7 +67,7 @@ func ProvideAnalyticsReporter( a *analytics.TiltAnalytics, st store.RStore, kClient k8s.Client, - env k8s.Env, + env clusterid.Product, fDefaults feature.Defaults) *AnalyticsReporter { return &AnalyticsReporter{ a: a, @@ -144,7 +145,7 @@ func (ar *AnalyticsReporter) report(ctx context.Context) { // env should really be a global tag, but there's a circular dependency // between the global tags and env initialization, so we add it manually. - "env": string(ar.env), + "env": k8s.AnalyticsEnv(ar.env), "term_mode": strconv.Itoa(int(st.TerminalMode)), } diff --git a/internal/engine/analytics/analytics_reporter_test.go b/internal/engine/analytics/analytics_reporter_test.go index 12ae5a137e..439060ddec 100644 --- a/internal/engine/analytics/analytics_reporter_test.go +++ b/internal/engine/analytics/analytics_reporter_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" + "github.com/tilt-dev/clusterid" tiltanalytics "github.com/tilt-dev/tilt/internal/analytics" "github.com/tilt-dev/tilt/internal/container" "github.com/tilt-dev/tilt/internal/feature" @@ -111,7 +112,7 @@ func TestAnalyticsReporter_Everything(t *testing.T) { "resource.enabled.count": "12", "tiltfile.error": "false", "up.starttime": state.TiltStartTime.Format(time.RFC3339), - "env": string(k8s.EnvDockerDesktop), + "env": k8s.AnalyticsEnv(clusterid.ProductDockerDesktop), "term_mode": "0", "k8s.runtime": "docker", "k8s.registry.host": "1", @@ -196,7 +197,7 @@ func TestAnalyticsReporter_TiltfileError(t *testing.T) { "builds.completed_count": "3", "tiltfile.error": "true", "up.starttime": state.TiltStartTime.Format(time.RFC3339), - "env": string(k8s.EnvDockerDesktop), + "env": k8s.AnalyticsEnv(clusterid.ProductDockerDesktop), "term_mode": "0", "k8s.runtime": "docker", "feature.testflag_enabled.enabled": "true", @@ -229,7 +230,7 @@ func newAnalyticsReporterTestFixture(t testing.TB) *analyticsReporterTestFixture state.Features = feature.FromDefaults(features).ToEnabled() st.UnlockMutableState() - ar := ProvideAnalyticsReporter(a, st, kClient, k8s.EnvDockerDesktop, features) + ar := ProvideAnalyticsReporter(a, st, kClient, clusterid.ProductDockerDesktop, features) return &analyticsReporterTestFixture{ manifestCount: 0, ar: ar, diff --git a/internal/engine/build_and_deployer.go b/internal/engine/build_and_deployer.go index 92fd3897b6..2b87650286 100644 --- a/internal/engine/build_and_deployer.go +++ b/internal/engine/build_and_deployer.go @@ -8,9 +8,9 @@ import ( "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/container" "github.com/tilt-dev/tilt/internal/engine/buildcontrol" - "github.com/tilt-dev/tilt/internal/k8s" "github.com/tilt-dev/tilt/internal/store" "github.com/tilt-dev/tilt/internal/store/liveupdates" "github.com/tilt-dev/tilt/pkg/logger" @@ -111,7 +111,7 @@ func (composite *CompositeBuildAndDeployer) BuildAndDeploy(ctx context.Context, } func DefaultBuildOrder(lubad *buildcontrol.LiveUpdateBuildAndDeployer, ibad *buildcontrol.ImageBuildAndDeployer, dcbad *buildcontrol.DockerComposeBuildAndDeployer, - ltbad *buildcontrol.LocalTargetBuildAndDeployer, updMode liveupdates.UpdateMode, env k8s.Env, runtime container.Runtime) BuildOrder { + ltbad *buildcontrol.LocalTargetBuildAndDeployer, updMode liveupdates.UpdateMode, env clusterid.Product, runtime container.Runtime) BuildOrder { if updMode == liveupdates.UpdateModeImage { return BuildOrder{dcbad, ibad, ltbad} } diff --git a/internal/engine/build_and_deployer_live_update_test.go b/internal/engine/build_and_deployer_live_update_test.go index 8655a8ca27..4626b5c134 100644 --- a/internal/engine/build_and_deployer_live_update_test.go +++ b/internal/engine/build_and_deployer_live_update_test.go @@ -10,18 +10,15 @@ import ( "github.com/stretchr/testify/require" "k8s.io/client-go/util/exec" + "github.com/tilt-dev/clusterid" + "github.com/tilt-dev/tilt/internal/container" + "github.com/tilt-dev/tilt/internal/docker" "github.com/tilt-dev/tilt/internal/engine/buildcontrol" + "github.com/tilt-dev/tilt/internal/k8s" "github.com/tilt-dev/tilt/internal/k8s/testyaml" - "github.com/tilt-dev/tilt/internal/store/liveupdates" - - "github.com/tilt-dev/tilt/internal/docker" - "github.com/tilt-dev/tilt/internal/store" - + "github.com/tilt-dev/tilt/internal/store/liveupdates" "github.com/tilt-dev/tilt/internal/testutils/manifestbuilder" - - "github.com/tilt-dev/tilt/internal/container" - "github.com/tilt-dev/tilt/internal/k8s" "github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1" "github.com/tilt-dev/tilt/pkg/model" ) @@ -178,7 +175,7 @@ func runTestCase(t *testing.T, f *bdFixture, tCase testCase) { } func TestLiveUpdateDockerBuildLocalContainer(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) m := manifestbuilder.New(f, "sancho"). WithK8sYAML(SanchoYAML). @@ -198,7 +195,7 @@ func TestLiveUpdateDockerBuildLocalContainer(t *testing.T) { } func TestLiveUpdateDockerBuildLocalContainerSameImgMultipleContainers(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) m := manifestbuilder.New(f, "sancho"). WithK8sYAML(SanchoYAML). @@ -222,7 +219,7 @@ func TestLiveUpdateDockerBuildLocalContainerSameImgMultipleContainers(t *testing } func TestLiveUpdateDockerBuildExecSameImgMultipleContainers(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeCrio) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeCrio) iTarg := NewSanchoDockerBuildImageTarget(f) lu := assembleLiveUpdate(SanchoSyncSteps(f), nil, false, []string{"i/match/nothing"}, f) @@ -246,7 +243,7 @@ func TestLiveUpdateDockerBuildExecSameImgMultipleContainers(t *testing.T) { } func TestLiveUpdateDockerBuildLocalContainerDiffImgMultipleContainers(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) sanchoTarg := NewSanchoLiveUpdateImageTarget(f) sidecarTarg := NewSanchoSidecarLiveUpdateImageTarget(f) @@ -273,7 +270,7 @@ func TestLiveUpdateDockerBuildLocalContainerDiffImgMultipleContainers(t *testing } func TestLiveUpdateDockerBuildExecDiffImgMultipleContainers(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeCrio) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeCrio) sanchoLU := assembleLiveUpdate(SanchoSyncSteps(f), SanchoRunSteps, false, nil, f) sidecarLU := assembleLiveUpdate(SyncStepsForApp("sidecar", f), RunStepsForApp("sidecar"), @@ -303,7 +300,7 @@ func TestLiveUpdateDockerBuildExecDiffImgMultipleContainers(t *testing.T) { } func TestLiveUpdateDiffImgMultipleContainersOnlySomeSyncsMatch(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeCrio) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeCrio) sanchoPath := f.JoinPath("sancho") sanchoSyncs := SanchoSyncSteps(f) @@ -352,7 +349,7 @@ func TestLiveUpdateDiffImgMultipleContainersOnlySomeSyncsMatch(t *testing.T) { } func TestLiveUpdateDiffImgMultipleContainersSameContextOnlyOneLiveUpdate(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeCrio) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeCrio) buildContext := f.Path() sanchoSyncs := SanchoSyncSteps(f) @@ -390,7 +387,7 @@ func TestLiveUpdateDiffImgMultipleContainersSameContextOnlyOneLiveUpdate(t *test } func TestLiveUpdateDiffImgMultipleContainersFallBackIfFilesDoesntMatchAnySyncs(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeCrio) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeCrio) sanchoSyncs := SanchoSyncSteps(f) sanchoSyncs[0].LocalPath = f.JoinPath("sancho") @@ -433,7 +430,7 @@ func TestLiveUpdateDiffImgMultipleContainersFallBackIfFilesDoesntMatchAnySyncs(t } func TestLiveUpdateDockerContainerUserRunFailureDoesntFallBack(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) m := manifestbuilder.New(f, "sancho"). WithK8sYAML(SanchoYAML). @@ -463,7 +460,7 @@ func TestLiveUpdateDockerContainerUserRunFailureDoesntFallBack(t *testing.T) { } func TestLiveUpdateExecUserRunFailureDoesntFallBack(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeCrio) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeCrio) f.k8s.ExecErrors = []error{nil, userFailureErrExec} @@ -493,7 +490,7 @@ func TestLiveUpdateExecUserRunFailureDoesntFallBack(t *testing.T) { // If any container updates fail with a non-UserRunFailure, fall back to image build. func TestLiveUpdateMultipleContainersFallsBackForFailure(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) f.docker.SetExecError(fmt.Errorf("egads")) @@ -522,7 +519,7 @@ func TestLiveUpdateMultipleContainersFallsBackForFailure(t *testing.T) { // Even if the first container update succeeds, if any subsequent container updates // fail with a non-UserRunFailure, fall back to image build. func TestLiveUpdateMultipleContainersFallsBackForFailureAfterSuccess(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) // First call = no error, second call = error f.docker.ExecErrorsToThrow = []error{nil, fmt.Errorf("egads")} @@ -554,7 +551,7 @@ func TestLiveUpdateMultipleContainersFallsBackForFailureAfterSuccess(t *testing. // If one container update fails with UserRunFailure, continue running updates on // all containers. If ALL the updates fail with a UserRunFailure, don't fall back. func TestLiveUpdateMultipleContainersUpdatesAllForUserRunFailuresAndDoesntFallBack(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) // Same UserRunFailure on all three exec calls f.docker.ExecErrorsToThrow = []error{userFailureErrDocker, userFailureErrDocker, userFailureErrDocker} @@ -591,7 +588,7 @@ func TestLiveUpdateMultipleContainersUpdatesAllForUserRunFailuresAndDoesntFallBa // If only SOME container updates fail with a UserRunFailure (1+ succeeds, or 1+ fails // with a non-UserRunFailure), fall back to an image build. func TestLiveUpdateMultipleContainersFallsBackForSomeUserRunFailuresSomeSuccess(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) f.docker.ExecErrorsToThrow = []error{userFailureErrDocker, nil, userFailureErrDocker} @@ -621,7 +618,7 @@ func TestLiveUpdateMultipleContainersFallsBackForSomeUserRunFailuresSomeSuccess( } func TestLiveUpdateMultipleContainersFallsBackForSomeUserRunFailuresSomeNonUserFailures(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) f.docker.ExecErrorsToThrow = []error{ userFailureErrDocker, @@ -654,7 +651,7 @@ func TestLiveUpdateMultipleContainersFallsBackForSomeUserRunFailuresSomeNonUserF } func TestLiveUpdateCustomBuildLocalContainer(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) lu := assembleLiveUpdate(SanchoSyncSteps(f), SanchoRunSteps, true, []string{"i/match/nothing"}, f) tCase := testCase{ @@ -675,7 +672,7 @@ func TestLiveUpdateCustomBuildLocalContainer(t *testing.T) { } func TestLiveUpdateHotReloadLocalContainer(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) lu := assembleLiveUpdate(SanchoSyncSteps(f), SanchoRunSteps, false, nil, f) tCase := testCase{ @@ -696,7 +693,7 @@ func TestLiveUpdateHotReloadLocalContainer(t *testing.T) { } func TestLiveUpdateRunTriggerLocalContainer(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) runs := []v1alpha1.LiveUpdateExec{ {Args: model.ToUnixCmd("echo hello").Argv}, @@ -722,7 +719,7 @@ func TestLiveUpdateRunTriggerLocalContainer(t *testing.T) { } func TestLiveUpdateRunTriggerExec(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) runs := []v1alpha1.LiveUpdateExec{ {Args: model.ToUnixCmd("echo hello").Argv}, @@ -749,7 +746,7 @@ func TestLiveUpdateRunTriggerExec(t *testing.T) { } func TestLiveUpdateCustomBuildExec(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) lu := assembleLiveUpdate(SanchoSyncSteps(f), SanchoRunSteps, false, nil, f) tCase := testCase{ @@ -771,7 +768,7 @@ func TestLiveUpdateCustomBuildExec(t *testing.T) { } func TestLiveUpdateExecDoesNotSupportRestart(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeContainerd) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeContainerd) lu := assembleLiveUpdate(SanchoSyncSteps(f), SanchoRunSteps, true, []string{"i/match/nothing"}, f) tCase := testCase{ @@ -794,7 +791,7 @@ func TestLiveUpdateExecDoesNotSupportRestart(t *testing.T) { } func TestLiveUpdateDockerBuildExec(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeContainerd) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeContainerd) lu := assembleLiveUpdate(SanchoSyncSteps(f), SanchoRunSteps, false, nil, f) tCase := testCase{ @@ -813,7 +810,7 @@ func TestLiveUpdateDockerBuildExec(t *testing.T) { } func TestLiveUpdateLocalContainerFallBackOn(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) lu := assembleLiveUpdate(SanchoSyncSteps(f), SanchoRunSteps, true, []string{"a.txt"}, f) tCase := testCase{ @@ -836,7 +833,7 @@ func TestLiveUpdateLocalContainerFallBackOn(t *testing.T) { } func TestLiveUpdateExecFallBackOn(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) lu := assembleLiveUpdate(SanchoSyncSteps(f), SanchoRunSteps, false, []string{"a.txt"}, f) tCase := testCase{ @@ -859,7 +856,7 @@ func TestLiveUpdateExecFallBackOn(t *testing.T) { } func TestLiveUpdateLocalContainerChangedFileNotMatchingSyncFallsBack(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) steps := []v1alpha1.LiveUpdateSync{{ LocalPath: filepath.Join("specific", "directory"), @@ -890,7 +887,7 @@ func TestLiveUpdateLocalContainerChangedFileNotMatchingSyncFallsBack(t *testing. } func TestLiveUpdateExecChangedFileNotMatchingSyncFallsBack(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) steps := []v1alpha1.LiveUpdateSync{{ LocalPath: filepath.Join("specific", "directory"), @@ -921,7 +918,7 @@ func TestLiveUpdateExecChangedFileNotMatchingSyncFallsBack(t *testing.T) { } func TestLiveUpdateManyFilesNotMatching(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) steps := []v1alpha1.LiveUpdateSync{{ LocalPath: filepath.Join("specific", "directory"), @@ -964,7 +961,7 @@ func TestLiveUpdateManyFilesNotMatching(t *testing.T) { } func TestLiveUpdateSomeFilesMatchSyncSomeDontFallsBack(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) steps := []v1alpha1.LiveUpdateSync{{ LocalPath: filepath.Join("specific", "directory"), @@ -996,7 +993,7 @@ func TestLiveUpdateSomeFilesMatchSyncSomeDontFallsBack(t *testing.T) { } func TestLiveUpdateInFirstImageOfImageDependency(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) steps := []v1alpha1.LiveUpdateSync{{ LocalPath: "sancho-base", @@ -1022,7 +1019,7 @@ func TestLiveUpdateInFirstImageOfImageDependency(t *testing.T) { } func TestLiveUpdateInFirstImageOfImageDependencyWithoutSync(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) steps := []v1alpha1.LiveUpdateSync{{ LocalPath: "sancho", @@ -1047,7 +1044,7 @@ func TestLiveUpdateInFirstImageOfImageDependencyWithoutSync(t *testing.T) { } func TestLiveUpdateInSecondImageOfImageDependency(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) steps := []v1alpha1.LiveUpdateSync{{ LocalPath: "sancho", diff --git a/internal/engine/build_and_deployer_test.go b/internal/engine/build_and_deployer_test.go index b0bd3a6b5c..d2a43a3232 100644 --- a/internal/engine/build_and_deployer_test.go +++ b/internal/engine/build_and_deployer_test.go @@ -31,6 +31,7 @@ import ( "github.com/tilt-dev/wmclient/pkg/dirs" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/container" "github.com/tilt-dev/tilt/internal/dockercompose" "github.com/tilt-dev/tilt/internal/k8s/testyaml" @@ -66,7 +67,7 @@ var testContainerInfo = liveupdates.Container{ } func TestGKEDeploy(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) manifest := NewSanchoLiveUpdateManifest(f) targets := buildcontrol.BuildTargets(manifest) @@ -90,7 +91,7 @@ func TestGKEDeploy(t *testing.T) { } func TestDockerForMacDeploy(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) manifest := NewSanchoDockerBuildManifest(f) targets := buildcontrol.BuildTargets(manifest) @@ -114,7 +115,7 @@ func TestDockerForMacDeploy(t *testing.T) { } func TestYamlManifestDeploy(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) manifest := manifestbuilder.New(f, "some_yaml"). WithK8sYAML(testyaml.TracerYAML).Build() @@ -130,7 +131,7 @@ func TestYamlManifestDeploy(t *testing.T) { } func TestLiveUpdateTaskKilled(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) changed := f.WriteFile("a.txt", "a") @@ -156,7 +157,7 @@ func TestLiveUpdateTaskKilled(t *testing.T) { } func TestFallBackToImageDeploy(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) f.docker.SetExecError(errors.New("some random error")) @@ -177,7 +178,7 @@ func TestFallBackToImageDeploy(t *testing.T) { } func TestLiveUpdateFallbackMessagingRedirect(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) syncs := []v1alpha1.LiveUpdateSync{ {LocalPath: ".", ContainerPath: "/blah"}, @@ -210,7 +211,7 @@ func TestLiveUpdateFallbackMessagingRedirect(t *testing.T) { } func TestLiveUpdateFallbackMessagingUnexpectedError(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) f.docker.SetExecError(errors.New("some random error")) @@ -238,7 +239,7 @@ func TestLiveUpdateFallbackMessagingUnexpectedError(t *testing.T) { } func TestLiveUpdateTwice(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) manifest := manifestbuilder.New(f, "sancho"). WithK8sYAML(SanchoYAML). @@ -279,7 +280,7 @@ func TestLiveUpdateTwice(t *testing.T) { // Kill the pod after the first container update, // and make sure the next image build gets the right file updates. func TestLiveUpdateTwiceDeadPod(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) manifest := manifestbuilder.New(f, "sancho"). WithK8sYAML(SanchoYAML). @@ -321,7 +322,7 @@ func TestLiveUpdateTwiceDeadPod(t *testing.T) { } func TestIgnoredFiles(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) manifest := NewSanchoDockerBuildManifest(f) @@ -360,7 +361,7 @@ func TestIgnoredFiles(t *testing.T) { } func TestCustomBuild(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) sha := digest.Digest("sha256:11cd0eb38bc3ceb958ffb2f9bd70be3fb317ce7d255c8a4c3f4af30e298aa1aab") f.docker.Images["gcr.io/some-project-162817/sancho:tilt-build-1551202573"] = types.ImageInspect{ID: string(sha)} @@ -382,7 +383,7 @@ func TestCustomBuild(t *testing.T) { } func TestCustomBuildDeterministicTag(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) refStr := "gcr.io/some-project-162817/sancho:deterministic-tag" sha := digest.Digest("sha256:11cd0eb38bc3ceb958ffb2f9bd70be3fb317ce7d255c8a4c3f4af30e298aa1aab") f.docker.Images[refStr] = types.ImageInspect{ID: string(sha)} @@ -405,7 +406,7 @@ func TestCustomBuildDeterministicTag(t *testing.T) { } func TestContainerBuildMultiStage(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) manifest := NewSanchoLiveUpdateMultiStageManifest(f) targets := buildcontrol.BuildTargets(manifest) @@ -442,7 +443,7 @@ func TestContainerBuildMultiStage(t *testing.T) { } func TestDockerComposeImageBuild(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) manifest := NewSanchoLiveUpdateDCManifest(f) targets := buildcontrol.BuildTargets(manifest) @@ -459,7 +460,7 @@ func TestDockerComposeImageBuild(t *testing.T) { } func TestDockerComposeLiveUpdate(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeContainerd) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeContainerd) manifest := NewSanchoLiveUpdateDCManifest(f) targets := buildcontrol.BuildTargets(manifest) @@ -482,7 +483,7 @@ func TestDockerComposeLiveUpdate(t *testing.T) { } func TestReturnLastUnexpectedError(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) // next Docker build will throw an unexpected error -- this is one we want to return, // even if subsequent builders throw expected errors. @@ -497,7 +498,7 @@ func TestReturnLastUnexpectedError(t *testing.T) { // errors get logged by the upper, so make sure our builder isn't logging the error redundantly func TestDockerBuildErrorNotLogged(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) // next Docker build will throw an unexpected error -- this is one we want to return, // even if subsequent builders throw expected errors. @@ -514,7 +515,7 @@ func TestDockerBuildErrorNotLogged(t *testing.T) { } func TestLiveUpdateWithRunFailureReturnsContainerIDs(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) // LiveUpdate will failure with a RunStepFailure f.docker.SetExecError(userFailureErrDocker) @@ -547,7 +548,7 @@ func TestLiveUpdateWithRunFailureReturnsContainerIDs(t *testing.T) { } func TestLiveUpdateMultipleImagesSamePod(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) manifest, bs := multiImageLiveUpdateManifestAndBuildState(f) _, err := f.BuildAndDeploy(buildcontrol.BuildTargets(manifest), bs) @@ -571,7 +572,7 @@ func TestLiveUpdateMultipleImagesSamePod(t *testing.T) { } func TestOneLiveUpdateOneDockerBuildDoesImageBuild(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) sanchoTarg := NewSanchoLiveUpdateImageTarget(f) // first target = LiveUpdate sidecarTarg := NewSanchoSidecarDockerBuildImageTarget(f) // second target = DockerBuild @@ -610,7 +611,7 @@ func TestLiveUpdateMultipleImagesOneRunErrorExecutesRestOfLiveUpdatesAndDoesntIm if runtime.GOOS == "windows" { t.Skip("TODO(nick): fix this") } - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) // First LiveUpdate will simulate a failed Run step f.docker.ExecErrorsToThrow = []error{userFailureErrDocker} @@ -637,7 +638,7 @@ func TestLiveUpdateMultipleImagesOneRunErrorExecutesRestOfLiveUpdatesAndDoesntIm } func TestLiveUpdateMultipleImagesOneUpdateErrorFallsBackToImageBuild(t *testing.T) { - f := newBDFixture(t, k8s.EnvDockerDesktop, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductDockerDesktop, container.RuntimeDocker) // Second LiveUpdate will throw an error f.docker.ExecErrorsToThrow = []error{nil, fmt.Errorf("whelp ¯\\_(ツ)_/¯")} @@ -659,7 +660,7 @@ func TestLiveUpdateMultipleImagesOneUpdateErrorFallsBackToImageBuild(t *testing. } func TestLiveUpdateMultipleImagesOneWithUnsyncedChangeFileFallsBackToImageBuild(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) manifest, bs := multiImageLiveUpdateManifestAndBuildState(f) bs[manifest.ImageTargetAt(1).ID()].FilesChangedSet["/not/synced"] = true // changed file not in a sync --> fall back to image build @@ -675,7 +676,7 @@ func TestLiveUpdateMultipleImagesOneWithUnsyncedChangeFileFallsBackToImageBuild( } func TestLocalTargetDeploy(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) lt := model.NewLocalTarget("hello-world", model.ToHostCmd("echo hello world"), model.Cmd{}, nil) res, err := f.BuildAndDeploy([]model.TargetSpec{lt}, store.BuildStateSet{}) @@ -689,7 +690,7 @@ func TestLocalTargetDeploy(t *testing.T) { } func TestLocalTargetFailure(t *testing.T) { - f := newBDFixture(t, k8s.EnvGKE, container.RuntimeDocker) + f := newBDFixture(t, clusterid.ProductGKE, container.RuntimeDocker) lt := model.NewLocalTarget("hello-world", model.ToHostCmd("echo 'oh no' && exit 1"), model.Cmd{}, nil) res, err := f.BuildAndDeploy([]model.TargetSpec{lt}, store.BuildStateSet{}) @@ -775,11 +776,11 @@ type bdFixture struct { ctrlClient ctrlclient.Client } -func newBDFixture(t *testing.T, env k8s.Env, runtime container.Runtime) *bdFixture { +func newBDFixture(t *testing.T, env clusterid.Product, runtime container.Runtime) *bdFixture { return newBDFixtureWithUpdateMode(t, env, runtime, liveupdates.UpdateModeAuto) } -func newBDFixtureWithUpdateMode(t *testing.T, env k8s.Env, runtime container.Runtime, um liveupdates.UpdateMode) *bdFixture { +func newBDFixtureWithUpdateMode(t *testing.T, env clusterid.Product, runtime container.Runtime, um liveupdates.UpdateMode) *bdFixture { logs := new(bytes.Buffer) ctx, _, ta := testutils.ForkedCtxAndAnalyticsForTest(logs) ctx, cancel := context.WithCancel(ctx) diff --git a/internal/engine/buildcontrol/image_build_and_deployer.go b/internal/engine/buildcontrol/image_build_and_deployer.go index 0e2a5fb617..1c989bae23 100644 --- a/internal/engine/buildcontrol/image_build_and_deployer.go +++ b/internal/engine/buildcontrol/image_build_and_deployer.go @@ -11,6 +11,7 @@ import ( "k8s.io/apimachinery/pkg/types" ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/analytics" "github.com/tilt-dev/tilt/internal/build" "github.com/tilt-dev/tilt/internal/container" @@ -33,7 +34,7 @@ type KINDLoader interface { } type cmdKINDLoader struct { - env k8s.Env + env clusterid.Product clusterName k8s.ClusterName } @@ -41,7 +42,7 @@ func (kl *cmdKINDLoader) LoadToKIND(ctx context.Context, ref reference.NamedTagg // In Kind5, --name specifies the name of the cluster in the kubeconfig. // In Kind6, the -name parameter is prefixed with 'kind-' before being written to/read from the kubeconfig kindName := string(kl.clusterName) - if kl.env == k8s.EnvKIND6 { + if kl.env == clusterid.ProductKIND { kindName = strings.TrimPrefix(kindName, "kind-") } @@ -53,7 +54,7 @@ func (kl *cmdKINDLoader) LoadToKIND(ctx context.Context, ref reference.NamedTagg return cmd.Run() } -func NewKINDLoader(env k8s.Env, clusterName k8s.ClusterName) KINDLoader { +func NewKINDLoader(env clusterid.Product, clusterName k8s.ClusterName) KINDLoader { return &cmdKINDLoader{ env: env, clusterName: clusterName, @@ -64,7 +65,7 @@ type ImageBuildAndDeployer struct { db *build.DockerBuilder ib *ImageBuilder k8sClient k8s.Client - env k8s.Env + env clusterid.Product kubeContext k8s.KubeContext analytics *analytics.TiltAnalytics clock build.Clock @@ -77,7 +78,7 @@ func NewImageBuildAndDeployer( db *build.DockerBuilder, customBuilder *build.CustomBuilder, k8sClient k8s.Client, - env k8s.Env, + env clusterid.Product, kubeContext k8s.KubeContext, analytics *analytics.TiltAnalytics, c build.Clock, @@ -296,7 +297,7 @@ func (ibd *ImageBuildAndDeployer) push(ctx context.Context, ref reference.NamedT } func (ibd *ImageBuildAndDeployer) shouldUseKINDLoad(ctx context.Context, iTarg model.ImageTarget) bool { - isKIND := ibd.env == k8s.EnvKIND5 || ibd.env == k8s.EnvKIND6 + isKIND := ibd.env == clusterid.ProductKIND if !isKIND { return false } diff --git a/internal/engine/buildcontrol/image_build_and_deployer_test.go b/internal/engine/buildcontrol/image_build_and_deployer_test.go index ac7ad1eac3..05878b7b84 100644 --- a/internal/engine/buildcontrol/image_build_and_deployer_test.go +++ b/internal/engine/buildcontrol/image_build_and_deployer_test.go @@ -20,6 +20,7 @@ import ( ktypes "k8s.io/apimachinery/pkg/types" ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/container" "github.com/tilt-dev/tilt/internal/controllers/fake" "github.com/tilt-dev/tilt/internal/docker" @@ -40,7 +41,7 @@ import ( ) func TestDeployTwinImages(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) sancho := NewSanchoDockerBuildManifest(f) newK8sTarget := k8s.MustTarget("sancho", yaml.ConcatYAML(SanchoYAML, SanchoTwinYAML)). @@ -60,7 +61,7 @@ func TestDeployTwinImages(t *testing.T) { } func TestForceUpdate(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) m := NewSanchoDockerBuildManifest(f) @@ -76,7 +77,7 @@ func TestForceUpdate(t *testing.T) { } func TestForceUpdateDoesNotDeleteNamespace(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) m := manifestbuilder.New(f, "sancho"). WithK8sYAML(SanchoYAML + ` @@ -108,7 +109,7 @@ metadata: } func TestDeleteShouldHappenInReverseOrder(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) m := newK8sMultiEntityManifest("sancho") @@ -119,7 +120,7 @@ func TestDeleteShouldHappenInReverseOrder(t *testing.T) { } func TestDeployPodWithMultipleImages(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) iTarget1 := NewSanchoDockerBuildImageTarget(f) iTarget2 := NewSanchoSidecarDockerBuildImageTarget(f) @@ -148,7 +149,7 @@ func TestDeployPodWithMultipleImages(t *testing.T) { } func TestDeployPodWithMultipleLiveUpdateImages(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) iTarget1 := NewSanchoLiveUpdateImageTarget(f) iTarget2 := NewSanchoSidecarLiveUpdateImageTarget(f) @@ -178,7 +179,7 @@ func TestDeployPodWithMultipleLiveUpdateImages(t *testing.T) { } func TestNoImageTargets(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) targName := "some-k8s-manifest" specs := []model.TargetSpec{ @@ -204,7 +205,7 @@ func TestNoImageTargets(t *testing.T) { } func TestStatefulSetPodManagementPolicy(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) targName := "redis" @@ -237,7 +238,7 @@ func TestStatefulSetPodManagementPolicy(t *testing.T) { } func TestImageIsClean(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) manifest := NewSanchoDockerBuildManifest(f) iTargetID1 := manifest.ImageTargets[0].ID() @@ -258,7 +259,7 @@ func TestImageIsClean(t *testing.T) { } func TestImageIsDirtyAfterContainerBuild(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) manifest := NewSanchoDockerBuildManifest(f) iTargetID1 := manifest.ImageTargets[0].ID() @@ -281,7 +282,7 @@ func TestImageIsDirtyAfterContainerBuild(t *testing.T) { } func TestMultiStageDockerBuild(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) manifest := NewSanchoDockerBuildMultiStageManifest(f) _, err := f.BuildAndDeploy(BuildTargets(manifest), store.BuildStateSet{}) @@ -306,7 +307,7 @@ ENTRYPOINT /go/bin/sancho } func TestMultiStageDockerBuildPreservesSyntaxDirective(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) baseImage := model.MustNewImageTarget(SanchoBaseRef). WithDockerImage(v1alpha1.DockerImageSpec{ @@ -354,7 +355,7 @@ ENTRYPOINT /go/bin/sancho } func TestMultiStageDockerBuildWithFirstImageDirty(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) manifest := NewSanchoDockerBuildMultiStageManifest(f) iTargetID1 := manifest.ImageTargets[0].ID() @@ -389,7 +390,7 @@ ENTRYPOINT /go/bin/sancho } func TestMultiStageDockerBuildWithSecondImageDirty(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) manifest := NewSanchoDockerBuildMultiStageManifest(f) iTargetID1 := manifest.ImageTargets[0].ID() @@ -423,7 +424,7 @@ ENTRYPOINT /go/bin/sancho } func TestK8sUpsertTimeout(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) timeout := 123 * time.Second @@ -441,7 +442,7 @@ func TestK8sUpsertTimeout(t *testing.T) { } func TestKINDLoad(t *testing.T) { - f := newIBDFixture(t, k8s.EnvKIND6) + f := newIBDFixture(t, clusterid.ProductKIND) manifest := NewSanchoDockerBuildManifest(f) _, err := f.BuildAndDeploy(BuildTargets(manifest), store.BuildStateSet{}) @@ -455,7 +456,7 @@ func TestKINDLoad(t *testing.T) { } func TestDockerPushIfKINDAndClusterRef(t *testing.T) { - f := newIBDFixture(t, k8s.EnvKIND6) + f := newIBDFixture(t, clusterid.ProductKIND) manifest := NewSanchoDockerBuildManifest(f) iTarg := manifest.ImageTargetAt(0) @@ -478,7 +479,7 @@ func TestDockerPushIfKINDAndClusterRef(t *testing.T) { } func TestCustomBuildDisablePush(t *testing.T) { - f := newIBDFixture(t, k8s.EnvKIND6) + f := newIBDFixture(t, clusterid.ProductKIND) sha := digest.Digest("sha256:11cd0eb38bc3ceb958ffb2f9bd70be3fb317ce7d255c8a4c3f4af30e298aa1aab") f.docker.Images["gcr.io/some-project-162817/sancho:tilt-build"] = types.ImageInspect{ID: string(sha)} @@ -494,7 +495,7 @@ func TestCustomBuildDisablePush(t *testing.T) { } func TestCustomBuildSkipsLocalDocker(t *testing.T) { - f := newIBDFixture(t, k8s.EnvKIND6) + f := newIBDFixture(t, clusterid.ProductKIND) sha := digest.Digest("sha256:11cd0eb38bc3ceb958ffb2f9bd70be3fb317ce7d255c8a4c3f4af30e298aa1aab") f.docker.Images["gcr.io/some-project-162817/sancho:tilt-build"] = types.ImageInspect{ID: string(sha)} @@ -542,7 +543,7 @@ func TestBuildAndDeployUsesCorrectRef(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) if strings.Contains(test.name, "custom build") { sha := digest.Digest("sha256:11cd0eb38bc3ceb958ffb2f9bd70be3fb317ce7d255c8a4c3f4af30e298aa1aab") @@ -581,7 +582,7 @@ func TestBuildAndDeployUsesCorrectRef(t *testing.T) { } func TestDeployInjectImageEnvVar(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) manifest := NewSanchoManifestWithImageInEnvVar(f) _, err := f.BuildAndDeploy(BuildTargets(manifest), store.BuildStateSet{}) @@ -616,7 +617,7 @@ func TestDeployInjectImageEnvVar(t *testing.T) { } func TestDeployInjectsOverrideCommand(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) cmd := model.ToUnixCmd("./foo.sh bar") manifest := NewSanchoDockerBuildManifest(f) @@ -668,7 +669,7 @@ func (f *ibdFixture) firstPodTemplateSpecHash() k8s.PodTemplateSpecHash { } func TestDeployInjectsPodTemplateSpecHash(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) manifest := NewSanchoDockerBuildManifest(f) @@ -683,7 +684,7 @@ func TestDeployInjectsPodTemplateSpecHash(t *testing.T) { } func TestDeployPodTemplateSpecHashChangesWhenImageChanges(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) manifest := NewSanchoDockerBuildManifest(f) @@ -708,7 +709,7 @@ func TestDeployPodTemplateSpecHashChangesWhenImageChanges(t *testing.T) { } func TestDeployInjectOverrideCommandClearsOldCommandButNotArgs(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) cmd := model.ToUnixCmd("./foo.sh bar") manifest := NewSanchoDockerBuildManifestWithYaml(f, testyaml.SanchoYAMLWithCommand) @@ -740,7 +741,7 @@ func TestDeployInjectOverrideCommandClearsOldCommandButNotArgs(t *testing.T) { } func TestDeployInjectOverrideCommandAndArgs(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) cmd := model.ToUnixCmd("./foo.sh bar") manifest := NewSanchoDockerBuildManifestWithYaml(f, testyaml.SanchoYAMLWithCommand) @@ -773,7 +774,7 @@ func TestDeployInjectOverrideCommandAndArgs(t *testing.T) { } func TestCantInjectOverrideCommandWithoutContainer(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) // CRD YAML: we WILL successfully inject the new image ref, but can't inject // an override command for that image because it's not in a "container" block: @@ -795,7 +796,7 @@ func TestCantInjectOverrideCommandWithoutContainer(t *testing.T) { } func TestInjectOverrideCommandsMultipleImages(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) cmd1 := model.ToUnixCmd("./command1.sh foo") cmd2 := model.ToUnixCmd("./command2.sh bar baz") @@ -838,7 +839,7 @@ func TestInjectOverrideCommandsMultipleImages(t *testing.T) { } func TestIBDDeployUIDs(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) manifest := NewSanchoDockerBuildManifest(f) result, err := f.BuildAndDeploy(BuildTargets(manifest), store.BuildStateSet{}) @@ -852,7 +853,7 @@ func TestIBDDeployUIDs(t *testing.T) { } func TestDockerBuildTargetStage(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) iTarget := NewSanchoDockerBuildImageTarget(f) db := iTarget.BuildDetails.(model.DockerBuild) @@ -871,7 +872,7 @@ func TestDockerBuildTargetStage(t *testing.T) { } func TestDockerBuildStatus(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) iTarget := NewSanchoDockerBuildImageTarget(f) manifest := manifestbuilder.New(f, "sancho"). @@ -897,7 +898,7 @@ func TestDockerBuildStatus(t *testing.T) { } func TestCustomBuildStatus(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) sha := digest.Digest("sha256:11cd0eb38bc3ceb958ffb2f9bd70be3fb317ce7d255c8a4c3f4af30e298aa1aab") f.docker.Images["gcr.io/some-project-162817/sancho:tilt-build"] = types.ImageInspect{ID: string(sha)} @@ -930,7 +931,7 @@ func TestCustomBuildStatus(t *testing.T) { } func TestTwoManifestsWithCommonImage(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) m1, m2 := NewManifestsWithCommonAncestor(f) results1, err := f.BuildAndDeploy(BuildTargets(m1), store.BuildStateSet{}) @@ -950,7 +951,7 @@ func TestTwoManifestsWithCommonImage(t *testing.T) { } func TestTwoManifestsWithCommonImagePrebuilt(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) m1, _ := NewManifestsWithCommonAncestor(f) iTarget1 := m1.ImageTargets[0] @@ -970,7 +971,7 @@ func TestTwoManifestsWithCommonImagePrebuilt(t *testing.T) { } func TestTwoManifestsWithTwoCommonAncestors(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) m1, m2 := NewManifestsWithTwoCommonAncestors(f) results1, err := f.BuildAndDeploy(BuildTargets(m1), store.BuildStateSet{}) @@ -990,7 +991,7 @@ func TestTwoManifestsWithTwoCommonAncestors(t *testing.T) { } func TestTwoManifestsWithSameTwoImages(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) m1, m2 := NewManifestsWithSameTwoImages(f) results1, err := f.BuildAndDeploy(BuildTargets(m1), store.BuildStateSet{}) @@ -1009,7 +1010,7 @@ func TestTwoManifestsWithSameTwoImages(t *testing.T) { } func TestPlatformFromCluster(t *testing.T) { - f := newIBDFixture(t, k8s.EnvGKE) + f := newIBDFixture(t, clusterid.ProductGKE) f.upsert(&v1alpha1.Cluster{ ObjectMeta: metav1.ObjectMeta{Name: "default"}, @@ -1049,7 +1050,7 @@ type ibdFixture struct { ctrlClient ctrlclient.Client } -func newIBDFixture(t *testing.T, env k8s.Env) *ibdFixture { +func newIBDFixture(t *testing.T, env clusterid.Product) *ibdFixture { f := tempdir.NewTempDirFixture(t) dir := dirs.NewTiltDevDirAt(f.Path()) diff --git a/internal/engine/buildcontrol/wire.go b/internal/engine/buildcontrol/wire.go index 2b05fbfc45..60463cf3ce 100644 --- a/internal/engine/buildcontrol/wire.go +++ b/internal/engine/buildcontrol/wire.go @@ -14,6 +14,7 @@ import ( "github.com/tilt-dev/wmclient/pkg/dirs" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/analytics" "github.com/tilt-dev/tilt/internal/build" "github.com/tilt-dev/tilt/internal/containerupdate" @@ -58,7 +59,7 @@ func ProvideImageBuildAndDeployer( ctx context.Context, docker docker.Client, kClient k8s.Client, - env k8s.Env, + env clusterid.Product, kubeContext k8s.KubeContext, clusterEnv docker.ClusterEnv, dir *dirs.TiltDevDir, diff --git a/internal/engine/buildcontrol/wire_gen.go b/internal/engine/buildcontrol/wire_gen.go index 5bb0d87a3b..2ffabac244 100644 --- a/internal/engine/buildcontrol/wire_gen.go +++ b/internal/engine/buildcontrol/wire_gen.go @@ -13,6 +13,7 @@ import ( "github.com/jonboulle/clockwork" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/analytics" "github.com/tilt-dev/tilt/internal/build" "github.com/tilt-dev/tilt/internal/containerupdate" @@ -32,7 +33,7 @@ import ( // Injectors from wire.go: -func ProvideImageBuildAndDeployer(ctx context.Context, docker2 docker.Client, kClient k8s.Client, env k8s.Env, kubeContext k8s.KubeContext, clusterEnv docker.ClusterEnv, dir *dirs.TiltDevDir, clock build.Clock, kp KINDLoader, analytics2 *analytics.TiltAnalytics, ctrlclient client.Client, st store.RStore, execer localexec.Execer) (*ImageBuildAndDeployer, error) { +func ProvideImageBuildAndDeployer(ctx context.Context, docker2 docker.Client, kClient k8s.Client, env clusterid.Product, kubeContext k8s.KubeContext, clusterEnv docker.ClusterEnv, dir *dirs.TiltDevDir, clock build.Clock, kp KINDLoader, analytics2 *analytics.TiltAnalytics, ctrlclient client.Client, st store.RStore, execer localexec.Execer) (*ImageBuildAndDeployer, error) { labels := _wireLabelsValue dockerBuilder := build.NewDockerBuilder(docker2, labels) customBuilder := build.NewCustomBuilder(docker2, clock) diff --git a/internal/engine/upper_test.go b/internal/engine/upper_test.go index f6e9a77848..cdc97fe028 100644 --- a/internal/engine/upper_test.go +++ b/internal/engine/upper_test.go @@ -30,8 +30,7 @@ import ( "k8s.io/apimachinery/pkg/types" ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/tilt-dev/wmclient/pkg/analytics" - + "github.com/tilt-dev/clusterid" tiltanalytics "github.com/tilt-dev/tilt/internal/analytics" "github.com/tilt-dev/tilt/internal/cloud" "github.com/tilt-dev/tilt/internal/container" @@ -110,6 +109,7 @@ import ( "github.com/tilt-dev/tilt/pkg/model" "github.com/tilt-dev/tilt/pkg/model/logstore" proto_webview "github.com/tilt-dev/tilt/pkg/webview" + "github.com/tilt-dev/wmclient/pkg/analytics" ) var originalWD string @@ -3460,7 +3460,7 @@ func newTestFixture(t *testing.T, options ...fixtureOptions) *testFixture { } clock := clockwork.NewRealClock() - env := k8s.EnvDockerDesktop + env := clusterid.ProductDockerDesktop podSource := podlogstream.NewPodSource(ctx, kClient, v1alpha1.NewScheme(), clock) plsc := podlogstream.NewController(ctx, cdc, sch, st, kClient, podSource, clock) au := engineanalytics.NewAnalyticsUpdater(ta, engineanalytics.CmdTags{}, engineMode) diff --git a/internal/engine/wire.go b/internal/engine/wire.go index 28fd2cc062..e79c63cd62 100644 --- a/internal/engine/wire.go +++ b/internal/engine/wire.go @@ -15,6 +15,7 @@ import ( "github.com/tilt-dev/wmclient/pkg/dirs" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/analytics" "github.com/tilt-dev/tilt/internal/build" "github.com/tilt-dev/tilt/internal/container" @@ -56,7 +57,7 @@ func provideFakeBuildAndDeployer( docker docker.Client, kClient k8s.Client, dir *dirs.TiltDevDir, - env k8s.Env, + env clusterid.Product, updateMode liveupdates.UpdateModeFlag, dcc dockercompose.DockerComposeClient, clock build.Clock, @@ -90,16 +91,16 @@ func provideFakeK8sNamespace() k8s.Namespace { return "default" } -func provideFakeKubeContext(env k8s.Env) k8s.KubeContext { +func provideFakeKubeContext(env clusterid.Product) k8s.KubeContext { return k8s.KubeContext(string(env)) } // A simplified version of the normal calculation we do // about whether we can build direct to a cluser -func provideFakeDockerClusterEnv(c docker.Client, k8sEnv k8s.Env, kubeContext k8s.KubeContext, runtime container.Runtime) docker.ClusterEnv { +func provideFakeDockerClusterEnv(c docker.Client, k8sEnv clusterid.Product, kubeContext k8s.KubeContext, runtime container.Runtime) docker.ClusterEnv { env := c.Env() isDockerRuntime := runtime == container.RuntimeDocker - isLocalDockerCluster := k8sEnv == k8s.EnvMinikube || k8sEnv == k8s.EnvMicroK8s || k8sEnv == k8s.EnvDockerDesktop + isLocalDockerCluster := k8sEnv == clusterid.ProductMinikube || k8sEnv == clusterid.ProductMicroK8s || k8sEnv == clusterid.ProductDockerDesktop if isDockerRuntime && isLocalDockerCluster { env.BuildToKubeContexts = append(env.BuildToKubeContexts, string(kubeContext)) } diff --git a/internal/engine/wire_gen.go b/internal/engine/wire_gen.go index dc06faf803..cd6b218989 100644 --- a/internal/engine/wire_gen.go +++ b/internal/engine/wire_gen.go @@ -14,6 +14,7 @@ import ( "go.opentelemetry.io/otel/sdk/trace" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/analytics" "github.com/tilt-dev/tilt/internal/build" "github.com/tilt-dev/tilt/internal/container" @@ -37,7 +38,7 @@ import ( // Injectors from wire.go: -func provideFakeBuildAndDeployer(ctx context.Context, docker2 docker.Client, kClient k8s.Client, dir *dirs.TiltDevDir, env k8s.Env, updateMode liveupdates.UpdateModeFlag, dcc dockercompose.DockerComposeClient, clock build.Clock, kp buildcontrol.KINDLoader, analytics2 *analytics.TiltAnalytics, ctrlClient client.Client, st store.RStore, execer localexec.Execer) (buildcontrol.BuildAndDeployer, error) { +func provideFakeBuildAndDeployer(ctx context.Context, docker2 docker.Client, kClient k8s.Client, dir *dirs.TiltDevDir, env clusterid.Product, updateMode liveupdates.UpdateModeFlag, dcc dockercompose.DockerComposeClient, clock build.Clock, kp buildcontrol.KINDLoader, analytics2 *analytics.TiltAnalytics, ctrlClient client.Client, st store.RStore, execer localexec.Execer) (buildcontrol.BuildAndDeployer, error) { dockerUpdater := containerupdate.NewDockerUpdater(docker2) execUpdater := containerupdate.NewExecUpdater(kClient) kubeContext := provideFakeKubeContext(env) @@ -98,16 +99,16 @@ func provideFakeK8sNamespace() k8s.Namespace { return "default" } -func provideFakeKubeContext(env k8s.Env) k8s.KubeContext { +func provideFakeKubeContext(env clusterid.Product) k8s.KubeContext { return k8s.KubeContext(string(env)) } // A simplified version of the normal calculation we do // about whether we can build direct to a cluser -func provideFakeDockerClusterEnv(c docker.Client, k8sEnv k8s.Env, kubeContext k8s.KubeContext, runtime container.Runtime) docker.ClusterEnv { +func provideFakeDockerClusterEnv(c docker.Client, k8sEnv clusterid.Product, kubeContext k8s.KubeContext, runtime container.Runtime) docker.ClusterEnv { env := c.Env() isDockerRuntime := runtime == container.RuntimeDocker - isLocalDockerCluster := k8sEnv == k8s.EnvMinikube || k8sEnv == k8s.EnvMicroK8s || k8sEnv == k8s.EnvDockerDesktop + isLocalDockerCluster := k8sEnv == clusterid.ProductMinikube || k8sEnv == clusterid.ProductMicroK8s || k8sEnv == clusterid.ProductDockerDesktop if isDockerRuntime && isLocalDockerCluster { env.BuildToKubeContexts = append(env.BuildToKubeContexts, string(kubeContext)) } diff --git a/internal/k8s/client.go b/internal/k8s/client.go index 0fa1169756..71a57cce2c 100644 --- a/internal/k8s/client.go +++ b/internal/k8s/client.go @@ -39,6 +39,7 @@ import ( // Client auth plugins! They will auto-init if we import them. _ "k8s.io/client-go/plugin/pkg/client/auth" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/container" "github.com/tilt-dev/tilt/pkg/logger" ) @@ -144,7 +145,7 @@ type RESTMapper interface { type K8sClient struct { InformerSet - env Env + product clusterid.Product core apiv1.CoreV1Interface restConfig *rest.Config portForwardClient PortForwardClient @@ -166,14 +167,14 @@ var _ Client = &K8sClient{} func ProvideK8sClient( globalCtx context.Context, - env Env, + product clusterid.Product, maybeRESTConfig RESTConfigOrError, maybeClientset ClientsetOrError, pfClient PortForwardClient, configNamespace Namespace, mkClient MinikubeClient, clientLoader clientcmd.ClientConfig) Client { - if env == EnvNone { + if product == ProductNone { // No k8s, so no need to get any further configs return &explodingClient{err: fmt.Errorf("Kubernetes context not set in %s", clientLoader.ConfigAccess().GetLoadingPrecedence())} } @@ -190,8 +191,8 @@ func ProvideK8sClient( core := clientset.CoreV1() runtimeAsync := newRuntimeAsync(core) - registryAsync := newRegistryAsync(env, core, runtimeAsync) - nodeIPAsync := newNodeIPAsync(env, mkClient) + registryAsync := newRegistryAsync(product, core, runtimeAsync) + nodeIPAsync := newNodeIPAsync(product, mkClient) di, err := dynamic.NewForConfig(restConfig) if err != nil { @@ -215,7 +216,7 @@ func ProvideK8sClient( c := &K8sClient{ InformerSet: newInformerSet(clientset, di), - env: env, + product: product, core: core, restConfig: restConfig, portForwardClient: pfClient, diff --git a/internal/k8s/client_test.go b/internal/k8s/client_test.go index d66d4b4cf3..57092ad63d 100644 --- a/internal/k8s/client_test.go +++ b/internal/k8s/client_test.go @@ -27,6 +27,7 @@ import ( restfake "k8s.io/client-go/rest/fake" ktesting "k8s.io/client-go/testing" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/k8s/testyaml" "github.com/tilt-dev/tilt/internal/testutils" ) @@ -365,14 +366,14 @@ func newClientTestFixture(t *testing.T) *clientTestFixture { core := cs.CoreV1() dc := dynfake.NewSimpleDynamicClient(scheme.Scheme) runtimeAsync := newRuntimeAsync(core) - registryAsync := newRegistryAsync(EnvUnknown, core, runtimeAsync) + registryAsync := newRegistryAsync(clusterid.ProductUnknown, core, runtimeAsync) resourceClient := &fakeResourceClient{} ret.resourceClient = resourceClient ret.restClient = &restfake.RESTClient{} ret.client = K8sClient{ - env: EnvUnknown, + product: clusterid.ProductUnknown, core: core, portForwardClient: NewFakePortForwardClient(), discovery: fakeDiscovery{restClient: ret.restClient}, diff --git a/internal/k8s/env.go b/internal/k8s/env.go index 296e0157f9..51dc84524b 100644 --- a/internal/k8s/env.go +++ b/internal/k8s/env.go @@ -2,50 +2,15 @@ package k8s import ( "context" - "path/filepath" - "strings" - "github.com/mitchellh/go-homedir" "github.com/pkg/errors" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/tools/clientcmd/api" - "github.com/tilt-dev/tilt/internal/ospath" - "github.com/tilt-dev/tilt/pkg/logger" + "github.com/tilt-dev/clusterid" ) type ClusterName string -type Env string - -// TODO(nick): Port this to use ctlptl's cluster detection code. -const ( - EnvUnknown Env = "unknown" - EnvGKE Env = "gke" - EnvMinikube Env = "minikube" - EnvDockerDesktop Env = "docker-for-desktop" - EnvMicroK8s Env = "microk8s" - EnvCRC Env = "crc" - EnvKrucible Env = "krucible" - // Kind v0.6 substantially changed the protocol for detecting and pulling, - // so we represent them as two separate envs. - EnvKIND5 Env = "kind-0.5-" - EnvKIND6 Env = "kind-0.6+" - EnvK3D Env = "k3d" - EnvRancherDesktop Env = "rancher-desktop" - EnvNone Env = "none" // k8s not running (not neces. a problem, e.g. if using Tilt x Docker Compose) -) - -func (e Env) IsDevCluster() bool { - return e == EnvMinikube || - e == EnvDockerDesktop || - e == EnvMicroK8s || - e == EnvCRC || - e == EnvKIND5 || - e == EnvKIND6 || - e == EnvK3D || - e == EnvKrucible || - e == EnvRancherDesktop -} func ProvideKubeContext(config *api.Config) (KubeContext, error) { return KubeContext(config.CurrentContext), nil @@ -82,78 +47,31 @@ func ProvideClusterName(ctx context.Context, config *api.Config) ClusterName { return ClusterName(c.Cluster) } -func ProvideEnv(ctx context.Context, config *api.Config) Env { +const ProductNone = clusterid.Product("") + +func ProvideClusterProduct(ctx context.Context, config *api.Config) clusterid.Product { n := config.CurrentContext c, ok := config.Contexts[n] if !ok { if n == "" { - return EnvNone + return ProductNone } - return EnvUnknown + return clusterid.ProductUnknown } cn := c.Cluster cl := config.Clusters[cn] - if strings.HasPrefix(cn, string(EnvMinikube)) { - return EnvMinikube - } else if strings.HasPrefix(cn, "docker-for-desktop-cluster") || strings.HasPrefix(cn, "docker-desktop") { - return EnvDockerDesktop - } else if strings.HasPrefix(cn, string(EnvGKE)) { - // GKE cluster strings look like: - // gke_blorg-dev_us-central1-b_blorg - return EnvGKE - } else if cn == "kind" { - return EnvKIND5 - } else if strings.HasPrefix(cn, "kind-") { - // As of KinD 0.6.0, KinD uses a context name prefix - // https://github.com/kubernetes-sigs/kind/issues/1060 - return EnvKIND6 - } else if strings.HasPrefix(cn, "microk8s-cluster") { - return EnvMicroK8s - } else if strings.HasPrefix(cn, "api-crc-testing") { - return EnvCRC - } else if strings.HasPrefix(cn, "krucible-") { - return EnvKrucible - } else if strings.HasPrefix(cn, "k3d-") { - return EnvK3D - } else if strings.HasPrefix(cn, "rancher-desktop") { - return EnvRancherDesktop - } - - loc := c.LocationOfOrigin - homedir, err := homedir.Dir() - if err != nil { - logger.Get(ctx).Infof("Error loading homedir: %v", err) - return EnvUnknown - } - - // K3D 1.x had a special directory where the config lived. - // Newer versions use a prefix like every other project. - k3dDir := filepath.Join(homedir, ".config", "k3d") - if ospath.IsChild(k3dDir, loc) { - return EnvK3D - } + return clusterid.ProductFromContext(c, cl) +} - minikubeDir := filepath.Join(homedir, ".minikube") - if cl != nil && cl.CertificateAuthority != "" && - ospath.IsChild(minikubeDir, cl.CertificateAuthority) { - return EnvMinikube +// Convert the current cluster type to an analytics env, for backwards compatibility. +func AnalyticsEnv(p clusterid.Product) string { + if p == clusterid.ProductDockerDesktop { + return "docker-for-desktop" } - - // NOTE(nick): Users can set the KIND cluster name with `kind create cluster - // --name`. This makes the KIND cluster really hard to detect. - // - // We currently do it by assuming that KIND configs are always stored in a - // file named kind-config-*. - // - // KIND internally looks for its clusters with `docker ps` + filters, - // which might be a route to explore if this isn't robust enough. - // - // This is for old pre-0.6.0 versions of KinD - if strings.HasPrefix(filepath.Base(loc), "kind-config-") { - return EnvKIND5 + if p == clusterid.ProductKIND { + return "kind-0.6+" } - - return EnvUnknown + return string(p) } diff --git a/internal/k8s/env_test.go b/internal/k8s/env_test.go deleted file mode 100644 index 69923b454b..0000000000 --- a/internal/k8s/env_test.go +++ /dev/null @@ -1,156 +0,0 @@ -package k8s - -import ( - "context" - "path/filepath" - "testing" - - "github.com/mitchellh/go-homedir" - "github.com/stretchr/testify/assert" - "k8s.io/client-go/tools/clientcmd/api" -) - -type expectedConfig struct { - expected Env - input *api.Config -} - -func TestProvideEnv(t *testing.T) { - minikubeContexts := map[string]*api.Context{ - "minikube": &api.Context{ - Cluster: "minikube", - }, - } - minikubePrefixContexts := map[string]*api.Context{ - "minikube-dev-cluster-1": &api.Context{ - Cluster: "minikube-dev-cluster-1", - }, - } - dockerDesktopContexts := map[string]*api.Context{ - "docker-for-desktop": &api.Context{ - Cluster: "docker-for-desktop-cluster", - }, - } - dockerDesktopPrefixContexts := map[string]*api.Context{ - "docker-for-desktop-dev-cluster-1": &api.Context{ - Cluster: "docker-for-desktop-cluster-dev-cluster-1", - }, - } - dockerDesktopEdgeContexts := map[string]*api.Context{ - "docker-for-desktop": &api.Context{ - Cluster: "docker-desktop", - }, - } - dockerDesktopEdgePrefixContexts := map[string]*api.Context{ - "docker-for-desktop-dev-cluster-1": &api.Context{ - Cluster: "docker-desktop-dev-cluster-1", - }, - } - gkeContexts := map[string]*api.Context{ - "gke_blorg-dev_us-central1-b_blorg": &api.Context{ - Cluster: "gke_blorg-dev_us-central1-b_blorg", - }, - } - kind5Contexts := map[string]*api.Context{ - "kubernetes-admin@kind-1": &api.Context{ - Cluster: "kind", - }, - } - microK8sContexts := map[string]*api.Context{ - "microk8s": &api.Context{ - Cluster: "microk8s-cluster", - }, - } - microK8sPrefixContexts := map[string]*api.Context{ - "microk8s-dev-cluster-1": &api.Context{ - Cluster: "microk8s-cluster-dev-cluster-1", - }, - } - krucibleContexts := map[string]*api.Context{ - "krucible-c-74701fe1a05596b3": &api.Context{ - Cluster: "krucible-c-74701fe1a05596b3", - }, - } - crcContexts := map[string]*api.Context{ - "api-crc-testing": &api.Context{ - Cluster: "api-crc-testing", - }, - } - crcPrefixContexts := map[string]*api.Context{ - "api-crc-testing:6443": &api.Context{ - Cluster: "api-crc-testing:6443", - }, - } - - homedir, err := homedir.Dir() - assert.NoError(t, err) - k3dContexts := map[string]*api.Context{ - "default": &api.Context{ - LocationOfOrigin: filepath.Join(homedir, ".config", "k3d", "k3s-default", "kubeconfig.yaml"), - Cluster: "default", - }, - } - kind5NamedClusterContexts := map[string]*api.Context{ - "default": &api.Context{ - LocationOfOrigin: filepath.Join(homedir, ".kube", "kind-config-integration"), - Cluster: "integration", - }, - } - kind6Contexts := map[string]*api.Context{ - "kind-custom-name": &api.Context{ - Cluster: "kind-custom-name", - }, - } - minikubeCustomNameContexts := map[string]*api.Context{ - "custom-name": &api.Context{ - Cluster: "custom-name", - }, - } - minikubeCustomNameClusters := map[string]*api.Cluster{ - "custom-name": &api.Cluster{ - CertificateAuthority: filepath.Join(homedir, ".minikube", "ca.crt"), - }, - } - k3d3xContexts := map[string]*api.Context{ - "k3d-k3s-default": &api.Context{ - Cluster: "k3d-k3s-default", - }, - } - rancherDesktopContexts := map[string]*api.Context{ - "rancher-desktop": {Cluster: "rancher-desktop"}, - } - - table := []expectedConfig{ - {EnvNone, &api.Config{}}, - {EnvUnknown, &api.Config{CurrentContext: "aws"}}, - {EnvMinikube, &api.Config{CurrentContext: "minikube", Contexts: minikubeContexts}}, - {EnvMinikube, &api.Config{CurrentContext: "minikube-dev-cluster-1", Contexts: minikubePrefixContexts}}, - {EnvDockerDesktop, &api.Config{CurrentContext: "docker-for-desktop", Contexts: dockerDesktopContexts}}, - {EnvDockerDesktop, &api.Config{CurrentContext: "docker-for-desktop-dev-cluster-1", Contexts: dockerDesktopPrefixContexts}}, - {EnvDockerDesktop, &api.Config{CurrentContext: "docker-for-desktop", Contexts: dockerDesktopEdgeContexts}}, - {EnvDockerDesktop, &api.Config{CurrentContext: "docker-for-desktop-dev-cluster-1", Contexts: dockerDesktopEdgePrefixContexts}}, - {EnvGKE, &api.Config{CurrentContext: "gke_blorg-dev_us-central1-b_blorg", Contexts: gkeContexts}}, - {EnvKIND5, &api.Config{CurrentContext: "kubernetes-admin@kind-1", Contexts: kind5Contexts}}, - {EnvMicroK8s, &api.Config{CurrentContext: "microk8s", Contexts: microK8sContexts}}, - {EnvMicroK8s, &api.Config{CurrentContext: "microk8s-dev-cluster-1", Contexts: microK8sPrefixContexts}}, - {EnvCRC, &api.Config{CurrentContext: "api-crc-testing", Contexts: crcContexts}}, - {EnvCRC, &api.Config{CurrentContext: "api-crc-testing:6443", Contexts: crcPrefixContexts}}, - {EnvKrucible, &api.Config{CurrentContext: "krucible-c-74701fe1a05596b3", Contexts: krucibleContexts}}, - {EnvK3D, &api.Config{CurrentContext: "default", Contexts: k3dContexts}}, - {EnvKIND5, &api.Config{CurrentContext: "default", Contexts: kind5NamedClusterContexts}}, - {EnvKIND6, &api.Config{CurrentContext: "kind-custom-name", Contexts: kind6Contexts}}, - {EnvMinikube, &api.Config{CurrentContext: "custom-name", Contexts: minikubeCustomNameContexts, Clusters: minikubeCustomNameClusters}}, - {EnvUnknown, &api.Config{CurrentContext: "custom-name", Contexts: minikubeCustomNameContexts}}, - {EnvK3D, &api.Config{CurrentContext: "k3d-k3s-default", Contexts: k3d3xContexts}}, - {EnvRancherDesktop, &api.Config{CurrentContext: "rancher-desktop", Contexts: rancherDesktopContexts}}, - } - - for _, tt := range table { - t.Run(tt.input.CurrentContext, func(t *testing.T) { - actual := ProvideEnv(context.Background(), tt.input) - if actual != tt.expected { - t.Errorf("Expected %s, actual %s", tt.expected, actual) - } - }) - } -} diff --git a/internal/k8s/ip.go b/internal/k8s/ip.go index 26cfe47b7c..76c96ac352 100644 --- a/internal/k8s/ip.go +++ b/internal/k8s/ip.go @@ -4,6 +4,7 @@ import ( "context" "sync" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/pkg/logger" ) @@ -12,12 +13,12 @@ type NodeIP string type nodeIPAsync struct { mkClient MinikubeClient - env Env + env clusterid.Product once sync.Once nodeIP NodeIP } -func newNodeIPAsync(env Env, mkClient MinikubeClient) *nodeIPAsync { +func newNodeIPAsync(env clusterid.Product, mkClient MinikubeClient) *nodeIPAsync { return &nodeIPAsync{ env: env, mkClient: mkClient, @@ -25,7 +26,7 @@ func newNodeIPAsync(env Env, mkClient MinikubeClient) *nodeIPAsync { } func (a *nodeIPAsync) detectNodeIP(ctx context.Context) NodeIP { - if a.env != EnvMinikube { + if a.env != clusterid.ProductMinikube { return "" } nodeIP, err := a.mkClient.NodeIP(ctx) diff --git a/internal/k8s/registry.go b/internal/k8s/registry.go index eb30aa2560..0549a66066 100644 --- a/internal/k8s/registry.go +++ b/internal/k8s/registry.go @@ -10,6 +10,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" apiv1 "k8s.io/client-go/kubernetes/typed/core/v1" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/localregistry-go" "github.com/tilt-dev/tilt/internal/container" "github.com/tilt-dev/tilt/pkg/logger" @@ -44,14 +45,14 @@ func (s NaiveRuntimeSource) Runtime(ctx context.Context) container.Runtime { } type registryAsync struct { - env Env + env clusterid.Product core apiv1.CoreV1Interface runtimeSource RuntimeSource registry container.Registry once sync.Once } -func newRegistryAsync(env Env, core apiv1.CoreV1Interface, runtimeSource RuntimeSource) *registryAsync { +func newRegistryAsync(env clusterid.Product, core apiv1.CoreV1Interface, runtimeSource RuntimeSource) *registryAsync { return ®istryAsync{ env: env, core: core, @@ -174,7 +175,7 @@ func (r *registryAsync) Registry(ctx context.Context) container.Registry { } // Auto-infer the microk8s local registry. - if r.env == EnvMicroK8s { + if r.env == clusterid.ProductMicroK8s { reg := r.inferRegistryFromMicrok8s(ctx) if !reg.Empty() { r.registry = reg @@ -192,7 +193,7 @@ func (r *registryAsync) Registry(ctx context.Context) container.Registry { logger.Get(ctx).Warnf("You are running without a local image registry.\n"+ "Tilt can use the local registry to speed up builds.\n"+ "Instructions: %s", help) - } else if r.env == EnvKIND6 { + } else if r.env == clusterid.ProductKIND { logger.Get(ctx).Warnf("You are running Kind without a local image registry.\n" + "Tilt can use the local registry to speed up builds.\n" + "Instructions: https://github.com/tilt-dev/kind-local") diff --git a/internal/k8s/registry_test.go b/internal/k8s/registry_test.go index 4711c88c4e..62628cb111 100644 --- a/internal/k8s/registry_test.go +++ b/internal/k8s/registry_test.go @@ -8,6 +8,7 @@ import ( goruntime "runtime" "testing" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/container" "github.com/tilt-dev/tilt/pkg/logger" @@ -42,7 +43,7 @@ func TestRegistryFoundMicrok8s(t *testing.T) { }) core := cs.CoreV1() - registryAsync := newRegistryAsync(EnvMicroK8s, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) + registryAsync := newRegistryAsync(clusterid.ProductMicroK8s, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) registry := registryAsync.Registry(newLoggerCtx(os.Stdout)) assert.Equal(t, "localhost:32000", registry.Host) @@ -63,7 +64,7 @@ func TestRegistryFoundInTiltAnnotationsWithClusterHost(t *testing.T) { }) core := cs.CoreV1() - registryAsync := newRegistryAsync(EnvKIND6, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) + registryAsync := newRegistryAsync(clusterid.ProductKIND, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) registry := registryAsync.Registry(newLoggerCtx(os.Stdout)) assert.Equal(t, "localhost:5000", registry.Host) @@ -84,7 +85,7 @@ func TestRegistryFoundInKindAnnotations(t *testing.T) { }) core := cs.CoreV1() - registryAsync := newRegistryAsync(EnvKIND6, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) + registryAsync := newRegistryAsync(clusterid.ProductKIND, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) registry := registryAsync.Registry(newLoggerCtx(os.Stdout)) assert.Equal(t, "localhost:5000", registry.Host) @@ -107,7 +108,7 @@ data: require.NoError(t, err) core := cs.CoreV1() - registryAsync := newRegistryAsync(EnvKIND6, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) + registryAsync := newRegistryAsync(clusterid.ProductKIND, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) out := bytes.NewBuffer(nil) registry := registryAsync.Registry(newLoggerCtx(out)) @@ -134,7 +135,7 @@ data: require.NoError(t, err) core := cs.CoreV1() - registryAsync := newRegistryAsync(EnvKIND6, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) + registryAsync := newRegistryAsync(clusterid.ProductKIND, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) registry := registryAsync.Registry(newLoggerCtx(os.Stdout)) assert.Equal(t, "localhost:5000", registry.Host) @@ -144,7 +145,7 @@ data: func TestKINDWarning(t *testing.T) { cs := &fake.Clientset{} core := cs.CoreV1() - registryAsync := newRegistryAsync(EnvKIND6, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) + registryAsync := newRegistryAsync(clusterid.ProductKIND, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) out := bytes.NewBuffer(nil) registry := registryAsync.Registry(newLoggerCtx(out)) @@ -155,7 +156,7 @@ func TestKINDWarning(t *testing.T) { func TestK3DNoWarning(t *testing.T) { cs := &fake.Clientset{} core := cs.CoreV1() - registryAsync := newRegistryAsync(EnvK3D, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) + registryAsync := newRegistryAsync(clusterid.ProductK3D, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) out := bytes.NewBuffer(nil) registry := registryAsync.Registry(newLoggerCtx(out)) @@ -177,7 +178,7 @@ func TestRegistryFoundInLabelsWithLocalOnly(t *testing.T) { }) core := cs.CoreV1() - registryAsync := newRegistryAsync(EnvKIND6, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) + registryAsync := newRegistryAsync(clusterid.ProductKIND, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) registry := registryAsync.Registry(newLoggerCtx(os.Stdout)) assert.Equal(t, "localhost:5000", registry.Host) @@ -195,7 +196,7 @@ func TestRegistryNotFound(t *testing.T) { cs.AddReactor("*", "*", ktesting.ObjectReaction(tracker)) core := cs.CoreV1() - registryAsync := newRegistryAsync(EnvMicroK8s, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) + registryAsync := newRegistryAsync(clusterid.ProductMicroK8s, core, NewNaiveRuntimeSource(container.RuntimeContainerd)) out := bytes.NewBuffer(nil) registry := registryAsync.Registry(newLoggerCtx(out)) diff --git a/internal/k8s/watch_test.go b/internal/k8s/watch_test.go index 8e9c03a41a..010f426ede 100644 --- a/internal/k8s/watch_test.go +++ b/internal/k8s/watch_test.go @@ -29,6 +29,7 @@ import ( mfake "k8s.io/client-go/metadata/fake" ktesting "k8s.io/client-go/testing" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/testutils" ) @@ -445,7 +446,7 @@ func newWatchTestFixture(t *testing.T) *watchTestFixture { ret.kCli = &K8sClient{ InformerSet: newInformerSet(cs, dcs), - env: EnvUnknown, + product: clusterid.ProductUnknown, drm: fakeRESTMapper{}, dynamic: dcs, clientset: cs, diff --git a/internal/tiltfile/k8scontext/k8scontext.go b/internal/tiltfile/k8scontext/k8scontext.go index 42e58c1263..8e51edf232 100644 --- a/internal/tiltfile/k8scontext/k8scontext.go +++ b/internal/tiltfile/k8scontext/k8scontext.go @@ -5,6 +5,7 @@ import ( "go.starlark.net/starlark" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/k8s" "github.com/tilt-dev/tilt/internal/tiltfile/starkit" "github.com/tilt-dev/tilt/internal/tiltfile/value" @@ -16,10 +17,10 @@ import ( // Exposes an API for other plugins to get and validate the allowed k8s context. type Plugin struct { context k8s.KubeContext - env k8s.Env + env clusterid.Product } -func NewPlugin(context k8s.KubeContext, env k8s.Env) Plugin { +func NewPlugin(context k8s.KubeContext, env clusterid.Product) Plugin { return Plugin{ context: context, env: env, @@ -81,7 +82,7 @@ var _ starkit.StatefulPlugin = &Plugin{} type State struct { context k8s.KubeContext - env k8s.Env + env clusterid.Product allowed []k8s.KubeContext } @@ -109,7 +110,7 @@ func (s State) IsAllowed(tf *v1alpha1.Tiltfile) bool { return true } - if s.env == k8s.EnvNone || s.env.IsDevCluster() { + if s.env == k8s.ProductNone || s.env.IsDevCluster() { return true } diff --git a/internal/tiltfile/k8scontext/k8scontext_test.go b/internal/tiltfile/k8scontext/k8scontext_test.go index 8622d420ee..e9cd0834b5 100644 --- a/internal/tiltfile/k8scontext/k8scontext_test.go +++ b/internal/tiltfile/k8scontext/k8scontext_test.go @@ -5,12 +5,13 @@ import ( "github.com/stretchr/testify/assert" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/k8s" "github.com/tilt-dev/tilt/internal/tiltfile/starkit" ) func TestAllowK8sContext(t *testing.T) { - f := NewFixture(t, "gke-blorg", k8s.EnvGKE) + f := NewFixture(t, "gke-blorg", clusterid.ProductGKE) f.File("Tiltfile", ` allow_k8s_contexts('gke-blorg') `) @@ -25,7 +26,7 @@ allow_k8s_contexts('gke-blorg') } func TestForbidK8sContext(t *testing.T) { - f := NewFixture(t, "gke-blorg", k8s.EnvGKE) + f := NewFixture(t, "gke-blorg", clusterid.ProductGKE) f.File("Tiltfile", ` `) model, err := f.ExecFile("Tiltfile") @@ -37,6 +38,6 @@ func TestForbidK8sContext(t *testing.T) { assert.True(t, MustState(model).IsAllowed(f.Tiltfile())) } -func NewFixture(tb testing.TB, ctx k8s.KubeContext, env k8s.Env) *starkit.Fixture { +func NewFixture(tb testing.TB, ctx k8s.KubeContext, env clusterid.Product) *starkit.Fixture { return starkit.NewFixture(tb, NewPlugin(ctx, env)) } diff --git a/internal/tiltfile/tiltfile.go b/internal/tiltfile/tiltfile.go index c5e8d50a51..78e392341b 100644 --- a/internal/tiltfile/tiltfile.go +++ b/internal/tiltfile/tiltfile.go @@ -10,6 +10,7 @@ import ( "go.starlark.net/starlark" + "github.com/tilt-dev/clusterid" "github.com/tilt-dev/tilt/internal/analytics" "github.com/tilt-dev/tilt/internal/container" "github.com/tilt-dev/tilt/internal/controllers/apiset" @@ -103,7 +104,7 @@ func ProvideTiltfileLoader( webHost model.WebHost, execer localexec.Execer, fDefaults feature.Defaults, - env k8s.Env) TiltfileLoader { + env clusterid.Product) TiltfileLoader { return tiltfileLoader{ analytics: analytics, k8sContextPlugin: k8sContextPlugin, @@ -129,7 +130,7 @@ type tiltfileLoader struct { configPlugin *config.Plugin extensionPlugin *tiltextension.Plugin fDefaults feature.Defaults - env k8s.Env + env clusterid.Product } var _ TiltfileLoader = &tiltfileLoader{} @@ -265,7 +266,7 @@ func (tfl *tiltfileLoader) reportTiltfileLoaded( // env should really be a global tag, but there's a circular dependency // between the global tags and env initialization, so we add it manually. - tags["env"] = string(tfl.env) + tags["env"] = k8s.AnalyticsEnv(tfl.env) tags["tiltfile.changed"] = strconv.FormatBool(prevHashes.TiltfileSHA256 != "" && prevHashes.TiltfileSHA256 != currHashes.TiltfileSHA256) tags["allfiles.changed"] = strconv.FormatBool(prevHashes.AllFilesSHA256 != "" && prevHashes.AllFilesSHA256 != currHashes.AllFilesSHA256) @@ -281,7 +282,7 @@ func (tfl *tiltfileLoader) reportTiltfileLoaded( tfl.analytics.Timer("tiltfile.load", loadDur, nil) for ext := range pluginsLoaded { tags := map[string]string{ - "env": string(tfl.env), + "env": k8s.AnalyticsEnv(tfl.env), "ext_name": ext, } tfl.analytics.Incr("tiltfile.loaded.plugin", tags) diff --git a/internal/tiltfile/tiltfile_test.go b/internal/tiltfile/tiltfile_test.go index c7ac8975f2..c617c0476a 100644 --- a/internal/tiltfile/tiltfile_test.go +++ b/internal/tiltfile/tiltfile_test.go @@ -20,6 +20,7 @@ import ( "k8s.io/apimachinery/pkg/labels" ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/tilt-dev/clusterid" tiltanalytics "github.com/tilt-dev/tilt/internal/analytics" "github.com/tilt-dev/tilt/internal/container" "github.com/tilt-dev/tilt/internal/controllers/apis/liveupdate" @@ -4117,16 +4118,15 @@ func TestK8SContextAcceptance(t *testing.T) { for _, test := range []struct { name string contextName k8s.KubeContext - env k8s.Env + env clusterid.Product expectError bool expectedErrorSubstrings []string }{ - {"minikube", "minikube", k8s.EnvMinikube, false, nil}, - {"docker-for-desktop", "docker-for-desktop", k8s.EnvDockerDesktop, false, nil}, - {"kind", "KIND", k8s.EnvKIND6, false, nil}, - {"kind", "KIND", k8s.EnvKIND5, false, nil}, - {"gke", "gke", k8s.EnvGKE, true, []string{"'gke'", "If you're sure", "switch k8s contexts", "allow_k8s_contexts"}}, - {"allowed", "allowed-context", k8s.EnvGKE, false, nil}, + {"minikube", "minikube", clusterid.ProductMinikube, false, nil}, + {"docker-for-desktop", "docker-for-desktop", clusterid.ProductDockerDesktop, false, nil}, + {"kind", "KIND", clusterid.ProductKIND, false, nil}, + {"gke", "gke", clusterid.ProductGKE, true, []string{"'gke'", "If you're sure", "switch k8s contexts", "allow_k8s_contexts"}}, + {"allowed", "allowed-context", clusterid.ProductGKE, false, nil}, } { t.Run(test.name, func(t *testing.T) { f := newFixture(t) @@ -4163,7 +4163,7 @@ allow_k8s_contexts("allowed-context") f.setupFoo() f.k8sContext = "gke" - f.k8sEnv = k8s.EnvGKE + f.k8sEnv = clusterid.ProductGKE f.loadErrString("If you're sure", "switch k8s contexts", "allow_k8s_contexts") } @@ -4172,13 +4172,13 @@ func TestLocalObeysAllowedK8sContexts(t *testing.T) { for _, test := range []struct { name string contextName k8s.KubeContext - env k8s.Env + env clusterid.Product expectError bool expectedErrorSubstrings []string }{ - {"gke", "gke", k8s.EnvGKE, true, []string{"'gke'", "If you're sure", "switch k8s contexts", "allow_k8s_contexts"}}, - {"allowed", "allowed-context", k8s.EnvGKE, false, nil}, - {"docker-compose", "unknown", k8s.EnvNone, false, nil}, + {"gke", "gke", clusterid.ProductGKE, true, []string{"'gke'", "If you're sure", "switch k8s contexts", "allow_k8s_contexts"}}, + {"allowed", "allowed-context", clusterid.ProductGKE, false, nil}, + {"docker-compose", "unknown", k8s.ProductNone, false, nil}, } { t.Run(test.name, func(t *testing.T) { f := newFixture(t) @@ -5698,7 +5698,7 @@ type fixture struct { t *testing.T *tempdir.TempDirFixture k8sContext k8s.KubeContext - k8sEnv k8s.Env + k8sEnv clusterid.Product webHost model.WebHost ctrlclient ctrlclient.Client @@ -5747,7 +5747,7 @@ func newFixture(t *testing.T) *fixture { an: ma, ta: ta, k8sContext: "fake-context", - k8sEnv: k8s.EnvDockerDesktop, + k8sEnv: clusterid.ProductDockerDesktop, ctrlclient: ctrlclient, features: features, } diff --git a/vendor/github.com/tilt-dev/clusterid/.gitignore b/vendor/github.com/tilt-dev/clusterid/.gitignore new file mode 100644 index 0000000000..66fd13c903 --- /dev/null +++ b/vendor/github.com/tilt-dev/clusterid/.gitignore @@ -0,0 +1,15 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ diff --git a/vendor/github.com/tilt-dev/clusterid/LICENSE b/vendor/github.com/tilt-dev/clusterid/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/vendor/github.com/tilt-dev/clusterid/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/tilt-dev/clusterid/Makefile b/vendor/github.com/tilt-dev/clusterid/Makefile new file mode 100644 index 0000000000..a410b0739a --- /dev/null +++ b/vendor/github.com/tilt-dev/clusterid/Makefile @@ -0,0 +1,14 @@ +GOPATH = $(shell go env GOPATH) + +.PHONY: test golangci-lint + +test: + go test -timeout 30s -v ./... + +.PHONY: golangci-lint +golangci-lint: $(GOLANGCILINT) + $(GOPATH)/bin/golangci-lint run --verbose + +$(GOLANGCILINT): + (cd /; GO111MODULE=on GOPROXY="direct" GOSUMDB=off go get github.com/golangci/golangci-lint/cmd/golangci-lint@v1.30.0) + diff --git a/vendor/github.com/tilt-dev/clusterid/README.md b/vendor/github.com/tilt-dev/clusterid/README.md new file mode 100644 index 0000000000..8822b000d4 --- /dev/null +++ b/vendor/github.com/tilt-dev/clusterid/README.md @@ -0,0 +1,26 @@ +# clusterid + +[![Build Status](https://circleci.com/gh/tilt-dev/clusterid/tree/main.svg?style=shield)](https://circleci.com/gh/tilt-dev/clusterid) +[![GoDoc](https://godoc.org/github.com/tilt-dev/clusterid?status.svg)](https://pkg.go.dev/github.com/tilt-dev/clusterid) + +A small Kubernetes cluster detection library. + +## Why? + +The [Tilt](https://github.com/tilt-dev/tilt) project interacts with +many different types of local development clusters. + +These clusters sometimes have machine-readable ways to determine +what features they support, but more often they do not. + +This library uses some simple heuristics to figure out what +kind of cluster we're talking to, to figure out what features +a cluster might support. + +## License + +Copyright 2022 Windmill Engineering + +Licensed under [the Apache License, Version 2.0](LICENSE) + + diff --git a/vendor/github.com/tilt-dev/clusterid/product.go b/vendor/github.com/tilt-dev/clusterid/product.go new file mode 100644 index 0000000000..ccdcecaf0b --- /dev/null +++ b/vendor/github.com/tilt-dev/clusterid/product.go @@ -0,0 +1,113 @@ +package clusterid + +import ( + "path/filepath" + "strings" + + "github.com/mitchellh/go-homedir" + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" +) + +// Enum of possible values for cluster.product +// +// Named in honor of the product component of the user-agent string, +// which we hope isn't foreshadowing. +type Product string + +func (p Product) DefaultClusterName() string { + if p == ProductKIND { + return "kind-kind" + } + if p == ProductK3D { + return "k3d-k3s-default" + } + return string(p) +} + +func (p Product) String() string { return string(p) } + +const ( + ProductUnknown Product = "unknown" + ProductGKE Product = "gke" + ProductMinikube Product = "minikube" + ProductDockerDesktop Product = "docker-desktop" + ProductMicroK8s Product = "microk8s" + ProductCRC Product = "crc" + ProductKrucible Product = "krucible" + ProductKIND Product = "kind" + ProductK3D Product = "k3d" + ProductRancherDesktop Product = "rancher-desktop" +) + +func (e Product) IsDevCluster() bool { + return e == ProductMinikube || + e == ProductDockerDesktop || + e == ProductMicroK8s || + e == ProductCRC || + e == ProductKIND || + e == ProductK3D || + e == ProductKrucible || + e == ProductRancherDesktop +} + +func ProductFromContext(c *clientcmdapi.Context, cl *clientcmdapi.Cluster) Product { + cn := c.Cluster + if strings.HasPrefix(cn, string(ProductMinikube)) { + return ProductMinikube + } else if strings.HasPrefix(cn, "docker-for-desktop-cluster") || strings.HasPrefix(cn, "docker-desktop") { + return ProductDockerDesktop + } else if strings.HasPrefix(cn, string(ProductGKE)) { + // GKE cluster strings look like: + // gke_blorg-dev_us-central1-b_blorg + return ProductGKE + } else if cn == "kind" { + return ProductKIND + } else if strings.HasPrefix(cn, "kind-") { + // As of KinD 0.6.0, KinD uses a context name prefix + // https://github.com/kubernetes-sigs/kind/issues/1060 + return ProductKIND + } else if strings.HasPrefix(cn, "microk8s-cluster") { + return ProductMicroK8s + } else if strings.HasPrefix(cn, "api-crc-testing") { + return ProductCRC + } else if strings.HasPrefix(cn, "krucible-") { + return ProductKrucible + } else if strings.HasPrefix(cn, "k3d-") { + return ProductK3D + } else if strings.HasPrefix(cn, "rancher-desktop") { + return ProductRancherDesktop + } + + loc := c.LocationOfOrigin + homedir, err := homedir.Dir() + if err != nil { + return ProductUnknown + } + + k3dDir := filepath.Join(homedir, ".config", "k3d") + if strings.HasPrefix(loc, k3dDir+string(filepath.Separator)) { + return ProductK3D + } + + minikubeDir := filepath.Join(homedir, ".minikube") + if cl != nil && cl.CertificateAuthority != "" && + strings.HasPrefix(cl.CertificateAuthority, minikubeDir+string(filepath.Separator)) { + return ProductMinikube + } + + // NOTE(nick): Users can set the KIND cluster name with `kind create cluster + // --name`. This makes the KIND cluster really hard to detect. + // + // We currently do it by assuming that KIND configs are always stored in a + // file named kind-config-*. + // + // KIND internally looks for its clusters with `docker ps` + filters, + // which might be a route to explore if this isn't robust enough. + // + // This is for old pre-0.6.0 versions of KinD + if strings.HasPrefix(filepath.Base(loc), "kind-config-") { + return ProductKIND + } + + return ProductUnknown +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 28bb09042f..1ee0222321 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -642,6 +642,9 @@ github.com/theupdateframework/notary/tuf/data github.com/theupdateframework/notary/tuf/signed github.com/theupdateframework/notary/tuf/utils github.com/theupdateframework/notary/tuf/validation +# github.com/tilt-dev/clusterid v0.1.2 +## explicit; go 1.17 +github.com/tilt-dev/clusterid # github.com/tilt-dev/dockerignore v0.1.1 ## explicit; go 1.16 github.com/tilt-dev/dockerignore @@ -1137,7 +1140,7 @@ k8s.io/api/storage/v1beta1 k8s.io/apiextensions-apiserver/pkg/apis/apiextensions k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1 k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1 -# k8s.io/apimachinery v0.23.0 => github.com/tilt-dev/apimachinery v0.23.0-tilt-20211221 +# k8s.io/apimachinery v0.23.5 => github.com/tilt-dev/apimachinery v0.23.0-tilt-20211221 ## explicit; go 1.16 k8s.io/apimachinery/pkg/api/equality k8s.io/apimachinery/pkg/api/errors @@ -1885,7 +1888,7 @@ sigs.k8s.io/kustomize/kyaml/yaml/merge2 sigs.k8s.io/kustomize/kyaml/yaml/merge3 sigs.k8s.io/kustomize/kyaml/yaml/schema sigs.k8s.io/kustomize/kyaml/yaml/walk -# sigs.k8s.io/structured-merge-diff/v4 v4.2.0 +# sigs.k8s.io/structured-merge-diff/v4 v4.2.1 ## explicit; go 1.13 sigs.k8s.io/structured-merge-diff/v4/fieldpath sigs.k8s.io/structured-merge-diff/v4/merge diff --git a/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/merge.go b/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/merge.go index afec9f3cfd..75244ef646 100644 --- a/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/merge.go +++ b/vendor/sigs.k8s.io/structured-merge-diff/v4/typed/merge.go @@ -17,8 +17,6 @@ limitations under the License. package typed import ( - "math" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" "sigs.k8s.io/structured-merge-diff/v4/schema" "sigs.k8s.io/structured-merge-diff/v4/value" @@ -170,74 +168,94 @@ func (w *mergingWalker) visitListItems(t *schema.List, lhs, rhs value.List) (err if lhs != nil { lLen = lhs.Length() } - out := make([]interface{}, 0, int(math.Max(float64(rLen), float64(lLen)))) + outLen := lLen + if outLen < rLen { + outLen = rLen + } + out := make([]interface{}, 0, outLen) + + rhsOrder, observedRHS, rhsErrs := w.indexListPathElements(t, rhs) + errs = append(errs, rhsErrs...) + lhsOrder, observedLHS, lhsErrs := w.indexListPathElements(t, lhs) + errs = append(errs, lhsErrs...) + + sharedOrder := make([]*fieldpath.PathElement, 0, rLen) + for i := range rhsOrder { + pe := &rhsOrder[i] + if _, ok := observedLHS.Get(*pe); ok { + sharedOrder = append(sharedOrder, pe) + } + } - lhsOrder := make([]fieldpath.PathElement, 0, lLen) + var nextShared *fieldpath.PathElement + if len(sharedOrder) > 0 { + nextShared = sharedOrder[0] + sharedOrder = sharedOrder[1:] + } - // First, collect all LHS children. - observedLHS := fieldpath.MakePathElementValueMap(lLen) - if lhs != nil { - for i := 0; i < lhs.Length(); i++ { - child := lhs.At(i) - pe, err := listItemToPathElement(w.allocator, w.schema, t, i, child) - if err != nil { - errs = append(errs, errorf("lhs: element %v: %v", i, err.Error())...) - // If we can't construct the path element, we can't - // even report errors deeper in the schema, so bail on - // this element. + lLen, rLen = len(lhsOrder), len(rhsOrder) + for lI, rI := 0, 0; lI < lLen || rI < rLen; { + if lI < lLen && rI < rLen { + pe := lhsOrder[lI] + if pe.Equals(rhsOrder[rI]) { + // merge LHS & RHS items + lChild, _ := observedLHS.Get(pe) + rChild, _ := observedRHS.Get(pe) + mergeOut, errs := w.mergeListItem(t, pe, lChild, rChild) + errs = append(errs, errs...) + if mergeOut != nil { + out = append(out, *mergeOut) + } + lI++ + rI++ + + nextShared = nil + if len(sharedOrder) > 0 { + nextShared = sharedOrder[0] + sharedOrder = sharedOrder[1:] + } continue } - if _, ok := observedLHS.Get(pe); ok { - errs = append(errs, errorf("lhs: duplicate entries for key %v", pe.String())...) - } - observedLHS.Insert(pe, child) - lhsOrder = append(lhsOrder, pe) - } - } - - // Then merge with RHS children. - observedRHS := fieldpath.MakePathElementSet(rLen) - if rhs != nil { - for i := 0; i < rhs.Length(); i++ { - child := rhs.At(i) - pe, err := listItemToPathElement(w.allocator, w.schema, t, i, child) - if err != nil { - errs = append(errs, errorf("rhs: element %v: %v", i, err.Error())...) - // If we can't construct the path element, we can't - // even report errors deeper in the schema, so bail on - // this element. + if _, ok := observedRHS.Get(pe); ok && nextShared != nil && !nextShared.Equals(lhsOrder[lI]) { + // shared item, but not the one we want in this round + lI++ continue } - if observedRHS.Has(pe) { - errs = append(errs, errorf("rhs: duplicate entries for key %v", pe.String())...) + } + if lI < lLen { + pe := lhsOrder[lI] + if _, ok := observedRHS.Get(pe); !ok { + // take LHS item + lChild, _ := observedLHS.Get(pe) + mergeOut, errs := w.mergeListItem(t, pe, lChild, nil) + errs = append(errs, errs...) + if mergeOut != nil { + out = append(out, *mergeOut) + } + lI++ continue } - observedRHS.Insert(pe) - w2 := w.prepareDescent(pe, t.ElementType) - w2.rhs = child - if lchild, ok := observedLHS.Get(pe); ok { - w2.lhs = lchild + } + if rI < rLen { + // Take the RHS item, merge with matching LHS item if possible + pe := rhsOrder[rI] + lChild, _ := observedLHS.Get(pe) // may be nil + rChild, _ := observedRHS.Get(pe) + mergeOut, errs := w.mergeListItem(t, pe, lChild, rChild) + errs = append(errs, errs...) + if mergeOut != nil { + out = append(out, *mergeOut) } - errs = append(errs, w2.merge(pe.String)...) - if w2.out != nil { - out = append(out, *w2.out) + rI++ + // Advance nextShared, if we are merging nextShared. + if nextShared != nil && nextShared.Equals(pe) { + nextShared = nil + if len(sharedOrder) > 0 { + nextShared = sharedOrder[0] + sharedOrder = sharedOrder[1:] + } } - w.finishDescent(w2) - } - } - - for _, pe := range lhsOrder { - if observedRHS.Has(pe) { - continue - } - value, _ := observedLHS.Get(pe) - w2 := w.prepareDescent(pe, t.ElementType) - w2.lhs = value - errs = append(errs, w2.merge(pe.String)...) - if w2.out != nil { - out = append(out, *w2.out) } - w.finishDescent(w2) } if len(out) > 0 { @@ -248,6 +266,46 @@ func (w *mergingWalker) visitListItems(t *schema.List, lhs, rhs value.List) (err return errs } +func (w *mergingWalker) indexListPathElements(t *schema.List, list value.List) ([]fieldpath.PathElement, fieldpath.PathElementValueMap, ValidationErrors) { + var errs ValidationErrors + length := 0 + if list != nil { + length = list.Length() + } + observed := fieldpath.MakePathElementValueMap(length) + pes := make([]fieldpath.PathElement, 0, length) + for i := 0; i < length; i++ { + child := list.At(i) + pe, err := listItemToPathElement(w.allocator, w.schema, t, i, child) + if err != nil { + errs = append(errs, errorf("element %v: %v", i, err.Error())...) + // If we can't construct the path element, we can't + // even report errors deeper in the schema, so bail on + // this element. + continue + } + if _, found := observed.Get(pe); found { + errs = append(errs, errorf("duplicate entries for key %v", pe.String())...) + continue + } + observed.Insert(pe, child) + pes = append(pes, pe) + } + return pes, observed, errs +} + +func (w *mergingWalker) mergeListItem(t *schema.List, pe fieldpath.PathElement, lChild, rChild value.Value) (out *interface{}, errs ValidationErrors) { + w2 := w.prepareDescent(pe, t.ElementType) + w2.lhs = lChild + w2.rhs = rChild + errs = append(errs, w2.merge(pe.String)...) + if w2.out != nil { + out = w2.out + } + w.finishDescent(w2) + return +} + func (w *mergingWalker) derefList(prefix string, v value.Value) (value.List, ValidationErrors) { if v == nil { return nil, nil