-
Notifications
You must be signed in to change notification settings - Fork 462
/
pods.go
171 lines (145 loc) · 4.97 KB
/
pods.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
// Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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 kubernetes
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"strings"
"github.com/gardener/gardener/pkg/utils"
corev1 "k8s.io/api/core/v1"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/portforward"
"k8s.io/client-go/tools/remotecommand"
"k8s.io/client-go/transport/spdy"
)
// NewPodExecutor returns a podExecutor
func NewPodExecutor(config *rest.Config) PodExecutor {
return &podExecutor{
config: config,
}
}
// PodExecutor is the pod executor interface
type PodExecutor interface {
Execute(namespace, name, containerName, command, commandArg string) (io.Reader, error)
}
type podExecutor struct {
config *rest.Config
}
// Execute executes a command on a pod
func (p *podExecutor) Execute(namespace, name, containerName, command, commandArg string) (io.Reader, error) {
client, err := corev1client.NewForConfig(p.config)
if err != nil {
return nil, err
}
var stdout, stderr bytes.Buffer
request := client.RESTClient().
Post().
Resource("pods").
Name(name).
Namespace(namespace).
SubResource("exec").
Param("container", containerName).
Param("command", command).
Param("stdin", "true").
Param("stdout", "true").
Param("stderr", "true").
Param("tty", "false")
executor, err := remotecommand.NewSPDYExecutor(p.config, http.MethodPost, request.URL())
if err != nil {
return nil, fmt.Errorf("failed to initialized the command exector: %w", err)
}
err = executor.Stream(remotecommand.StreamOptions{
Stdin: strings.NewReader(commandArg),
Stdout: &stdout,
Stderr: &stderr,
Tty: false,
})
if err != nil {
return &stderr, err
}
return &stdout, nil
}
// GetPodLogs retrieves the pod logs of the pod of the given name with the given options.
func GetPodLogs(ctx context.Context, podInterface corev1client.PodInterface, name string, options *corev1.PodLogOptions) ([]byte, error) {
request := podInterface.GetLogs(name, options)
stream, err := request.Stream(ctx)
if err != nil {
return nil, err
}
defer func() { utilruntime.HandleError(stream.Close()) }()
return io.ReadAll(stream)
}
// CheckForwardPodPort tries to open a portForward connection with the passed PortForwarder.
// It returns nil if the port forward connection has been established successfully or an error otherwise.
func CheckForwardPodPort(fw PortForwarder) error {
errChan := make(chan error, 1)
go func() {
errChan <- fw.ForwardPorts()
}()
select {
case err := <-errChan:
return fmt.Errorf("error forwarding ports: %w", err)
case <-fw.Ready():
return nil
}
}
// PortForwarder knows how to forward a port connection
// Ready channel is expected to be closed once the connection becomes ready
type PortForwarder interface {
ForwardPorts() error
Ready() chan struct{}
}
// SetupPortForwarder sets up a PortForwarder which forwards the <remote> port of the pod with name <name> in namespace <namespace>
// to the <local> port. If <local> equals zero, a free port will be chosen randomly.
// When calling ForwardPorts on the returned PortForwarder, it will run until the given context is cancelled.
// Hence, the given context should carry a timeout and should be cancelled once the forwarding is no longer needed.
func SetupPortForwarder(ctx context.Context, config *rest.Config, namespace, name string, local, remote int) (PortForwarder, error) {
var (
readyChan = make(chan struct{}, 1)
out = io.Discard
localPort int
)
client, err := corev1client.NewForConfig(config)
if err != nil {
return nil, err
}
u := client.RESTClient().Post().Resource("pods").Namespace(namespace).Name(name).SubResource("portforward").URL()
transport, upgrader, err := spdy.RoundTripperFor(config)
if err != nil {
return nil, err
}
dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, "POST", u)
if local == 0 {
localPort, err = utils.FindFreePort()
if err != nil {
return nil, err
}
}
fw, err := portforward.New(dialer, []string{fmt.Sprintf("%d:%d", localPort, remote)}, ctx.Done(), readyChan, out, out)
if err != nil {
return nil, err
}
return portForwarder{fw}, nil
}
type portForwarder struct {
*portforward.PortForwarder
}
func (p portForwarder) Ready() chan struct{} {
return p.PortForwarder.Ready
}