github.com/vtuson/helm@v2.8.2+incompatible/pkg/helm/portforwarder/portforwarder.go (about)

     1  /*
     2  Copyright 2016 The Kubernetes Authors All rights reserved.
     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  )
    31  
    32  var (
    33  	tillerPodLabels = labels.Set{"app": "helm", "name": "tiller"}
    34  )
    35  
    36  // New creates a new and initialized tunnel.
    37  func New(namespace string, client kubernetes.Interface, config *rest.Config) (*kube.Tunnel, error) {
    38  	podName, err := GetTillerPodName(client.CoreV1(), namespace)
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  	const tillerPort = 44134
    43  	t := kube.NewTunnel(client.CoreV1().RESTClient(), config, namespace, podName, tillerPort)
    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  func getFirstRunningPod(client corev1.PodsGetter, namespace string, selector labels.Selector) (*v1.Pod, error) {
    58  	options := metav1.ListOptions{LabelSelector: selector.String()}
    59  	pods, err := client.Pods(namespace).List(options)
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  	if len(pods.Items) < 1 {
    64  		return nil, fmt.Errorf("could not find tiller")
    65  	}
    66  	for _, p := range pods.Items {
    67  		if isPodReady(&p) {
    68  			return &p, nil
    69  		}
    70  	}
    71  	return nil, fmt.Errorf("could not find a ready tiller pod")
    72  }