-
Notifications
You must be signed in to change notification settings - Fork 4
/
terraform_controller_operation.go
237 lines (174 loc) · 6.82 KB
/
terraform_controller_operation.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
package controllers
import (
"context"
"errors"
"fmt"
"time"
"github.com/kuptan/terraform-operator/api/v1alpha1"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
)
func (r *TerraformReconciler) updateRunStatus(ctx context.Context, run *v1alpha1.Terraform, status v1alpha1.TerraformRunStatus) {
run.Status.RunStatus = status
// set completion time of the run only if status is completed/failed
if status == v1alpha1.RunCompleted || status == v1alpha1.RunFailed {
run.Status.CompletionTime = time.Now().Format(time.UnixDate)
}
// record the status only if completed/failed/waiting
if status == v1alpha1.RunCompleted || status == v1alpha1.RunFailed || status == v1alpha1.RunWaitingForDependency {
r.MetricsRecorder.RecordStatus(run.Name, run.Namespace, status)
}
if err := r.Status().Update(ctx, run); err != nil {
r.Log.Error(err, "failed to update status")
}
}
func (r *TerraformReconciler) handleRunCreate(ctx context.Context, run *v1alpha1.Terraform, namespacedName types.NamespacedName) (ctrl.Result, error) {
dependencies, err := r.checkDependencies(ctx, *run)
run.Status.ObservedGeneration = run.Generation
if err != nil {
if !run.IsWaiting() {
r.Recorder.Event(run, "Normal", "Waiting", "Dependencies are not yet completed")
r.updateRunStatus(ctx, run, v1alpha1.RunWaitingForDependency)
}
return ctrl.Result{
RequeueAfter: r.requeueDependency,
}, nil
}
run.SetRunID()
r.Log.Info("cleaning up old resources if exist")
setVariablesFromDependencies(run, dependencies)
_, err = run.CreateTerraformRun(ctx, namespacedName)
if err != nil {
r.Log.Error(err, "failed create a terraform run")
r.updateRunStatus(ctx, run, v1alpha1.RunFailed)
return ctrl.Result{}, err
}
if err = run.CleanupResources(ctx); err != nil {
r.Log.Error(err, "failed to cleanup resources")
}
run.Status.OutputSecretName = run.GetOutputSecretName()
run.Status.StartedTime = time.Now().Format(time.UnixDate)
r.updateRunStatus(ctx, run, v1alpha1.RunStarted)
return ctrl.Result{}, nil
}
func (r *TerraformReconciler) handleRunUpdate(ctx context.Context, run *v1alpha1.Terraform, namespacedName types.NamespacedName) (ctrl.Result, error) {
r.Recorder.Event(run, "Normal", "Updated", "Creating a new run job")
return r.handleRunCreate(ctx, run, namespacedName)
}
func (r *TerraformReconciler) handleRunDelete(ctx context.Context, run *v1alpha1.Terraform) (ctrl.Result, error) {
r.Log.Info("terraform run is being deleted", "name", run.Name)
r.MetricsRecorder.RecordStatus(run.Name, run.Namespace, v1alpha1.RunDeleted)
controllerutil.RemoveFinalizer(run, v1alpha1.TerraformFinalizer)
if err := r.Update(ctx, run); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
func (r *TerraformReconciler) handleRunJobWatch(ctx context.Context, run *v1alpha1.Terraform) (ctrl.Result, error) {
job, err := run.GetJobByRun(ctx)
r.Log.Info("waiting for terraform job run to complete", "name", job.Name)
if err != nil {
return ctrl.Result{}, err
}
startTime, err := time.Parse(time.UnixDate, run.Status.StartedTime)
if err != nil {
r.Log.Error(err, "failed to parse workflow start time")
}
defer r.MetricsRecorder.RecordDuration(run.Name, run.Namespace, startTime)
// job hasn't started
if job.Status.Active == 0 && job.Status.Succeeded == 0 && job.Status.Failed == 0 {
return ctrl.Result{RequeueAfter: r.requeueJobWatch}, nil
}
// job is still running
if job.Status.Active > 0 {
if !run.IsRunning() {
r.updateRunStatus(ctx, run, v1alpha1.RunRunning)
r.Recorder.Event(run, "Normal", "Running", fmt.Sprintf("Run(%s) waiting for run job to finish", run.Status.RunID))
}
return ctrl.Result{RequeueAfter: r.requeueJobWatch}, nil
}
// job is successful
if job.Status.Succeeded > 0 {
r.Log.Info("terraform run job completed successfully")
if run.Spec.DeleteCompletedJobs {
r.Log.Info("deleting completed job")
if err := run.DeleteAfterCompletion(ctx); err != nil {
r.Log.Error(err, "failed to delete terraform run job after completion", "name", job.Name)
} else {
r.Recorder.Event(run, "Normal", "Cleanup", fmt.Sprintf("Run(%s) kubernetes job was deleted", run.Status.RunID))
}
}
if !run.Spec.Destroy {
r.Recorder.Event(run, "Normal", "Completed", fmt.Sprintf("Run(%s) completed", run.Status.RunID))
} else {
r.Recorder.Event(run, "Normal", "Destroyed", fmt.Sprintf("Run(%s) completed with terraform destroy", run.Status.RunID))
}
r.updateRunStatus(ctx, run, v1alpha1.RunCompleted)
return ctrl.Result{}, nil
}
// if it got here, then the job is failed -- sadly .... :( :( :(
r.Recorder.Event(run, "Warning", "Failed", fmt.Sprintf("Run(%s) failed", run.Status.RunID))
r.Log.Error(errors.New("job failed"), "terraform run job failed to complete", "name", job.Name)
r.updateRunStatus(ctx, run, v1alpha1.RunFailed)
return ctrl.Result{}, nil
}
func (r *TerraformReconciler) checkDependencies(ctx context.Context, run v1alpha1.Terraform) ([]v1alpha1.Terraform, error) {
dependencies := []v1alpha1.Terraform{}
for _, d := range run.Spec.DependsOn {
if d.Namespace == "" {
d.Namespace = run.Namespace
}
dName := types.NamespacedName{
Namespace: d.Namespace,
Name: d.Name,
}
var dRun v1alpha1.Terraform
err := r.Get(ctx, dName, &dRun)
if err != nil {
return dependencies, fmt.Errorf("unable to get '%s' dependency: %w", dName, err)
}
if dRun.Generation != dRun.Status.ObservedGeneration {
return dependencies, fmt.Errorf("dependency '%s' is not ready", dName)
}
if dRun.Status.RunStatus != v1alpha1.RunCompleted {
return dependencies, fmt.Errorf("dependency '%s' is not ready", dName)
}
dependencies = append(dependencies, dRun)
}
return dependencies, nil
}
// setVariablesFromDependencies sets the variable from the output of a dependency
// this currently only works with runs within the same namespace
func setVariablesFromDependencies(run *v1alpha1.Terraform, dependencies []v1alpha1.Terraform) {
if len(dependencies) == 0 {
return
}
for _, v := range run.Spec.Variables {
if v.DependencyRef == nil {
continue
}
for index, d := range dependencies {
if d.Name == v.DependencyRef.Name && d.Namespace == run.Namespace {
tfVarRef := &v1.EnvVarSource{
SecretKeyRef: &v1.SecretKeySelector{
Key: v.DependencyRef.Key,
LocalObjectReference: v1.LocalObjectReference{
Name: d.Status.OutputSecretName,
},
},
}
tfVar := v1alpha1.Variable{
Key: v.Key,
DependencyRef: v.DependencyRef,
ValueFrom: tfVarRef,
}
// remove the current variable from the list
run.Spec.Variables = append(run.Spec.Variables[:index], run.Spec.Variables[index+1:]...)
// add a new variable with the valueFrom
run.Spec.Variables = append(run.Spec.Variables, tfVar)
}
}
}
}