-
Notifications
You must be signed in to change notification settings - Fork 79
/
cronjobs.go
266 lines (236 loc) · 7.11 KB
/
cronjobs.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
// Package cronjobs creates CronJob objects in Kubernetes.
package cronjobs
import (
"context"
"errors"
"fmt"
"math/rand"
"os"
"strings"
"time"
"github.com/aws/aws-k8s-tester/eksconfig"
k8s_client "github.com/aws/aws-k8s-tester/pkg/k8s-client"
"github.com/aws/aws-sdk-go/aws"
"github.com/dustin/go-humanize"
"go.uber.org/zap"
batchv1 "k8s.io/api/batch/v1"
batchv1beta1 "k8s.io/api/batch/v1beta1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/yaml"
)
// Config defines 'CronJob' configuration.
type Config struct {
Logger *zap.Logger
Stopc chan struct{}
Sig chan os.Signal
EKSConfig *eksconfig.Config
K8SClient k8s_client.EKS
}
// 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.AddOnCronJobs.Created {
ts.cfg.Logger.Info("skipping create AddOnCronJob")
return nil
}
ts.cfg.EKSConfig.AddOnCronJobs.Created = true
ts.cfg.EKSConfig.Sync()
createStart := time.Now()
defer func() {
ts.cfg.EKSConfig.AddOnCronJobs.CreateTook = time.Since(createStart)
ts.cfg.EKSConfig.AddOnCronJobs.CreateTookString = ts.cfg.EKSConfig.AddOnCronJobs.CreateTook.String()
ts.cfg.EKSConfig.Sync()
}()
if err := k8s_client.CreateNamespace(ts.cfg.Logger, ts.cfg.K8SClient.KubernetesClientSet(), ts.cfg.EKSConfig.AddOnCronJobs.Namespace); err != nil {
return err
}
obj, b, err := ts.createCronJobs()
if err != nil {
return err
}
ts.cfg.Logger.Info("creating CronJob",
zap.String("name", cronJobName),
zap.Int("completes", ts.cfg.EKSConfig.AddOnCronJobs.Completes),
zap.Int("parallels", ts.cfg.EKSConfig.AddOnCronJobs.Parallels),
zap.String("object-size", humanize.Bytes(uint64(len(b)))),
)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
_, err = ts.cfg.K8SClient.KubernetesClientSet().
BatchV1beta1().
CronJobs(ts.cfg.EKSConfig.AddOnCronJobs.Namespace).
Create(ctx, &obj, metav1.CreateOptions{})
cancel()
if err != nil {
return fmt.Errorf("failed to create CronJob (%v)", err)
}
ts.cfg.Logger.Info("created CronJob")
// take about 4-min for 10 cron jobs to trigger
select {
case <-ts.cfg.Stopc:
ts.cfg.Logger.Warn("wait aborted")
return nil
case <-time.After(2 * time.Minute):
}
waitDur := 3*time.Minute + 10*time.Duration(ts.cfg.EKSConfig.AddOnCronJobs.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.AddOnCronJobs.Namespace,
cronJobName,
int(ts.cfg.EKSConfig.AddOnCronJobs.Completes),
jobsFieldSelector,
v1.PodSucceeded,
)
if err != nil {
return err
}
println()
for _, item := range completedJobs {
fmt.Printf("CronJob 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.AddOnCronJobs.Created {
ts.cfg.Logger.Info("skipping delete AddOnCronJob")
return nil
}
deleteStart := time.Now()
defer func() {
ts.cfg.EKSConfig.AddOnCronJobs.DeleteTook = time.Since(deleteStart)
ts.cfg.EKSConfig.AddOnCronJobs.DeleteTookString = ts.cfg.EKSConfig.AddOnCronJobs.DeleteTook.String()
ts.cfg.EKSConfig.Sync()
}()
var errs []string
ts.cfg.Logger.Info("deleting Job", zap.String("name", cronJobName))
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
err := ts.cfg.
K8SClient.KubernetesClientSet().
BatchV1beta1().
CronJobs(ts.cfg.EKSConfig.AddOnCronJobs.Namespace).
Delete(
ctx,
cronJobName,
metav1.DeleteOptions{
GracePeriodSeconds: aws.Int64(0),
PropagationPolicy: &propagationBackground,
},
)
cancel()
if err != nil {
errs = append(errs, fmt.Sprintf("failed to delete CronJob %q (%v)", cronJobName, err))
}
ts.cfg.Logger.Info("deleted CronJob", zap.String("name", cronJobName))
if err := k8s_client.DeleteNamespaceAndWait(ts.cfg.Logger,
ts.cfg.K8SClient.KubernetesClientSet(),
ts.cfg.EKSConfig.AddOnCronJobs.Namespace,
k8s_client.DefaultNamespaceDeletionInterval,
k8s_client.DefaultNamespaceDeletionTimeout); err != nil {
errs = append(errs, fmt.Sprintf("failed to delete CronJobs namespace (%v)", err))
}
if len(errs) > 0 {
return errors.New(strings.Join(errs, ", "))
}
ts.cfg.EKSConfig.AddOnCronJobs.Created = false
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"
cronJobName = "cronjob-echo"
cronJobEchoImageName = "busybox"
)
func (ts *tester) createCronJobs() (batchv1beta1.CronJob, string, error) {
podSpec := v1.PodTemplateSpec{
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: cronJobName,
Image: cronJobEchoImageName,
ImagePullPolicy: v1.PullAlways,
Command: []string{
"/bin/sh",
"-ec",
fmt.Sprintf("echo -n '%s' >> /config/output.txt", randString(ts.cfg.EKSConfig.AddOnCronJobs.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{},
},
},
},
},
}
jobSpec := batchv1beta1.JobTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Name: jobName,
Namespace: ts.cfg.EKSConfig.AddOnCronJobs.Namespace,
},
Spec: batchv1.JobSpec{
Completions: aws.Int32(int32(ts.cfg.EKSConfig.AddOnCronJobs.Completes)),
Parallelism: aws.Int32(int32(ts.cfg.EKSConfig.AddOnCronJobs.Parallels)),
Template: podSpec,
// TODO: 'TTLSecondsAfterFinished' is still alpha
// https://kubernetes.io/docs/concepts/workloads/controllers/ttlafterfinished/
},
}
cronObj := batchv1beta1.CronJob{
TypeMeta: metav1.TypeMeta{
APIVersion: "batch/v1beta1",
Kind: "CronJob",
},
ObjectMeta: metav1.ObjectMeta{
Name: cronJobName,
Namespace: ts.cfg.EKSConfig.AddOnCronJobs.Namespace,
},
Spec: batchv1beta1.CronJobSpec{
Schedule: ts.cfg.EKSConfig.AddOnCronJobs.Schedule,
SuccessfulJobsHistoryLimit: aws.Int32(ts.cfg.EKSConfig.AddOnCronJobs.SuccessfulJobsHistoryLimit),
FailedJobsHistoryLimit: aws.Int32(ts.cfg.EKSConfig.AddOnCronJobs.FailedJobsHistoryLimit),
JobTemplate: jobSpec,
},
}
b, err := yaml.Marshal(cronObj)
return cronObj, 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)
}