/
job.go
93 lines (82 loc) · 2.53 KB
/
job.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
// Job handles the internal representation of a job and it's context.
package job
import (
"context"
"github.com/vshn/k8up/api/v1alpha1"
k8upv1alpha1 "github.com/vshn/k8up/api/v1alpha1"
"github.com/vshn/k8up/cfg"
"github.com/go-logr/logr"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const (
// K8uplabel is a label that is required for the operator to differentiate
// batchv1.job objects managed by k8up from others.
K8uplabel = "k8upjob"
// K8upExclusive is needed to determine if a given job is considered exclusive or not.
K8upExclusive = "k8upjob/exclusive"
)
// Config represents the whole context for a given job. It contains everything
// that is necessary to handle the job.
type Config struct {
Client client.Client
Log logr.Logger
CTX context.Context
Obj Object
Scheme *runtime.Scheme
Repository string
}
// Object is an interface that must be implemented by all CRDs that implement a
// job.
type Object interface {
GetMetaObject() metav1.Object
GetRuntimeObject() runtime.Object
GetStatus() k8upv1alpha1.Status
SetStatus(s k8upv1alpha1.Status)
GetType() v1alpha1.JobType
GetResources() corev1.ResourceRequirements
}
// NewConfig returns a new configuration.
func NewConfig(ctx context.Context, client client.Client, log logr.Logger, obj Object, scheme *runtime.Scheme, repository string) Config {
return Config{
Client: client,
Log: log,
CTX: ctx,
Obj: obj,
Scheme: scheme,
Repository: repository,
}
}
// GenerateGenericJob returns a generic batchv1.job for further use.
func GenerateGenericJob(obj Object, config Config) (*batchv1.Job, error) {
job := &batchv1.Job{
ObjectMeta: metav1.ObjectMeta{
Name: obj.GetMetaObject().GetName(),
Namespace: obj.GetMetaObject().GetNamespace(),
Labels: map[string]string{
K8uplabel: "true",
k8upv1alpha1.LabelK8upType: obj.GetType().String(),
},
},
Spec: batchv1.JobSpec{
Template: corev1.PodTemplateSpec{
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyOnFailure,
Containers: []corev1.Container{
{
Name: obj.GetMetaObject().GetName(),
Image: cfg.Config.BackupImage,
Resources: config.Obj.GetResources(),
},
},
},
},
},
}
err := ctrl.SetControllerReference(obj.GetMetaObject(), job, config.Scheme)
return job, err
}