forked from alexellis/run-job
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
377 lines (313 loc) Β· 9.24 KB
/
main.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
package main
import (
"bytes"
"context"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
"time"
"github.com/davecgh/go-spew/spew"
apierrors "k8s.io/apimachinery/pkg/api/errors"
resource "k8s.io/apimachinery/pkg/api/resource"
"github.com/google/uuid"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
watchtools "k8s.io/client-go/tools/watch"
yaml "gopkg.in/yaml.v2"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
// required to authenticate against GKE clusters
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
)
var (
Version string
GitCommit string
)
type Job struct {
JobName string `yaml:"name"`
Image string `yaml:"image"`
Namespace string `yaml:"namespace,omitempty"`
ServiceAccount string `yaml:"service_account,omitempty"`
Command []string `yaml:"command,omitempty"`
Args []string `yaml:"args,omitempty"`
Limits map[string]string `yaml:"limits,omitempty"`
Requests map[string]string `yaml:"requests,omitempty"`
}
func makeResourceList(inputMap map[string]string) corev1.ResourceList {
// Create a new ResourceList
resourceList := corev1.ResourceList{}
// Iterate through the input map and populate the ResourceList
for key, value := range inputMap {
quantity, err := resource.ParseQuantity(value)
if err != nil {
fmt.Printf("Error converting value for key %s: %v\n", key, err)
continue
}
resourceList[corev1.ResourceName(key)] = quantity
}
return resourceList
}
func main() {
var (
kubeconfig string
outFile string
file string
)
flag.StringVar(&outFile, "out", "", "File to write to or leave blank for STDOUT")
flag.StringVar(&kubeconfig, "kubeconfig", "$HOME/.kube/config", "Path to KUBECONFIG")
flag.StringVar(&file, "f", "", "Job to run or leave blank for job.yaml in current directory")
flag.Parse()
if len(file) == 0 {
if stat, err := os.Stat("./job.yaml"); err != nil {
log.Fatal("specify a job file with -f or provide a job file called job.yaml in this directory")
} else {
file = stat.Name()
}
}
jobFile := Job{}
data, err := os.ReadFile(file)
if err != nil {
log.Fatalf("error reading job file %s %s", file, err.Error())
}
err = yaml.Unmarshal(data, &jobFile)
if err != nil {
log.Fatalf("error parsing job file %s %s", file, err.Error())
}
name := jobFile.JobName
image := jobFile.Image
namespace := jobFile.Namespace
sa := jobFile.ServiceAccount
command := jobFile.Command
args := jobFile.Args
requests := jobFile.Requests
limits := jobFile.Limits
if len(namespace) == 0 {
namespace = "default"
}
if len(name) == 0 {
log.Fatalf("--job is required")
}
if len(image) == 0 {
log.Fatalf("--image is required")
}
clientset, err := getClientset(kubeconfig)
if err != nil {
panic(err)
}
if len(sa) > 0 {
if _, err := clientset.CoreV1().
ServiceAccounts(namespace).
Get(context.Background(), sa, metav1.GetOptions{}); err != nil {
if apierrors.IsNotFound(err) {
log.Fatalf("service account %s not found in namespace %s", sa, namespace)
}
}
}
jobID := uuid.New().String()
parallelism := int32(1)
ctx := context.Background()
jobSpec := &batchv1.Job{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
Labels: map[string]string{
"app": "run-job",
"job-id": jobID,
},
},
Spec: batchv1.JobSpec{
Parallelism: ¶llelism,
BackoffLimit: ¶llelism,
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": "run-job",
"job-id": jobID,
},
Name: name,
Namespace: namespace,
},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyNever,
ServiceAccountName: sa,
Containers: []corev1.Container{
{
Image: image,
Name: name,
ImagePullPolicy: corev1.PullAlways,
Command: command,
Args: args,
Resources: corev1.ResourceRequirements{
Requests: makeResourceList(requests),
Limits: makeResourceList(limits),
},
},
},
},
},
},
}
job, err := clientset.BatchV1().
Jobs(namespace).
Create(ctx, jobSpec, metav1.CreateOptions{})
if err != nil {
log.Fatalf("Error creating job: %v", err)
}
fmt.Printf("Created job %s.%s (%s)\n", job.GetName(), job.GetNamespace(), jobID)
if err := watchForJob(clientset, ctx, jobID, job.GetName(), job.Namespace, outFile); err != nil {
log.Fatalf("Error watching job: %v", err)
}
}
func watchForJob(clientset *kubernetes.Clientset, ctx context.Context, jobID, name, namespace, outFile string) error {
listOptions := metav1.ListOptions{
LabelSelector: "job-id=" + jobID,
}
wCtx, cancel := context.WithCancel(ctx)
defer cancel()
rw, err := watchtools.NewRetryWatcher("1", &cache.ListWatch{
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return clientset.BatchV1().Jobs(namespace).Watch(wCtx, listOptions)
},
})
if err != nil {
return fmt.Errorf("error creating label watcher: %s", err.Error())
}
go func() {
<-ctx.Done()
// Cancel the context
rw.Stop()
}()
ch := rw.ResultChan()
//defer rw.Stop()
for event := range ch {
// We need to inspect the event and get ResourceVersion out of it
switch event.Type {
case watch.Added, watch.Modified:
job, ok := event.Object.(*batchv1.Job)
if !ok {
return fmt.Errorf("unable to parse Kubernetes Job from Annotation watcher")
}
done := false
message := ""
failed := false
for _, condition := range job.Status.Conditions {
switch condition.Type {
case batchv1.JobFailed:
failed = true
message = condition.Message
done = true
case batchv1.JobComplete:
failed = false
message = condition.Message
done = true
}
}
fmt.Printf(".")
if done {
if failed {
fmt.Printf("\nJob %s.%s (%s) failed %s\n", name, namespace, jobID, message)
} else {
fmt.Printf("\nJob %s.%s (%s) succeeded %s\n", name, namespace, jobID, message)
}
pods, err := clientset.CoreV1().Pods(namespace).List(wCtx, listOptions)
if err == nil {
podNames := []string{}
for _, pod := range pods.Items {
podNames = append(podNames, pod.Name)
}
logsOut, err := logs(wCtx, clientset, podNames, namespace)
if err != nil {
log.Fatalf("Error getting logs: %v", err)
}
logsOut = "Recorded: " + time.Now().UTC().String() + "\n\n" + logsOut
deletePol := metav1.DeletePropagationBackground
if err := clientset.BatchV1().Jobs(namespace).Delete(wCtx, name, metav1.DeleteOptions{PropagationPolicy: &deletePol}); err != nil {
log.Fatalf("Error deleting job: %v", err)
} else {
fmt.Printf("Deleted job %s\n", name)
}
if len(outFile) > 0 {
if err := ioutil.WriteFile(outFile, []byte(logsOut), os.ModePerm); err != nil {
log.Fatalf("Error writing logs to file: %v", err)
} else {
fmt.Printf("Logs written to: %s", outFile)
}
} else {
fmt.Printf("\n%s\n", logsOut)
}
} else {
log.Fatalf("Error getting pods: %v", err)
}
cancel()
return nil
}
case watch.Deleted:
_, ok := event.Object.(*batchv1.Job)
if !ok {
return fmt.Errorf("unable to parse Kubernetes Job from Annotation watcher")
}
case watch.Bookmark:
// Un-used
case watch.Error:
log.Printf("Error attempting to watch Kubernetes Jobs")
// This round trip allows us to handle unstructured status
errObject := apierrors.FromObject(event.Object)
statusErr, ok := errObject.(*apierrors.StatusError)
if !ok {
log.Printf(spew.Sprintf("received an error which is not *metav1.Status but %#+v", event.Object))
}
status := statusErr.ErrStatus
log.Printf("%v", status)
default:
}
}
return nil
}
func getClientset(kubeconfig string) (*kubernetes.Clientset, error) {
kubeconfig = strings.ReplaceAll(kubeconfig, "$HOME", os.Getenv("HOME"))
kubeconfig = strings.ReplaceAll(kubeconfig, "~", os.Getenv("HOME"))
masterURL := ""
var clientConfig *rest.Config
if _, err := os.Stat(kubeconfig); err != nil {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatalf("Error building in-cluster config: %s", err.Error())
}
clientConfig = config
} else {
config, err := clientcmd.BuildConfigFromFlags(masterURL, kubeconfig)
if err != nil {
log.Fatalf("Error building kubeconfig: %s %s", kubeconfig, err.Error())
}
clientConfig = config
}
clientset, err := kubernetes.NewForConfig(clientConfig)
if err != nil {
return nil, err
}
return clientset, nil
}
func logs(ctx context.Context, clientset *kubernetes.Clientset, pods []string, namespace string) (string, error) {
buf := new(bytes.Buffer)
for _, pod := range pods {
req := clientset.CoreV1().Pods(namespace).GetLogs(pod, &corev1.PodLogOptions{})
stream, err := req.Stream(ctx)
if err != nil {
return "", fmt.Errorf("error while reading %s logs %w", pod, err)
}
_, err = io.Copy(buf, stream)
stream.Close()
if err != nil {
return "", fmt.Errorf("error while reading %s logs %w", pod, err)
}
}
return buf.String(), nil
}