-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjob_controller.go
195 lines (155 loc) · 5.22 KB
/
job_controller.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
package controller
import (
"context"
"fmt"
"os/exec"
"strings"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
dismasv1 "dismas/api/v1"
)
// Event describes a Job.
type Event struct {
Command string
Args []string
}
// IsEqual tell wether two Event is same (Command and args).
func (lhs Event) isEqual(rhs Event) bool {
if lhs.Command != rhs.Command {
return false
}
if len(lhs.Args) != len(rhs.Args) {
return false
}
for idx, arg := range lhs.Args {
if arg != rhs.Args[idx] {
return false
}
}
return true
}
// JobReconciler reconciles a Job object.
type JobReconciler struct {
client.Client
Scheme *runtime.Scheme
// LastEvents keeps track of namespace-name => lastevent
LastEvents map[string]Event
Podname string
}
//+kubebuilder:rbac:groups=crd.dismas.org,resources=jobs,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=crd.dismas.org,resources=jobs/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=crd.dismas.org,resources=jobs/finalizers,verbs=update
const maxRetry = 7
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
func (r *JobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logr := log.FromContext(ctx)
// TODO: only in debug
logr.Info("Receiving an event to handle for job " + req.Name)
// 1. Fetch the job and deal with delete event
var job dismasv1.Job
err := r.Get(ctx, req.NamespacedName, &job)
if apierrors.IsNotFound(err) {
r.processDelete(ctx, req.Namespace, req.Name)
logr.Info("already removed job: " + req.Name)
return reconcileDone(), nil
} else if err != nil {
return requeueAfter(), client.IgnoreNotFound(err)
}
// 2. Deal with update event triggered by operator itselef
newEvent := Event{Command: job.Spec.Command, Args: job.Spec.Args}
if !r.isRepeatEvent(newEvent, req.NamespacedName) {
logr.Info("Refuse to exec a repeat job " + req.Name)
return reconcileDone(), nil
}
// 3. Deal with create or update event, execute the command
logr.Info("Execute command for " + req.Name)
stdout, stderr, cmderr := r.execute(job.Spec.Command, job.Spec.Args)
// 4. CAS update the status
return r.tryUpdateStatus(ctx, job, stdout, stderr, cmderr, newEvent)
}
// SetupWithManager sets up the controller with the Manager.
func (r *JobReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&dismasv1.Job{}).
Complete(r)
}
// processDelete removes a deleted Job's last event tracked in cache.
func (r *JobReconciler) processDelete(ctx context.Context, namespace string, name string) {
log.Log.Info("delete " + name)
key := NameToKey(namespace, name)
if _, ok := r.LastEvents[key]; ok {
delete(r.LastEvents, key)
log.Log.Info("delete cache for ", key)
}
}
// updateIfNotRepeatedEvent return false if is a repeated event
func (r *JobReconciler) isRepeatEvent(newEvent Event, namespacedname types.NamespacedName) bool {
key := NameToKey(namespacedname.Namespace, namespacedname.Name)
if lastEvent, ok := r.LastEvents[key]; ok {
if lastEvent.isEqual(newEvent) {
return false
}
}
return true
}
// execute run a command with its args.
func (r *JobReconciler) execute(command string, args []string) (string, string, error) {
cmd := exec.Command(command, args...)
var output, cmderr strings.Builder
cmd.Stdout = &output
cmd.Stderr = &cmderr
err := cmd.Run()
return output.String(), cmderr.String(), err
}
// updateJobStatus checks job and updates datas.
func (r *JobReconciler) updateJobStatus(ctx context.Context, job *dismasv1.Job,
stdout string, stderr string, err error) error {
checkJobMapIsNotNil(job)
job.Status.Stdouts[r.Podname] = stdout
job.Status.Stderrs[r.Podname] = stderr
if err != nil {
job.Status.Errors[r.Podname] = err.Error()
}
return r.Status().Update(ctx, job)
}
func (r *JobReconciler) tryUpdateStatus(ctx context.Context, job dismasv1.Job,
stdout string, stderr string, cmderr error, event Event) (ctrl.Result, error) {
for retryTime := 0; retryTime <= maxRetry; retryTime++ {
err := r.updateJobStatus(ctx, &job, stdout, stderr, cmderr)
// Successfully updated status
if err == nil {
key := NameToKey(job.Namespace, job.Name)
r.LastEvents[key] = event
return reconcileDone(), nil
}
// Unexpected errors
if !apierrors.IsConflict(err) {
return reconcileDone(), err
}
// Conflict, retry updating
if err := r.Get(ctx, types.NamespacedName{Namespace: job.Namespace, Name: job.Name}, &job); err != nil {
return requeueAfter(), client.IgnoreNotFound(err)
}
}
return reconcileDone(), nil
}
func NameToKey(namespace string, name string) string {
return fmt.Sprintf("%s-%s", namespace, name)
}
// checkJobMapIsNil make sures maps in Job is initialized.
func checkJobMapIsNotNil(job *dismasv1.Job) {
if job.Status.Stdouts == nil {
job.Status.Stdouts = make(map[string]string)
}
if job.Status.Stderrs == nil {
job.Status.Stderrs = make(map[string]string)
}
if job.Status.Errors == nil {
job.Status.Errors = make(map[string]string)
}
}