This repository has been archived by the owner on Oct 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
output_persistor.go
380 lines (334 loc) · 11.3 KB
/
output_persistor.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
package quarksjob
import (
"context"
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"github.com/pkg/errors"
"go.uber.org/zap"
"gopkg.in/fsnotify.v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
qjv1a1 "code.cloudfoundry.org/quarks-job/pkg/kube/apis/quarksjob/v1alpha1"
"code.cloudfoundry.org/quarks-job/pkg/kube/client/clientset/versioned"
"code.cloudfoundry.org/quarks-utils/pkg/names"
podutil "code.cloudfoundry.org/quarks-utils/pkg/pod"
"code.cloudfoundry.org/quarks-utils/pkg/versionedsecretstore"
)
// OutputPersistor creates a kubernetes secret for each container in the in the qJob pod.
type OutputPersistor struct {
log *zap.SugaredLogger
namespace string
podName string
clientSet kubernetes.Interface
versionedClientSet versioned.Interface
outputFilePathPrefix string
}
// NewOutputPersistor returns a persist output interface which can create kubernetes secrets.
func NewOutputPersistor(log *zap.SugaredLogger, namespace string, podName string, clientSet kubernetes.Interface, versionedClientSet versioned.Interface, outputFilePathPrefix string) *OutputPersistor {
return &OutputPersistor{
log: log,
namespace: namespace,
podName: podName,
clientSet: clientSet,
versionedClientSet: versionedClientSet,
outputFilePathPrefix: outputFilePathPrefix,
}
}
// Persist converts the output files of each container
// in the pod related to an qJob into a kubernetes secret.
func (po *OutputPersistor) Persist(ctx context.Context) error {
// Fetch the pod
pod, err := po.clientSet.CoreV1().Pods(po.namespace).Get(ctx, po.podName, metav1.GetOptions{})
if err != nil {
return errors.Wrapf(err, "failed to fetch pod %s", po.podName)
}
// Fetch the qJob
qJobName := pod.GetLabels()[qjv1a1.LabelQJobName]
qJobClient := po.versionedClientSet.QuarksjobV1alpha1().QuarksJobs(po.namespace)
qJob, err := qJobClient.Get(ctx, qJobName, metav1.GetOptions{})
if err != nil {
return errors.Wrapf(err, "failed to fetch qJob")
}
// Persist output if needed
if !reflect.DeepEqual(qjv1a1.Output{}, qJob.Spec.Output) && qJob.Spec.Output != nil {
err = po.persistPod(ctx, pod, qJob)
if err != nil {
return err
}
}
return nil
}
// persistPod starts goroutine for creating secrets for each output found in our containers
func (po *OutputPersistor) persistPod(ctx context.Context, pod *corev1.Pod, qJob *qjv1a1.QuarksJob) error {
errorContainerChannel := make(chan error)
// Loop over containers and create go routine
for containerIndex, container := range pod.Spec.Containers {
if container.Name == "output-persist" {
continue
}
filesToSecrets, found := qJob.Spec.Output.OutputMap[container.Name]
if !found {
continue
}
go po.persistContainer(ctx, qJob, containerIndex, container, filesToSecrets, errorContainerChannel)
}
// wait for all container go routines
for i := 0; i < len(pod.Spec.Containers)-1; i++ {
err := <-errorContainerChannel
if err != nil {
return err
}
}
return nil
}
// persistContainer converts json output file
// of the specified container into secret(s)
func (po *OutputPersistor) persistContainer(
ctx context.Context,
qJob *qjv1a1.QuarksJob,
containerIndex int,
container corev1.Container,
filesToSecrets qjv1a1.FilesToSecrets,
errorContainerChannel chan<- error,
) {
prefix := filepath.Join(po.outputFilePathPrefix, container.Name)
filePaths := filesToSecrets.PrefixedPaths(prefix)
po.log.Debugf("container '%s': expects outputs in %v", container.Name, filePaths)
containerIndex, err := po.checkForOutputFiles(filePaths, containerIndex, container.Name)
if err != nil {
errorContainerChannel <- err
}
if containerIndex != -1 {
exitCode, err := po.getContainerExitCode(ctx, containerIndex)
if err != nil {
errorContainerChannel <- err
}
if exitCode == 0 || (exitCode == 1 && qJob.Spec.Output.WriteOnFailure) {
for fileName, options := range filesToSecrets {
filePath := filepath.Join(prefix, fileName)
if options.AdditionalSecretLabels == nil {
options.AdditionalSecretLabels = map[string]string{}
}
// Fetch json from file
file, err := ioutil.ReadFile(filePath)
if err != nil {
errorContainerChannel <- errors.Wrapf(err, "unable to read file %s in container %s in pod '%s/%s'", filePath, container.Name, po.namespace, po.podName)
}
var data map[string]string
if err := json.Unmarshal([]byte(file), &data); err != nil {
errorContainerChannel <- errors.Wrapf(err, "failed to convert output file %s into json for creating secret(s) %s in pod '%s/%s'", filePath, options.Name, po.namespace, po.podName)
}
labels := newLabels(*qJob.Spec.Output, options.AdditionalSecretLabels, container)
switch options.PersistenceMethod {
case qjv1a1.PersistUsingFanOut:
po.log.Debugf("container '%s': creating secrets with prefix '%s' from '%s'", container.Name, options.Name, filePath)
for key, value := range data {
name := names.SanitizeSubdomain(options.FanOutName(key))
var stringData map[string]string
if err := json.Unmarshal([]byte(value), &stringData); err != nil {
errorContainerChannel <- err
}
if options.Versioned {
err = po.createVersionedSecret(qJob, name, labels, options.AdditionalSecretAnnotations, stringData)
} else {
err = po.createSecret(ctx, name, labels, options.AdditionalSecretAnnotations, stringData)
}
if err != nil {
errorContainerChannel <- errors.Wrapf(err, "failed to persist qjob '%s' output, pod '%s/%s', container '%s', using fan-out", qJob.Name, po.namespace, po.podName, container.Name)
}
}
default:
name := names.SanitizeSubdomain(options.Name)
po.log.Debugf("container '%s': creating secret '%s' from '%s'", container.Name, name, filePath)
var err error
if options.Versioned {
err = po.createVersionedSecret(qJob, name, labels, options.AdditionalSecretAnnotations, data)
} else {
err = po.createSecret(ctx, name, labels, options.AdditionalSecretAnnotations, data)
}
if err != nil {
errorContainerChannel <- errors.Wrapf(err, "failed to persist qjob '%s' output, pod '%s/%s', container '%s', using one-to-one", qJob.Name, po.namespace, po.podName, container.Name)
}
}
}
}
}
errorContainerChannel <- err
}
// getContainerExitCode returns the exit code of the container
func (po *OutputPersistor) getContainerExitCode(ctx context.Context, containerIndex int) (int, error) {
// Wait until the container gets into terminated state
for {
pod, err := po.clientSet.CoreV1().Pods(po.namespace).Get(ctx, po.podName, metav1.GetOptions{})
if err != nil {
return -1, errors.Wrapf(err, "failed to fetch pod '%s/%s'", po.namespace, po.podName)
}
for _, containerStatus := range pod.Status.ContainerStatuses {
if containerStatus.Name == pod.Spec.Containers[containerIndex].Name && containerStatus.State.Terminated != nil {
return int(containerStatus.State.Terminated.ExitCode), nil
}
}
}
}
// checkForOutputFiles waits for the output json file to be created
// in the container
func (po *OutputPersistor) checkForOutputFiles(filePaths []string, containerIndex int, containerName string) (int, error) {
seen := newSeen(filePaths)
seen.checkAll()
if seen.complete() {
po.log.Debugf("container '%s': exit early, files already existed", containerName)
return containerIndex, nil
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return -1, err
}
defer watcher.Close()
createEventFileChannel := make(chan int)
errorEventFileChannel := make(chan error)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
continue
}
po.log.Debugf("container '%s': new event for %s", containerName, event.Name)
if event.Op == fsnotify.Create && seen.requires(event.Name) {
po.log.Debugf("container '%s': event for %s", containerName, event.Name)
seen.done(event.Name)
}
if seen.complete() {
createEventFileChannel <- containerIndex
}
case err, ok := <-watcher.Errors:
if !ok {
continue
}
errorEventFileChannel <- err
}
}
}()
err = watcher.Add(filepath.Join(po.outputFilePathPrefix, containerName))
if err != nil {
return -1, err
}
select {
case containerIndex := <-createEventFileChannel:
return containerIndex, nil
case err := <-errorEventFileChannel:
return -1, err
}
}
type seen map[string]bool
func newSeen(files []string) seen {
s := map[string]bool{}
for _, file := range files {
s[file] = false
}
return s
}
func (s seen) requires(key string) bool {
if _, found := s[key]; found {
return true
}
return false
}
func (s seen) done(file string) {
s[file] = true
}
func (s seen) complete() bool {
for _, result := range s {
if !result {
return false
}
}
return true
}
func (s seen) checkAll() {
for file := range s {
if fileExists(file) {
s.done(file)
}
}
}
// fileExists checks if the file exists
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func newLabels(output qjv1a1.Output, additionalSecretLabels map[string]string, container corev1.Container) map[string]string {
labels := map[string]string{}
for k, v := range output.SecretLabels {
labels[k] = names.Sanitize(v)
}
for k, v := range additionalSecretLabels {
labels[k] = names.Sanitize(v)
}
labels[qjv1a1.LabelPersistentSecretContainer] = names.Sanitize(container.Name)
if id, ok := podutil.LookupEnv(container.Env, qjv1a1.RemoteIDKey); ok {
labels[qjv1a1.LabelRemoteID] = id
}
return labels
}
func (po *OutputPersistor) createVersionedSecret(
qJob *qjv1a1.QuarksJob,
name string,
labels map[string]string,
annotations map[string]string,
data map[string]string,
) error {
ownerName := qJob.GetName()
ownerID := qJob.GetUID()
ownerKind := qjv1a1.QuarksJobResourceKind
sourceDescription := "created by quarksJob"
store := versionedsecretstore.NewClientsetVersionedSecretStore(po.clientSet)
err := store.Create(context.Background(), po.namespace, ownerName, ownerID, ownerKind, name, data, annotations, labels, sourceDescription)
if err != nil {
if !versionedsecretstore.IsSecretIdenticalError(err) {
return errors.Wrap(err, "failed to create versioned secret")
}
// No-op. the latest version is identical to the one we have
return nil
}
return nil
}
// createSecret converts the output file into json and creates a secret for a given container
func (po *OutputPersistor) createSecret(
ctx context.Context,
name string,
labels map[string]string,
annotations map[string]string,
data map[string]string,
) error {
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: po.namespace,
},
}
secret.StringData = data
secret.Labels = labels
secret.Annotations = annotations
_, err := po.clientSet.CoreV1().Secrets(po.namespace).Create(ctx, secret, metav1.CreateOptions{})
if err != nil {
if apierrors.IsAlreadyExists(err) {
// If it exists update it
_, err = po.clientSet.CoreV1().Secrets(po.namespace).Update(ctx, secret, metav1.UpdateOptions{})
if err != nil {
return errors.Wrapf(err, "failed to update secret '%s'", name)
}
} else {
return errors.Wrapf(err, "failed to create secret '%s'", name)
}
}
return nil
}