forked from fission/fission-workflows
/
portforward.go
227 lines (194 loc) · 6.21 KB
/
portforward.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package main
import (
"fmt"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gradecak/fission-workflows/pkg/apiserver/httpclient"
"github.com/sirupsen/logrus"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/portforward"
"k8s.io/client-go/transport/spdy"
)
type client struct {
Admin *httpclient.AdminAPI
Workflow *httpclient.WorkflowAPI
Invocation *httpclient.InvocationAPI
Consent *httpclient.ConsentAPI
}
func getClient(ctx Context) client {
url := ctx.GlobalString("url")
// fetch the FISSION_URL env variable. If not set, port-forward to controller.
if len(url) == 0 {
fissionURL := os.Getenv("FISSION_URL")
if len(fissionURL) == 0 {
fissionNamespace := getFissionNamespace()
kubeConfig := getKubeConfigPath()
localPort := setupPortForward(kubeConfig, fissionNamespace, "application=fission-api")
url = "http://127.0.0.1:" + localPort
logrus.Debugf("Forwarded Fission API to %s.", url)
} else {
url = fissionURL
}
}
path := ctx.GlobalString("path-prefix")
if path[0] != '/' {
path = "/" + path
}
url = url + strings.TrimSuffix(path, "/")
httpClient := http.Client{}
return client{
Admin: httpclient.NewAdminAPI(url, httpClient),
Workflow: httpclient.NewWorkflowAPI(url, httpClient),
Invocation: httpclient.NewInvocationAPI(url, httpClient),
Consent: httpclient.NewConsentAPI(url, httpClient),
}
}
func getFissionNamespace() string {
fissionNamespace := os.Getenv("FISSION_NAMESPACE")
return fissionNamespace
}
func getKubeConfigPath() string {
kubeConfig := os.Getenv("KUBECONFIG")
if len(kubeConfig) == 0 {
home := os.Getenv("HOME")
kubeConfig = filepath.Join(home, ".kube", "config")
if _, err := os.Stat(kubeConfig); os.IsNotExist(err) {
panic("Couldn't find kubeconfig file. Set the KUBECONFIG environment variable to your kubeconfig's path.")
}
}
return kubeConfig
}
func findFreePort() (string, error) {
listener, err := net.Listen("tcp", ":0")
if err != nil {
return "", err
}
port := strconv.Itoa(listener.Addr().(*net.TCPAddr).Port)
file, err := listener.(*net.TCPListener).File()
if err != nil {
return "", nil
}
err = listener.Close()
if err != nil {
return "", err
}
err = file.Close()
if err != nil {
return "", err
}
return port, nil
}
// runPortForward creates a local port forward to the specified pod
func runPortForward(kubeConfig string, labelSelector string, localPort string, fissionNamespace string) error {
config, err := clientcmd.BuildConfigFromFlags("", kubeConfig)
if err != nil {
panic(fmt.Sprintf("Failed to connect to Kubernetes: %s", err))
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(fmt.Sprintf("Failed to connect to Kubernetes: %s", err))
}
// if fission namespace is unset, try to find a fission pod in any namespace
if len(fissionNamespace) == 0 {
fissionNamespace = meta_v1.NamespaceAll
}
// get the pod; if there is more than one, ask the user to disambiguate
podList, err := clientset.CoreV1().Pods(fissionNamespace).List(meta_v1.ListOptions{LabelSelector: labelSelector})
if err != nil || len(podList.Items) == 0 {
panic("Error getting controller pod for port-forwarding")
}
// make a useful error message if there is more than one install
if len(podList.Items) > 1 {
namespaces := make([]string, 0)
for _, p := range podList.Items {
namespaces = append(namespaces, p.Namespace)
}
panic(fmt.Sprintf("Found %v fission installs, set FISSION_NAMESPACE to one of: %v",
len(podList.Items), strings.Join(namespaces, " ")))
}
// pick the first pod
podName := podList.Items[0].Name
podNameSpace := podList.Items[0].Namespace
// get the service and the target port
svcs, err := clientset.CoreV1().Services(podNameSpace).
List(meta_v1.ListOptions{LabelSelector: labelSelector})
if err != nil {
panic(fmt.Sprintf("Error getting %v service :%v", labelSelector, err.Error()))
}
if len(svcs.Items) == 0 {
panic(fmt.Sprintf("Service %v not found", labelSelector))
}
service := &svcs.Items[0]
var targetPort string
for _, servicePort := range service.Spec.Ports {
targetPort = servicePort.TargetPort.String()
}
stopChannel := make(chan struct{}, 1)
readyChannel := make(chan struct{})
// create request URL
req := clientset.CoreV1().RESTClient().Post().Resource("pods").
Namespace(podNameSpace).Name(podName).SubResource("portforward")
url := req.URL()
// create ports slice
portCombo := localPort + ":" + targetPort
ports := []string{portCombo}
// actually start the port-forwarding process here
transport, upgrader, err := spdy.RoundTripperFor(config)
if err != nil {
msg := fmt.Sprintf("newexecutor errored out :%v", err.Error())
panic(msg)
}
dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, "POST", url)
fw, err := portforward.New(dialer, ports, stopChannel, readyChannel, nil, os.Stderr)
if err != nil {
msg := fmt.Sprintf("portforward.new errored out :%v", err.Error())
panic(msg)
}
return fw.ForwardPorts()
}
// Port forward a free local port to a pod on the cluster. The pod is
// found in the specified namespace by labelSelector. The pod's port
// is found by looking for a service in the same namespace and using
// its targetPort. Once the port forward is started, wait for it to
// start accepting connections before returning.
func setupPortForward(kubeConfig, namespace, labelSelector string) string {
localPort, err := findFreePort()
if err != nil {
panic(fmt.Sprintf("Error finding unused port :%v", err.Error()))
}
for {
conn, _ := net.DialTimeout("tcp",
net.JoinHostPort("", localPort), time.Millisecond)
if conn != nil {
conn.Close()
} else {
break
}
time.Sleep(time.Millisecond * 50)
}
go func() {
err := runPortForward(kubeConfig, labelSelector, localPort, namespace)
if err != nil {
panic(fmt.Sprintf("Error forwarding to controller port: %s", err.Error()))
}
}()
for {
conn, _ := net.DialTimeout("tcp",
net.JoinHostPort("", localPort), time.Millisecond)
if conn != nil {
conn.Close()
break
}
time.Sleep(time.Millisecond * 50)
}
return localPort
}