github.com/cloudposse/helm@v2.2.3+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/kubernetes/pkg/api"
    23  	"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
    24  	"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion"
    25  	"k8s.io/kubernetes/pkg/client/restclient"
    26  	"k8s.io/kubernetes/pkg/labels"
    27  
    28  	"k8s.io/helm/pkg/kube"
    29  )
    30  
    31  // New creates a new and initialized tunnel.
    32  func New(namespace string, client *internalclientset.Clientset, config *restclient.Config) (*kube.Tunnel, error) {
    33  	podName, err := getTillerPodName(client.Core(), namespace)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	const tillerPort = 44134
    38  	t := kube.NewTunnel(client.Core().RESTClient(), config, namespace, podName, tillerPort)
    39  	return t, t.ForwardPort()
    40  }
    41  
    42  func getTillerPodName(client internalversion.PodsGetter, namespace string) (string, error) {
    43  	// TODO use a const for labels
    44  	selector := labels.Set{"app": "helm", "name": "tiller"}.AsSelector()
    45  	pod, err := getFirstRunningPod(client, namespace, selector)
    46  	if err != nil {
    47  		return "", err
    48  	}
    49  	return pod.ObjectMeta.GetName(), nil
    50  }
    51  
    52  func getFirstRunningPod(client internalversion.PodsGetter, namespace string, selector labels.Selector) (*api.Pod, error) {
    53  	options := api.ListOptions{LabelSelector: selector}
    54  	pods, err := client.Pods(namespace).List(options)
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  	if len(pods.Items) < 1 {
    59  		return nil, fmt.Errorf("could not find tiller")
    60  	}
    61  	for _, p := range pods.Items {
    62  		if api.IsPodReady(&p) {
    63  			return &p, nil
    64  		}
    65  	}
    66  	return nil, fmt.Errorf("could not find a ready tiller pod")
    67  }