/
propagation_controller.go
217 lines (193 loc) · 7.16 KB
/
propagation_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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/*
Copyright 2023.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controller
import (
"context"
"fmt"
"time"
v1alpha1 "github.com/kuberik/propagation-controller/api/v1alpha1"
"github.com/kuberik/propagation-controller/internal/controller/clients"
"golang.org/x/sync/errgroup"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"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"
kyaml_utils "sigs.k8s.io/kustomize/kyaml/utils"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
// PropagationReconciler reconciles a Propagation object
type PropagationReconciler struct {
client.Client
Scheme *runtime.Scheme
clients.PropagationClientset
}
//+kubebuilder:rbac:groups=kuberik.io,resources=propagations,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=kuberik.io,resources=propagations/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=kuberik.io,resources=propagations/finalizers,verbs=update
// 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 *PropagationReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := log.FromContext(ctx).WithName(req.NamespacedName.String())
propagation := &v1alpha1.Propagation{}
err := r.Client.Get(ctx, req.NamespacedName, propagation)
if err != nil {
return ctrl.Result{}, err
}
propagationClient, err := r.Propagation(*propagation)
if err != nil {
meta.SetStatusCondition(&propagation.Status.Conditions, metav1.Condition{
Type: v1alpha1.ReadyCondition,
Message: err.Error(),
Status: metav1.ConditionFalse,
ObservedGeneration: propagation.Generation,
Reason: "BackendInitFailed",
})
r.Client.Status().Update(ctx, propagation)
return ctrl.Result{}, err
}
version, err := r.getVersion(ctx, *propagation)
if err != nil {
meta.SetStatusCondition(&propagation.Status.Conditions, metav1.Condition{
Type: v1alpha1.ReadyCondition,
Message: err.Error(),
Status: metav1.ConditionFalse,
ObservedGeneration: propagation.Generation,
Reason: "VersionMissing",
})
r.Client.Status().Update(ctx, propagation)
return ctrl.Result{}, err
}
if readyCondition := meta.FindStatusCondition(
propagation.Status.Conditions, v1alpha1.ReadyCondition,
); readyCondition == nil || readyCondition.Status != metav1.ConditionTrue {
meta.SetStatusCondition(&propagation.Status.Conditions, metav1.Condition{
Type: v1alpha1.ReadyCondition,
Status: metav1.ConditionTrue,
Message: "Propagation ready",
ObservedGeneration: propagation.Generation,
Reason: "Ready",
})
if err := r.Client.Status().Update(ctx, propagation); err != nil {
return ctrl.Result{}, err
}
}
// TODO: setting to healthy always for starters because we don't have any health controllers and will at least make controller somewhat useful
deploymentState := v1alpha1.HealthStateHealthy
if propagation.Status.DeploymentStatus.Version != version ||
propagation.Status.DeploymentStatus.State != deploymentState {
propagation.Status.DeploymentStatus = v1alpha1.DeploymentStatus{
Version: version,
State: v1alpha1.HealthStateHealthy,
}
if err := propagationClient.PublishStatus(
propagation.Spec.Deployment.Name,
propagation.Status.DeploymentStatus,
); err != nil {
return ctrl.Result{}, err
}
err = r.Client.Status().Update(ctx, propagation)
if err != nil {
return ctrl.Result{}, nil
}
}
// if status healthy, propagate
// 1. fetch statuses
var getStatusErrors errgroup.Group
reports := make([]v1alpha1.DeploymentStatusesReport, len(propagation.Status.DeployAfter.Deployments))
for i, deployment := range propagation.Status.DeployAfter.Deployments {
report := propagation.Status.FindDeploymentStatusReport(deployment)
if report == nil {
report = &v1alpha1.DeploymentStatusesReport{
DeploymentName: deployment,
}
}
reports[i] = *report
i, deployment := i, deployment
getStatusErrors.Go(func() error {
status, err := propagationClient.GetStatus(deployment)
if err != nil {
return err
}
status.Start = metav1.Now()
reports[i].AppendStatus(*status)
return nil
})
}
statusesErr := getStatusErrors.Wait()
// TODO: Set condition
propagation.Status.DeploymentStatusesReports = reports
err = r.Client.Status().Update(ctx, propagation)
if statusesErr != nil {
return ctrl.Result{}, statusesErr
} else if err != nil {
return ctrl.Result{}, err
}
propagateVersion := propagation.NextVersion()
if propagateVersion == "" {
// TODO: Calculate from status how long to wait
log.Info("No candidate version to propagate")
return ctrl.Result{
Requeue: true,
RequeueAfter: 60 * time.Second,
}, nil
}
log.Info(fmt.Sprintf("Propagating to version %s", propagateVersion))
if err := propagationClient.Propagate(propagation.Spec.Deployment.Name, propagateVersion); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
func (r *PropagationReconciler) getVersion(ctx context.Context, propagation v1alpha1.Propagation) (string, error) {
versionObject := &unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": propagation.Spec.Deployment.Version.APIVersion,
"kind": propagation.Spec.Deployment.Version.Kind,
},
}
if propagation.Spec.Deployment.Version.Name == "" {
return "", fmt.Errorf("missing version's object name")
}
if propagation.Spec.Deployment.Version.FieldPath == "" {
return "", fmt.Errorf("missing version's object fieldPath")
}
err := r.Client.Get(ctx, types.NamespacedName{Name: propagation.Spec.Deployment.Version.Name, Namespace: propagation.Namespace}, versionObject)
if err != nil {
return "", err
}
objRNode, err := yaml.FromMap(versionObject.Object)
if err != nil {
return "", err
}
fieldPath := kyaml_utils.SmarterPathSplitter(propagation.Spec.Deployment.Version.FieldPath, ".")
rn, err := objRNode.Pipe(yaml.Lookup(fieldPath...))
if err != nil {
return "", fmt.Errorf("error looking up version path: %w", err)
}
if rn.IsNilOrEmpty() {
return "", fmt.Errorf("version is empty")
}
if !rn.IsStringValue() {
return "", fmt.Errorf("version field is not a string")
}
return rn.Document().Value, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *PropagationReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&v1alpha1.Propagation{}).
Complete(r)
}