2 Star 1 Fork 3

Helm/helm

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
tunnel.go 2.77 KB
一键复制 编辑 原始数据 按行查看 历史
/*
Copyright 2016 The Kubernetes Authors All rights reserved.
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.
*/
package kube
import (
"fmt"
"io"
"io/ioutil"
"net"
"strconv"
"k8s.io/kubernetes/pkg/client/restclient"
"k8s.io/kubernetes/pkg/client/unversioned/portforward"
"k8s.io/kubernetes/pkg/client/unversioned/remotecommand"
)
// Tunnel describes a ssh-like tunnel to a kubernetes pod
type Tunnel struct {
Local int
Remote int
Namespace string
PodName string
Out io.Writer
stopChan chan struct{}
readyChan chan struct{}
config *restclient.Config
client *restclient.RESTClient
}
// NewTunnel creates a new tunnel
func NewTunnel(client *restclient.RESTClient, config *restclient.Config, namespace, podName string, remote int) *Tunnel {
return &Tunnel{
config: config,
client: client,
Namespace: namespace,
PodName: podName,
Remote: remote,
stopChan: make(chan struct{}, 1),
readyChan: make(chan struct{}, 1),
Out: ioutil.Discard,
}
}
// Close disconnects a tunnel connection
func (t *Tunnel) Close() {
close(t.stopChan)
close(t.readyChan)
}
// ForwardPort opens a tunnel to a kubernetes pod
func (t *Tunnel) ForwardPort() error {
// Build a url to the portforward endpoint
// example: http://localhost:8080/api/v1/namespaces/helm/pods/tiller-deploy-9itlq/portforward
u := t.client.Post().
Resource("pods").
Namespace(t.Namespace).
Name(t.PodName).
SubResource("portforward").URL()
dialer, err := remotecommand.NewExecutor(t.config, "POST", u)
if err != nil {
return err
}
local, err := getAvailablePort()
if err != nil {
return fmt.Errorf("could not find an available port: %s", err)
}
t.Local = local
ports := []string{fmt.Sprintf("%d:%d", t.Local, t.Remote)}
pf, err := portforward.New(dialer, ports, t.stopChan, t.readyChan, t.Out, t.Out)
if err != nil {
return err
}
errChan := make(chan error)
go func() {
errChan <- pf.ForwardPorts()
}()
select {
case err = <-errChan:
return fmt.Errorf("Error forwarding ports: %v\n", err)
case <-pf.Ready:
return nil
}
}
func getAvailablePort() (int, error) {
l, err := net.Listen("tcp", ":0")
if err != nil {
return 0, err
}
defer l.Close()
_, p, err := net.SplitHostPort(l.Addr().String())
port, err := strconv.Atoi(p)
if err != nil {
return 0, err
}
return port, err
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zyxjob/helm.git
git@gitee.com:zyxjob/helm.git
zyxjob
helm
helm
v2.0.0-beta.1

搜索帮助