-
Notifications
You must be signed in to change notification settings - Fork 79
/
jobs.go
277 lines (248 loc) · 6.95 KB
/
jobs.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
// Package jobsecho creates Job objects in Kubernetes.
package jobsecho
import (
"fmt"
"math/rand"
"os"
"strings"
"time"
"github.com/aws/aws-k8s-tester/eksconfig"
"github.com/aws/aws-sdk-go/aws"
"github.com/dustin/go-humanize"
"go.uber.org/zap"
batchv1 "k8s.io/api/batch/v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
clientset "k8s.io/client-go/kubernetes"
"sigs.k8s.io/yaml"
)
// Config defines 'Job' configuration.
type Config struct {
Logger *zap.Logger
Stopc chan struct{}
Sig chan os.Signal
EKSConfig *eksconfig.Config
K8SClient k8sClientSetGetter
}
type k8sClientSetGetter interface {
KubernetesClientSet() *clientset.Clientset
}
// Tester defines Job tester.
type Tester interface {
// Create creates Job objects, and waits for completion.
Create() error
// Delete deletes all Job objects.
Delete() error
}
// New creates a new Job tester.
func New(cfg Config) (Tester, error) {
return &tester{cfg: cfg}, nil
}
type tester struct {
cfg Config
}
func (ts *tester) Create() error {
if ts.cfg.EKSConfig.AddOnJobEcho.Created {
ts.cfg.Logger.Info("skipping create AddOnJobEcho")
return nil
}
ts.cfg.EKSConfig.AddOnJobEcho.Created = true
ts.cfg.EKSConfig.Sync()
createStart := time.Now()
defer func() {
ts.cfg.EKSConfig.AddOnJobEcho.CreateTook = time.Since(createStart)
ts.cfg.EKSConfig.AddOnJobEcho.CreateTookString = ts.cfg.EKSConfig.AddOnJobEcho.CreateTook.String()
ts.cfg.EKSConfig.Sync()
}()
if err := ts.createNamespace(); err != nil {
return err
}
obj, b, err := ts.createObject()
if err != nil {
return err
}
ts.cfg.Logger.Info("creating Job",
zap.String("name", jobName),
zap.Int("completes", ts.cfg.EKSConfig.AddOnJobEcho.Completes),
zap.Int("parallels", ts.cfg.EKSConfig.AddOnJobEcho.Parallels),
zap.String("object-size", humanize.Bytes(uint64(len(b)))),
)
_, err = ts.cfg.K8SClient.KubernetesClientSet().
BatchV1().
Jobs(ts.cfg.EKSConfig.AddOnJobEcho.Namespace).
Create(&obj)
if err != nil {
return fmt.Errorf("failed to create Job (%v)", err)
}
ts.cfg.Logger.Info("created Job")
waitDur := 3*time.Minute + 10*time.Duration(ts.cfg.EKSConfig.AddOnJobEcho.Completes)*time.Second
completedJobs, err := waitJobs(
ts.cfg.Logger,
ts.cfg.Stopc,
ts.cfg.Sig,
ts.cfg.K8SClient.KubernetesClientSet(),
waitDur,
5*time.Second,
ts.cfg.EKSConfig.AddOnJobEcho.Namespace,
jobName,
int(ts.cfg.EKSConfig.AddOnJobEcho.Completes),
jobsFieldSelector,
v1.PodSucceeded,
)
if err != nil {
return err
}
println()
for _, item := range completedJobs {
fmt.Printf("Job Pod %q: %q\n", item.Name, item.Status.Phase)
}
println()
return nil
}
var propagationBackground = metav1.DeletePropagationBackground
func (ts *tester) Delete() error {
if !ts.cfg.EKSConfig.AddOnJobEcho.Created {
ts.cfg.Logger.Info("skipping delete AddOnJobPi")
return nil
}
deleteStart := time.Now()
defer func() {
ts.cfg.EKSConfig.AddOnJobEcho.DeleteTook = time.Since(deleteStart)
ts.cfg.EKSConfig.AddOnJobEcho.DeleteTookString = ts.cfg.EKSConfig.AddOnJobEcho.DeleteTook.String()
ts.cfg.EKSConfig.Sync()
}()
ts.cfg.Logger.Info("deleting Job", zap.String("name", jobName))
err := ts.cfg.
K8SClient.KubernetesClientSet().
BatchV1().
Jobs(ts.cfg.EKSConfig.AddOnJobEcho.Namespace).
Delete(
jobName,
&metav1.DeleteOptions{
GracePeriodSeconds: aws.Int64(0),
PropagationPolicy: &propagationBackground,
},
)
if err != nil {
return fmt.Errorf("failed to delete Job %q (%v)", jobName, err)
}
ts.cfg.Logger.Info("deleted Job", zap.String("name", jobName))
if err := ts.deleteNamespace(); err != nil {
return err
}
ts.cfg.EKSConfig.AddOnJobEcho.Created = false
return ts.cfg.EKSConfig.Sync()
}
func (ts *tester) createNamespace() error {
ts.cfg.Logger.Info("creating namespace", zap.String("namespace", ts.cfg.EKSConfig.AddOnJobEcho.Namespace))
_, err := ts.cfg.K8SClient.KubernetesClientSet().
CoreV1().
Namespaces().
Create(&v1.Namespace{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Namespace",
},
ObjectMeta: metav1.ObjectMeta{
Name: ts.cfg.EKSConfig.AddOnJobEcho.Namespace,
Labels: map[string]string{
"name": ts.cfg.EKSConfig.AddOnJobEcho.Namespace,
},
},
})
if err != nil {
return err
}
ts.cfg.Logger.Info("created namespace", zap.String("namespace", ts.cfg.EKSConfig.AddOnJobEcho.Namespace))
return ts.cfg.EKSConfig.Sync()
}
func (ts *tester) deleteNamespace() error {
ts.cfg.Logger.Info("deleting namespace", zap.String("namespace", ts.cfg.EKSConfig.AddOnJobEcho.Namespace))
foreground := metav1.DeletePropagationForeground
err := ts.cfg.K8SClient.KubernetesClientSet().
CoreV1().
Namespaces().
Delete(
ts.cfg.EKSConfig.AddOnJobEcho.Namespace,
&metav1.DeleteOptions{
GracePeriodSeconds: aws.Int64(0),
PropagationPolicy: &foreground,
},
)
if err != nil {
// ref. https://github.com/aws/aws-k8s-tester/issues/79
if !strings.Contains(err.Error(), ` not found`) {
return err
}
}
ts.cfg.Logger.Info("deleted namespace", zap.Error(err))
return ts.cfg.EKSConfig.Sync()
}
const (
// https://github.com/kubernetes/kubernetes/blob/d379ab2697251334774b7bd6f41b26cf39de470d/pkg/apis/batch/v1/conversion.go#L30-L41
jobsFieldSelector = "status.phase!=Running"
jobName = "job-echo"
jobEchoImageName = "busybox"
)
func (ts *tester) createObject() (batchv1.Job, string, error) {
podSpec := v1.PodTemplateSpec{
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: jobName,
Image: jobEchoImageName,
ImagePullPolicy: v1.PullAlways,
Command: []string{
"/bin/sh",
"-ec",
fmt.Sprintf("echo -n '%s' >> /config/output.txt", randString(ts.cfg.EKSConfig.AddOnJobEcho.EchoSize)),
},
VolumeMounts: []v1.VolumeMount{
{
Name: "config",
MountPath: "/config",
},
},
},
},
// spec.template.spec.restartPolicy: Unsupported value: "Always": supported values: "OnFailure", "Never"
RestartPolicy: v1.RestartPolicyOnFailure,
Volumes: []v1.Volume{
{
Name: "config",
VolumeSource: v1.VolumeSource{
EmptyDir: &v1.EmptyDirVolumeSource{},
},
},
},
},
}
jobObj := batchv1.Job{
TypeMeta: metav1.TypeMeta{
APIVersion: "batch/v1",
Kind: "Job",
},
ObjectMeta: metav1.ObjectMeta{
Name: jobName,
Namespace: ts.cfg.EKSConfig.AddOnJobEcho.Namespace,
},
Spec: batchv1.JobSpec{
Completions: aws.Int32(int32(ts.cfg.EKSConfig.AddOnJobEcho.Completes)),
Parallelism: aws.Int32(int32(ts.cfg.EKSConfig.AddOnJobEcho.Parallels)),
Template: podSpec,
// TODO: 'TTLSecondsAfterFinished' is still alpha
// https://kubernetes.io/docs/concepts/workloads/controllers/ttlafterfinished/
},
}
b, err := yaml.Marshal(jobObj)
return jobObj, string(b), err
}
const ll = "0123456789abcdefghijklmnopqrstuvwxyz"
func randString(n int) string {
b := make([]byte, n)
for i := range b {
rand.Seed(time.Now().UnixNano())
b[i] = ll[rand.Intn(len(ll))]
}
return string(b)
}