forked from CARV-ICS-FORTH/knoc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremote.go
455 lines (425 loc) · 14.3 KB
/
remote.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
// Copyright © 2021 FORTH-ICS
//
// 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 main
package knoc
import (
"context"
"encoding/json"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
b64 "encoding/base64"
common "github.com/CARV-ICS-FORTH/knoc/common"
"github.com/containerd/containerd/log"
"github.com/pkg/sftp"
"github.com/sfreiberg/simplessh"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func getRoutine(mode int8) string {
switch mode {
case 0:
return "Create Remote Execution"
case 1:
return "Delete Remote Execution"
default:
return "UNKNOWN"
}
}
func normalizeImageName(instance_name string) string {
instances_str := strings.Split(string(instance_name), "/")
final_name := ""
first_iter := true
for _, strings := range instances_str {
if first_iter {
final_name = strings
first_iter = false
continue
}
final_name = final_name + "-" + strings
}
without_version_stamp := strings.Split(final_name, ":")
return without_version_stamp[0]
}
func exportContainerb64Json(instance_name string, obj v1.Container, meta metav1.ObjectMeta) string {
obj.Name = instance_name
dc := common.DoorContainer{}
dc.Args = obj.Args
dc.Command = obj.Command
dc.Env = obj.Env
dc.EnvFrom = obj.EnvFrom
dc.Image = obj.Image
dc.Name = obj.Name
dc.Ports = obj.Ports
dc.Resources = obj.Resources
dc.VolumeDevices = obj.VolumeDevices
dc.VolumeMounts = obj.VolumeMounts
dc.Metadata = meta
u, _ := json.Marshal(dc)
sEnc := b64.StdEncoding.EncodeToString(u)
return sEnc
}
func hasDoor(client *simplessh.Client) bool {
_, err := client.Exec("./door --version")
return err == nil
}
func prepareDoor(client *simplessh.Client) {
if !hasDoor(client) {
// Could not find KNoC's Door binary in the remote system...
// send door to remote
local := "/usr/local/bin/door" // from inside the container's root dir
remote := "door"
common.UploadFile(client, local, remote, 0700)
// check again else die
_, err := client.Exec("./door --version")
if err != nil {
fmt.Println("Could not upload KNoC's Door")
panic(err)
}
}
}
func runRemoteExecutionInstance(ctx context.Context, client *simplessh.Client, imageLocation string, instance_name string, container v1.Container, meta metav1.ObjectMeta) ([]byte, error) {
b64dc := exportContainerb64Json(instance_name, container, meta)
output, err := client.Exec("bash -l -c \"nohup ./door -a submit -c " + b64dc + " -V >> .knoc/door.log 2>> .knoc/door.log < /dev/null & \"")
log.G(ctx).Debugf("bash -l -c \"nohup ./door -a submit -c " + b64dc + " -V >> .knoc/door.log 2>> .knoc/door.log < /dev/null & \"")
if err != nil {
// Could not exec instance
return nil, err
}
return output, nil
}
func BuildRemoteExecutionInstanceName(container v1.Container, pod *v1.Pod) string {
return pod.Namespace + "-" + string(pod.UID) + "-" + normalizeImageName(container.Image)
}
func BuildRemoteExecutionPodName(pod *v1.Pod) string {
return pod.Namespace + "-" + string(pod.UID)
}
func stopRemoteExecutionInstance(ctx context.Context, client *simplessh.Client, pod *v1.Pod, instance_name string, container v1.Container, meta metav1.ObjectMeta) ([]byte, error) {
b64dc := exportContainerb64Json(instance_name, container, meta)
output, err := client.Exec("bash -l -c \"nohup ./door -a stop -c " + b64dc + " -V >> .knoc/door.log 2>> .knoc/door.log < /dev/null & \"")
log.G(ctx).Debugf("bash -l -c \"nohup ./door -a stop -c " + b64dc + " -V >> .knoc/door.log 2>> .knoc/door.log < /dev/null & \"")
if err != nil {
// Could not exec instance
return nil, err
}
return output, nil
}
func RemoteExecution(p *KNOCProvider, ctx context.Context, mode int8, imageLocation string, pod *v1.Pod, container v1.Container) error {
var err error
instance_name := BuildRemoteExecutionInstanceName(container, pod)
client, err := simplessh.ConnectWithKey(os.Getenv("REMOTE_HOST")+":"+os.Getenv("REMOTE_PORT"), os.Getenv("REMOTE_USER"), os.Getenv("REMOTE_KEY"))
if err != nil {
return err
}
defer client.Close()
log.GetLogger(ctx).Info(getRoutine(mode) + " Container")
prepareDoor(client)
if mode == common.CREATE {
err = PrepareContainerData(p, ctx, client, instance_name, container, pod)
if err != nil {
return err
}
_, err = runRemoteExecutionInstance(ctx, client, imageLocation, instance_name, container, pod.ObjectMeta)
} else if mode == common.DELETE {
_, err = stopRemoteExecutionInstance(ctx, client, pod, instance_name, container, pod.ObjectMeta)
}
if err != nil {
return err
}
return nil
}
func PrepareContainerData(p *KNOCProvider, ctx context.Context, client *simplessh.Client, instance_name string, container v1.Container, pod *v1.Pod) error {
log.G(ctx).Debugf("receive prepareContainerData %v", container.Name)
c, err := sftp.NewClient(client.SSHClient)
if err != nil {
fmt.Println("Could not connect over sftp on the remote system ")
panic(err)
}
defer c.Close()
//add kubeconfig on remote:$HOME
out, err := exec.Command("test -f .kube/config").Output()
if _, ok := err.(*exec.ExitError); !ok {
log.GetLogger(ctx).Debug("Kubeconfig doesn't exist, so we will generate it...")
out, err = exec.Command("/bin/sh", "/home/user0/scripts/prepare_kubeconfig.sh").Output()
if err != nil {
log.GetLogger(ctx).Errorln("Could not run kubeconfig_setup script!")
log.GetLogger(ctx).Error(string(out))
panic(err)
}
log.GetLogger(ctx).Debug("Kubeconfig generated")
client.Exec("mkdir -p .kube")
_, err = client.Exec("echo \"" + string(out) + "\" > .kube/config")
if err != nil {
log.GetLogger(ctx).Errorln("Could not setup kubeconfig on the remote system ")
panic(err)
}
log.GetLogger(ctx).Debug("Kubeconfig installed")
}
client.Exec("mkdir -p " + ".knoc")
for _, mountSpec := range container.VolumeMounts {
podVolSpec := findPodVolumeSpec(pod, mountSpec.Name)
if podVolSpec.ConfigMap != nil {
cmvs := podVolSpec.ConfigMap
mode := podVolSpec.ConfigMap.DefaultMode
podConfigMapDir := filepath.Join(common.PodVolRoot, BuildRemoteExecutionPodName(pod)+"/", mountSpec.Name)
configMap, err := p.resourceManager.GetConfigMap(cmvs.Name, pod.Namespace)
if cmvs.Optional != nil && !*cmvs.Optional {
return fmt.Errorf("Configmap %s is required by Pod %s and does not exist", cmvs.Name, pod.Name)
}
if err != nil {
return fmt.Errorf("Error getting configmap %s from API server: %v", pod.Name, err)
}
if configMap == nil {
continue
}
client.Exec("mkdir -p " + podConfigMapDir)
log.GetLogger(ctx).Debugf("%v", "create dir for configmaps "+podConfigMapDir)
for k, v := range configMap.Data {
// TODO: Ensure that these files are deleted in failure cases
fullPath := filepath.Join(podConfigMapDir, k)
common.UploadData(client, []byte(v), fullPath, fs.FileMode(*mode))
if err != nil {
return fmt.Errorf("Could not write configmap file %s", fullPath)
}
}
} else if podVolSpec.Secret != nil {
svs := podVolSpec.Secret
mode := podVolSpec.Secret.DefaultMode
podSecretDir := filepath.Join(common.PodVolRoot, BuildRemoteExecutionPodName(pod)+"/", mountSpec.Name)
secret, err := p.resourceManager.GetSecret(svs.SecretName, pod.Namespace)
if svs.Optional != nil && !*svs.Optional {
return fmt.Errorf("Secret %s is required by Pod %s and does not exist", svs.SecretName, pod.Name)
}
if err != nil {
return fmt.Errorf("Error getting secret %s from API server: %v", pod.Name, err)
}
if secret == nil {
continue
}
client.Exec("mkdir -p " + podSecretDir)
log.GetLogger(ctx).Debugf("%v", "create dir for secrets "+podSecretDir)
for k, v := range secret.Data {
fullPath := filepath.Join(podSecretDir, k)
common.UploadData(client, []byte(v), fullPath, fs.FileMode(*mode))
if err != nil {
return fmt.Errorf("Could not write secret file %s", fullPath)
}
}
} else if podVolSpec.EmptyDir != nil {
// pod-global directory
edPath := filepath.Join(common.PodVolRoot, BuildRemoteExecutionPodName(pod)+"/"+mountSpec.Name)
// mounted for every container
client.Exec("mkdir -p " + edPath)
// without size limit for now
}
}
return nil
}
// Search for a particular volume spec by name in the Pod spec
func findPodVolumeSpec(pod *v1.Pod, name string) *v1.VolumeSource {
for _, volume := range pod.Spec.Volumes {
if volume.Name == name {
return &volume.VolumeSource
}
}
return nil
}
func checkPodsStatus(p *KNOCProvider, ctx context.Context) {
if len(p.pods) == 0 {
return
}
log.GetLogger(ctx).Debug("received checkPodStatus")
client, err := simplessh.ConnectWithKey(os.Getenv("REMOTE_HOST")+":"+os.Getenv("REMOTE_PORT"), os.Getenv("REMOTE_USER"), os.Getenv("REMOTE_KEY"))
if err != nil {
panic(err)
}
defer client.Close()
instance_name := ""
now := metav1.Now()
for _, pod := range p.pods {
if pod.Status.Phase == v1.PodSucceeded || pod.Status.Phase == v1.PodFailed || pod.Status.Phase == v1.PodPending {
continue
}
// if its not initialized yet
if pod.Status.Conditions[0].Status == v1.ConditionFalse && pod.Status.Conditions[0].Type == v1.PodInitialized {
containers_count := len(pod.Spec.InitContainers)
successfull := 0
failed := 0
valid := 1
for idx, container := range pod.Spec.InitContainers {
//TODO: find next initcontainer and run it
instance_name = BuildRemoteExecutionInstanceName(container, pod)
if len(pod.Status.InitContainerStatuses) < len(pod.Spec.InitContainers) {
pod.Status.InitContainerStatuses = append(pod.Status.InitContainerStatuses, v1.ContainerStatus{
Name: container.Name,
Image: container.Image,
Ready: true,
RestartCount: 0,
State: v1.ContainerState{
Running: &v1.ContainerStateRunning{
StartedAt: now,
},
},
})
continue
}
lastStatus := pod.Status.InitContainerStatuses[idx]
if lastStatus.Ready {
status_file, err := client.Exec("cat " + ".knoc/" + instance_name + ".status")
status := string(status_file)
if len(status) > 1 {
// remove '\n' from end of status due to golang's string conversion :X
status = status[:len(status)-1]
}
if err != nil || status == "" {
// still running
continue
}
i, err := strconv.Atoi(status)
reason := "Unknown"
if i == 0 && err == nil {
successfull++
reason = "Completed"
} else {
failed++
reason = "Error"
}
containers_count--
pod.Status.InitContainerStatuses[idx] = v1.ContainerStatus{
Name: container.Name,
Image: container.Image,
Ready: false,
State: v1.ContainerState{
Terminated: &v1.ContainerStateTerminated{
StartedAt: lastStatus.State.Running.StartedAt,
FinishedAt: now,
Reason: reason,
ExitCode: int32(i),
},
},
}
valid = 0
} else {
containers_count--
status := lastStatus.State.Terminated.ExitCode
i, _ := strconv.Atoi(string(status))
if i == 0 {
successfull++
} else {
failed++
}
}
}
if containers_count == 0 && pod.Status.Phase == v1.PodRunning {
if successfull == len(pod.Spec.InitContainers) {
log.GetLogger(ctx).Debug("SUCCEEDED InitContainers")
// PodInitialized = true
pod.Status.Conditions[0].Status = v1.ConditionTrue
// PodReady = true
pod.Status.Conditions[1].Status = v1.ConditionTrue
p.startMainContainers(ctx, pod)
valid = 0
} else {
pod.Status.Phase = v1.PodFailed
valid = 0
}
}
if valid == 0 {
p.UpdatePod(ctx, pod)
}
// log.GetLogger(ctx).Infof("init checkPodStatus:%v %v %v", pod.Name, successfull, failed)
} else {
// if its initialized
containers_count := len(pod.Spec.Containers)
successfull := 0
failed := 0
valid := 1
for idx, container := range pod.Spec.Containers {
instance_name = BuildRemoteExecutionInstanceName(container, pod)
lastStatus := pod.Status.ContainerStatuses[idx]
if lastStatus.Ready {
status_file, err := client.Exec("cat " + ".knoc/" + instance_name + ".status")
status := string(status_file)
if len(status) > 1 {
// remove '\n' from end of status due to golang's string conversion :X
status = status[:len(status)-1]
}
if err != nil || status == "" {
// still running
continue
}
containers_count--
i, err := strconv.Atoi(status)
reason := "Unknown"
if i == 0 && err == nil {
successfull++
reason = "Completed"
} else {
failed++
reason = "Error"
// log.GetLogger(ctx).Info("[checkPodStatus] CONTAINER_FAILED")
}
pod.Status.ContainerStatuses[idx] = v1.ContainerStatus{
Name: container.Name,
Image: container.Image,
Ready: false,
State: v1.ContainerState{
Terminated: &v1.ContainerStateTerminated{
StartedAt: lastStatus.State.Running.StartedAt,
FinishedAt: now,
Reason: reason,
ExitCode: int32(i),
},
},
}
valid = 0
} else {
if lastStatus.State.Terminated == nil {
// containers not yet turned on
if p.initContainersActive(pod) {
continue
}
}
containers_count--
status := lastStatus.State.Terminated.ExitCode
i := status
if i == 0 && err == nil {
successfull++
} else {
failed++
}
}
}
if containers_count == 0 && pod.Status.Phase == v1.PodRunning {
// containers are ready
pod.Status.Conditions[1].Status = v1.ConditionFalse
if successfull == len(pod.Spec.Containers) {
log.GetLogger(ctx).Debug("[checkPodStatus] POD_SUCCEEDED ")
pod.Status.Phase = v1.PodSucceeded
} else {
log.GetLogger(ctx).Debug("[checkPodStatus] POD_FAILED ", successfull, " ", containers_count, " ", len(pod.Spec.Containers), " ", failed)
pod.Status.Phase = v1.PodFailed
}
valid = 0
}
if valid == 0 {
p.UpdatePod(ctx, pod)
}
log.GetLogger(ctx).Debugf("main checkPodStatus:%v %v %v", pod.Name, successfull, failed)
}
}
}