github.com/sdbaiguanghe/helm@v2.16.7+incompatible/pkg/helm/portforwarder/portforwarder.go (about) 1 /* 2 Copyright The Helm Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package portforwarder 18 19 import ( 20 "fmt" 21 22 "k8s.io/api/core/v1" 23 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 24 "k8s.io/apimachinery/pkg/labels" 25 "k8s.io/client-go/kubernetes" 26 corev1 "k8s.io/client-go/kubernetes/typed/core/v1" 27 "k8s.io/client-go/rest" 28 29 "k8s.io/helm/pkg/kube" 30 "k8s.io/helm/pkg/tiller/environment" 31 ) 32 33 var ( 34 tillerPodLabels = labels.Set{"app": "helm", "name": "tiller"} 35 ) 36 37 // New creates a new and initialized tunnel. 38 func New(namespace string, client kubernetes.Interface, config *rest.Config) (*kube.Tunnel, error) { 39 podName, err := GetTillerPodName(client.CoreV1(), namespace) 40 if err != nil { 41 return nil, err 42 } 43 t := kube.NewTunnel(client.CoreV1().RESTClient(), config, namespace, podName, environment.DefaultTillerPort) 44 return t, t.ForwardPort() 45 } 46 47 // GetTillerPodName fetches the name of tiller pod running in the given namespace. 48 func GetTillerPodName(client corev1.PodsGetter, namespace string) (string, error) { 49 selector := tillerPodLabels.AsSelector() 50 pod, err := getFirstRunningPod(client, namespace, selector) 51 if err != nil { 52 return "", err 53 } 54 return pod.ObjectMeta.GetName(), nil 55 } 56 57 // GetTillerPodImage fetches the image of tiller pod running in the given namespace. 58 func GetTillerPodImage(client corev1.PodsGetter, namespace string) (string, error) { 59 selector := tillerPodLabels.AsSelector() 60 pod, err := getFirstRunningPod(client, namespace, selector) 61 if err != nil { 62 return "", err 63 } 64 for _, c := range pod.Spec.Containers { 65 if c.Name == "tiller" { 66 return c.Image, nil 67 } 68 } 69 return "", fmt.Errorf("could not find a tiller pod") 70 } 71 72 func getFirstRunningPod(client corev1.PodsGetter, namespace string, selector labels.Selector) (*v1.Pod, error) { 73 options := metav1.ListOptions{LabelSelector: selector.String()} 74 pods, err := client.Pods(namespace).List(options) 75 if err != nil { 76 return nil, err 77 } 78 if len(pods.Items) < 1 { 79 return nil, fmt.Errorf("could not find tiller") 80 } 81 for _, p := range pods.Items { 82 if isPodReady(&p) { 83 return &p, nil 84 } 85 } 86 return nil, fmt.Errorf("could not find a ready tiller pod") 87 }