This repository has been archived by the owner on Nov 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
k8s.go
343 lines (280 loc) · 8.63 KB
/
k8s.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
package remote_development
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
"bunnyshell.com/cli/pkg/util"
appsV1 "k8s.io/api/apps/v1"
coreV1 "k8s.io/api/core/v1"
apiMetaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/watch"
applyCoreV1 "k8s.io/client-go/applyconfigurations/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/portforward"
"k8s.io/client-go/transport/spdy"
)
const (
MetadataRemoteDevPrefix = "remote-dev.bunnyshell.com/"
MetadataRemoteDevEnabled = MetadataRemoteDevPrefix + "enabled"
MetadataRemoteDevComponent = MetadataRemoteDevPrefix + "component"
MetadataRemoteDevContainer = MetadataRemoteDevPrefix + "container"
// todo this should match the secret name that remote development start api is looking for
SecretNamePattern = "%s-remote-dev"
// todo this should match the pvc name that remote development start api created
PVCName = "%s-remote-dev"
SecretCertKeyName = "cert.pem"
SecretKeyKeyName = "key.pem"
SecretConfigKeyName = "config.xml"
SecretAuthorizedKeysKeyName = "authorized_keys"
PortForwardMethod = "POST"
PortForwardInterface = "127.0.0.1"
SSHRemotePort = 2222
)
type PortForwardOptions struct {
Interface string
RemotePort int
LocalPort int
StopChannel chan struct{}
ReadyChannel chan struct{}
}
func NewPortForwardOptions() *PortForwardOptions {
return &PortForwardOptions{
Interface: PortForwardInterface,
RemotePort: SSHRemotePort,
LocalPort: 0,
StopChannel: make(chan struct{}),
ReadyChannel: make(chan struct{}, 1),
}
}
type KubernetesClient struct {
Config clientcmd.ClientConfig
RESTConfig *rest.Config
ClientSet *kubernetes.Clientset
SSHPortForwardOptions *PortForwardOptions
}
func NewKubernetesClient(kubeConfigPath string) (*KubernetesClient, error) {
newKubernetes := new(KubernetesClient)
kubeconfig, err := os.ReadFile(kubeConfigPath)
if err != nil {
return newKubernetes, err
}
config, err := clientcmd.NewClientConfigFromBytes(kubeconfig)
if err != nil {
return newKubernetes, err
}
restConfig, err := config.ClientConfig()
if err != nil {
return newKubernetes, err
}
clientset, err := kubernetes.NewForConfig(restConfig)
if err != nil {
return newKubernetes, err
}
newKubernetes.Config = config
newKubernetes.RESTConfig = restConfig
newKubernetes.ClientSet = clientset
newKubernetes.SSHPortForwardOptions = NewPortForwardOptions()
return newKubernetes, nil
}
func (r *RemoteDevelopment) EnsureRemoteDevK8sSecret() error {
spinner := util.MakeSpinner(" Prepare Secret")
spinner.Start()
defer spinner.Stop()
remoteSyncthingConfigDir := r.getRemoteSyncthingConfigDir()
syncthingCertData, err := os.ReadFile(remoteSyncthingConfigDir + "/cert.pem")
if err != nil {
return err
}
syncthingKeyData, err := os.ReadFile(remoteSyncthingConfigDir + "/key.pem")
if err != nil {
return err
}
syncthingConfigData, err := os.ReadFile(remoteSyncthingConfigDir + "/config.xml")
if err != nil {
return err
}
sshPublicKeyData, err := os.ReadFile(r.SSHPublicKeyPath)
if err != nil {
return err
}
namespace, _, err := r.KubernetesClient.Config.Namespace()
if err != nil {
return err
}
secretName := fmt.Sprintf(SecretNamePattern, r.ContainerName)
labels := make(map[string]string)
labels[MetadataRemoteDevEnabled] = "true"
labels[MetadataRemoteDevComponent] = r.ComponentName
secretData := make(map[string][]byte)
secretData[SecretCertKeyName] = syncthingCertData
secretData[SecretKeyKeyName] = syncthingKeyData
secretData[SecretConfigKeyName] = syncthingConfigData
secretData[SecretAuthorizedKeysKeyName] = sshPublicKeyData
applySecret := applyCoreV1.Secret(secretName, namespace).WithLabels(labels).WithData(secretData)
_, err = r.KubernetesClient.ClientSet.CoreV1().Secrets(namespace).Apply(context.TODO(), applySecret, apiMetaV1.ApplyOptions{
FieldManager: "bunnyshell-cli",
})
if err != nil {
return err
}
return nil
}
func (r *RemoteDevelopment) DeleteRemoteDevK8sPVC() error {
pvcName := fmt.Sprintf(PVCName, r.ComponentName)
return r.KubernetesClient.DeletePVC(pvcName)
}
func (k *KubernetesClient) DeletePVC(name string) error {
namespace, _, err := k.Config.Namespace()
if err != nil {
return err
}
fmt.Println(namespace)
return k.ClientSet.CoreV1().PersistentVolumeClaims(namespace).Delete(context.TODO(), name, apiMetaV1.DeleteOptions{})
}
func (k *KubernetesClient) GetDeployment(name string) (*appsV1.Deployment, error) {
deployment := &appsV1.Deployment{}
namespace, _, err := k.Config.Namespace()
if err != nil {
return deployment, err
}
return k.ClientSet.AppsV1().Deployments(namespace).Get(context.TODO(), name, apiMetaV1.GetOptions{})
}
func (k *KubernetesClient) GetDeploymentContainers(name string) ([]coreV1.Container, error) {
deployment, err := k.GetDeployment(name)
return deployment.Spec.Template.Spec.Containers, err
}
func (k *KubernetesClient) WatchRemoteDevPods(componentName, containerName string) error {
spinner := util.MakeSpinner(" Waiting for pod to be ready for remote development")
spinner.Start()
defer spinner.Stop()
labelSelector := apiMetaV1.LabelSelector{MatchLabels: map[string]string{
MetadataRemoteDevEnabled: "true",
MetadataRemoteDevComponent: componentName,
}}
namespace, _, err := k.Config.Namespace()
if err != nil {
return err
}
timeout := int64(120)
listOptions := apiMetaV1.ListOptions{
LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
TimeoutSeconds: &timeout,
}
podList, err := k.ClientSet.CoreV1().Pods(namespace).List(context.TODO(), listOptions)
if err != nil {
return err
}
allRunning := len(podList.Items) > 0
for _, pod := range podList.Items {
if pod.DeletionTimestamp != nil || pod.Status.Phase != coreV1.PodRunning {
allRunning = false
break
}
}
if allRunning {
return nil
}
watcher, err := k.ClientSet.CoreV1().Pods(namespace).Watch(context.TODO(), listOptions)
if err != nil {
return err
}
defer watcher.Stop()
for event := range watcher.ResultChan() {
pod := event.Object.(*coreV1.Pod)
// ignore terminating pod
if pod.DeletionTimestamp != nil {
continue
}
if event.Type == watch.Added {
continue
}
for _, containerStatus := range pod.Status.ContainerStatuses {
if containerStatus.Name == containerName && containerStatus.Ready {
return nil
}
}
}
// timeout reached
return fmt.Errorf("failed to start remote development")
}
func (k *KubernetesClient) GetComponentPod(componentName string) (coreV1.Pod, error) {
nilPod := coreV1.Pod{}
labelSelector := apiMetaV1.LabelSelector{MatchLabels: map[string]string{
MetadataRemoteDevEnabled: "true",
MetadataRemoteDevComponent: componentName,
}}
namespace, _, err := k.Config.Namespace()
if err != nil {
return nilPod, err
}
listOptions := apiMetaV1.ListOptions{
LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
}
podList, err := k.ClientSet.CoreV1().Pods(namespace).List(context.TODO(), listOptions)
if err != nil {
return nilPod, err
}
for _, pod := range podList.Items {
if pod.DeletionTimestamp == nil && pod.Status.Phase == coreV1.PodRunning {
return pod, nil
}
}
return nilPod, fmt.Errorf("pod not found for component %v", componentName)
}
func (k *KubernetesClient) GetPortForwardSubresourceURL(pod coreV1.Pod) *url.URL {
return k.ClientSet.CoreV1().RESTClient().Post().
Resource("pods").
Namespace(pod.Namespace).
Name(pod.Name).
SubResource("portforward").URL()
}
func (k *KubernetesClient) PortForwardRemoteSSH(componentName string) (*portforward.PortForwarder, error) {
pod, err := k.GetComponentPod(componentName)
if err != nil {
return nil, err
}
transport, upgrader, err := spdy.RoundTripperFor(k.RESTConfig)
if err != nil {
return nil, err
}
url := k.GetPortForwardSubresourceURL(pod)
dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, PortForwardMethod, url)
k.SSHPortForwardOptions.LocalPort, err = util.GetAvailableEphemeralPort(k.SSHPortForwardOptions.Interface)
if err != nil {
return nil, err
}
ports := []string{fmt.Sprintf(
"%d:%d",
k.SSHPortForwardOptions.LocalPort,
k.SSHPortForwardOptions.RemotePort,
)}
forwarder, err := portforward.NewOnAddresses(
dialer,
[]string{k.SSHPortForwardOptions.Interface},
ports,
k.SSHPortForwardOptions.StopChannel,
k.SSHPortForwardOptions.ReadyChannel,
io.Discard,
os.Stderr,
)
if err != nil {
return nil, err
}
errChan := make(chan error, 1)
go func() {
errChan <- forwarder.ForwardPorts()
close(errChan)
}()
select {
case <-forwarder.Ready:
case err := <-errChan:
return nil, err
}
return forwarder, nil
}