/
forwarder.go
354 lines (281 loc) · 9.01 KB
/
forwarder.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package kubernetes
import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/eko/monday/pkg/config"
"github.com/eko/monday/pkg/log"
"github.com/eko/monday/pkg/ui"
appsv1 "k8s.io/api/apps/v1"
apiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/portforward"
"k8s.io/client-go/transport/spdy"
)
const (
// RemoteSSHProxyPort is the SSH proxy port used by the 'ekofr/monday-proxy' docker image
// to make a remote-forward on the Kubernetes pod to be able to next forward trafic locally
RemoteSSHProxyPort = 5022
// ProxyDockerImage is the path to the public Docker image acting as a proxy in the
// Kubernetes cluster
ProxyDockerImage = "ekofr/monday-proxy"
// ProxyPortName is the name given to the SSH port used when deploying the proxy image into the
// cluster
ProxyPortName = "ssh-proxy"
)
var (
defaultKubeConfigPath = fmt.Sprintf("%s/%s", os.Getenv("HOME"), "/.kube/config")
)
type DeploymentBackup struct {
OldImage string
OldPorts []apiv1.ContainerPort
Deployment *appsv1.Deployment
}
type Forwarder struct {
view ui.View
forwardType string
name string
clientConfig *restclient.Config
clientSet kubernetes.Interface
restClient restclient.Interface
context string
namespace string
ports []string
labels map[string]string
portForwarders map[string]*portforward.PortForwarder
deployments map[string]*DeploymentBackup
stopChannel chan struct{}
readyChannel chan struct{}
}
func NewForwarder(view ui.View, forwardType, name, context, namespace string, ports []string, labels map[string]string) (*Forwarder, error) {
kubeConfigPath := getKubeConfigPath()
clientConfig, err := initializeClientConfig(context, kubeConfigPath)
if err != nil {
return nil, err
}
clientSet, err := initializeClientSet(clientConfig)
if err != nil {
return nil, err
}
return &Forwarder{
view: view,
forwardType: forwardType,
name: name,
context: context,
namespace: namespace,
labels: labels,
ports: ports,
clientConfig: clientConfig,
clientSet: clientSet,
restClient: clientSet.RESTClient(),
portForwarders: make(map[string]*portforward.PortForwarder, 0),
deployments: make(map[string]*DeploymentBackup, 0),
stopChannel: make(chan struct{}, 1),
readyChannel: make(chan struct{}),
}, nil
}
// GetForwardType returns the type of the forward specified in the configuration (ssh, ssh-remote, kubernetes, ...)
func (f *Forwarder) GetForwardType() string {
return f.forwardType
}
// GetReadyChannel returns the Kubernetes go client channel for ready event
func (f *Forwarder) GetReadyChannel() chan struct{} {
return f.readyChannel
}
// GetStopChannel returns the Kubernetes go client channel for stop event
func (f *Forwarder) GetStopChannel() chan struct{} {
return f.readyChannel
}
// Forward method executes the local or remote port-forward depending on the given type
func (f *Forwarder) Forward(ctx context.Context) error {
selector := f.getSelector()
if selector == "" {
return fmt.Errorf("Please provide a selector of labels in order to use Kubernetes forwarding")
}
switch f.forwardType {
case config.ForwarderKubernetes:
err := f.forwardLocal(ctx, selector)
if err != nil {
return err
}
case config.ForwarderKubernetesRemote:
err := f.forwardRemote(ctx, selector)
if err != nil {
return err
}
}
return nil
}
// Stop stops the current forwarder
func (f *Forwarder) Stop(ctx context.Context) error {
// Close port-forwards currently active connections
for _, portForwarder := range f.portForwarders {
portForwarder.Close()
}
deploymentsClient := f.clientSet.AppsV1().Deployments(f.namespace)
// Reset currently active remote-forward deployment proxies
for _, backup := range f.deployments {
selector := f.getSelector()
deployments, err := deploymentsClient.List(ctx, metav1.ListOptions{LabelSelector: selector})
if err != nil {
continue
}
if len(deployments.Items) < 1 {
continue
}
// Take first pod matching at the moment, maybe we should take all?
deployment := deployments.Items[0]
deployment.Spec.Template.Spec.Containers[0].Image = backup.OldImage
deployment.Spec.Template.Spec.Containers[0].Ports = backup.OldPorts
_, err = deploymentsClient.Update(ctx, &deployment, metav1.UpdateOptions{})
if err != nil {
f.view.Writef("❌ An error has occured while stopping/resetting a deployment: %v\n", err)
}
}
return nil
}
func isPodRunning(pod *apiv1.Pod) bool {
return pod.Status.Phase == apiv1.PodRunning
}
func (f *Forwarder) forwardLocal(ctx context.Context, selector string) error {
pods, err := f.clientSet.CoreV1().Pods(f.namespace).List(
ctx,
metav1.ListOptions{LabelSelector: selector},
)
if err != nil {
return fmt.Errorf("Unable to find pods for selector '%s': %v", selector, err)
}
if len(pods.Items) < 1 {
return fmt.Errorf("No pod available for selector '%s': %v", selector, err)
}
var runningPod apiv1.Pod
foundRunningPod := false
for _, pod := range pods.Items {
if isPodRunning(&pod) {
runningPod = pod
foundRunningPod = true
break
}
}
if !foundRunningPod {
return fmt.Errorf("No runnning pod available for selector '%s'", selector)
}
request := f.restClient.Post().Resource("pods").Namespace(f.namespace).Name(runningPod.Name).SubResource("portforward")
url := url.URL{
Scheme: request.URL().Scheme,
Host: request.URL().Host,
Path: buildPath(request),
RawQuery: "timeout=30s",
}
transport, upgrader, err := spdy.RoundTripperFor(f.clientConfig)
if err != nil {
return err
}
dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, "POST", &url)
stdoutStream := log.NewStreamer(log.StdOut, runningPod.Name, f.view)
stderrStream := log.NewStreamer(log.StdErr, runningPod.Name, f.view)
fw, err := portforward.New(dialer, f.ports, f.stopChannel, f.readyChannel, stdoutStream, stderrStream)
if err != nil {
return err
}
f.portForwarders[f.name] = fw
err = fw.ForwardPorts()
if err != nil {
return err
}
return nil
}
func (f *Forwarder) forwardRemote(ctx context.Context, selector string) error {
deploymentsClient := f.clientSet.AppsV1().Deployments(f.namespace)
deployments, err := deploymentsClient.List(
ctx,
metav1.ListOptions{LabelSelector: selector},
)
if err != nil {
return err
}
if len(deployments.Items) < 1 {
return fmt.Errorf("No deployment available for selector '%s': %v", selector, err)
}
// Take first pod matching at the moment, maybe we should take all?
deployment := deployments.Items[0]
container := deployment.Spec.Template.Spec.Containers[0]
if _, ok := f.deployments[f.name]; !ok {
f.view.Writef("📡 Setting up proxy on application '%s', please wait some seconds for pod to be ready...\n", deployment.Name)
f.deployments[f.name] = &DeploymentBackup{
OldImage: container.Image,
OldPorts: container.Ports,
Deployment: &deployment,
}
}
container.Image = ProxyDockerImage
ports := make([]apiv1.ContainerPort, 0)
for _, port := range container.Ports {
if port.Name == ProxyPortName {
continue
}
ports = append(ports, port)
}
ports = append(ports, apiv1.ContainerPort{
Name: ProxyPortName,
Protocol: apiv1.ProtocolTCP,
ContainerPort: RemoteSSHProxyPort,
})
container.Ports = ports
deployment.Spec.Template.Spec.Containers[0] = container
deployment.Spec.Template.Spec.ReadinessGates = []apiv1.PodReadinessGate{}
_, err = deploymentsClient.Update(ctx, &deployment, metav1.UpdateOptions{})
if err != nil {
f.view.Write(err.Error())
}
time.Sleep(time.Duration(5 * time.Second))
// Deployment has been updated with proxy, now forward ports locally
f.forwardLocal(ctx, selector)
return nil
}
func (f *Forwarder) getSelector() string {
selector := ""
for label, value := range f.labels {
if selector != "" {
selector = selector + ","
}
selector = selector + fmt.Sprintf("%s=%s", label, value)
}
return selector
}
func initializeClientConfig(context string, kubeConfigPath string) (*restclient.Config, error) {
overrides := &clientcmd.ConfigOverrides{CurrentContext: context}
clientConfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeConfigPath},
overrides,
).ClientConfig()
if err != nil {
return nil, err
}
return clientConfig, nil
}
func initializeClientSet(clientConfig *restclient.Config) (*kubernetes.Clientset, error) {
clientSet, err := kubernetes.NewForConfig(clientConfig)
if err != nil {
return nil, err
}
return clientSet, nil
}
func buildPath(request *restclient.Request) string {
parts := strings.Split(request.URL().Path, "/namespaces")
return parts[0] + "/api/v1/namespaces" + parts[1]
}
func getKubeConfigPath() string {
if value := os.Getenv("MONDAY_KUBE_CONFIG"); value != "" {
return value
}
return defaultKubeConfigPath
}