-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.go
More file actions
368 lines (307 loc) · 12.4 KB
/
controller.go
File metadata and controls
368 lines (307 loc) · 12.4 KB
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
package scalityuicomponent
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/intstr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
uiv1alpha1 "github.com/scality/ui-operator/api/v1alpha1"
)
// DefaultServicePort is the default port used to connect to the UI component service
const DefaultServicePort = 80
// MicroAppConfig represents the structure of the micro-app-configuration file
type MicroAppConfig struct {
Kind string `json:"kind"`
ApiVersion string `json:"apiVersion"`
Metadata ConfigMeta `json:"metadata"`
Spec ConfigSpec `json:"spec"`
}
// ConfigMeta represents the metadata section of the micro-app-configuration
type ConfigMeta struct {
Kind string `json:"kind"`
}
// ConfigSpec represents the spec section of the micro-app-configuration
type ConfigSpec struct {
RemoteEntryPath string `json:"remoteEntryPath"`
PublicPath string `json:"publicPath"`
Version string `json:"version"`
}
// ConfigFetcher defines an interface for fetching UI component configurations
type ConfigFetcher interface {
FetchConfig(ctx context.Context, namespace, serviceName string, port int) (string, error)
}
// K8sServiceProxyFetcher implements ConfigFetcher using Kubernetes service proxy
type K8sServiceProxyFetcher struct {
// Config *rest.Config // No longer needed for direct HTTP GET
}
// FetchConfig retrieves the micro-app configuration from the specified service
func (f *K8sServiceProxyFetcher) FetchConfig(ctx context.Context, namespace, serviceName string, port int) (string, error) {
logger := ctrl.LoggerFrom(ctx)
// Construct the in-cluster service URL
// Example: http://my-service.my-namespace.svc.cluster.local:80/.well-known/micro-app-configuration
url := fmt.Sprintf("http://%s.%s.svc.cluster.local:%d/.well-known/micro-app-configuration", serviceName, namespace, port)
logger.Info("Fetching configuration via direct HTTP GET", "url", url)
httpClient := &http.Client{
Timeout: 10 * time.Second, // Add a timeout for the HTTP request
}
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
logger.Error(err, "Failed to create HTTP request")
return "", err
}
resp, err := httpClient.Do(req)
if err != nil {
logger.Error(err, "Failed to get configuration via direct HTTP GET")
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err := fmt.Errorf("failed to fetch configuration, status code: %d", resp.StatusCode)
logger.Error(err, "Failed to fetch configuration")
return "", err
}
body, err := io.ReadAll(resp.Body)
if err != nil {
logger.Error(err, "Failed to read response body")
return "", err
}
logger.Info("Successfully fetched configuration", "length", len(body))
return string(body), nil
}
// ScalityUIComponentReconciler reconciles a ScalityUIComponent object
type ScalityUIComponentReconciler struct {
client.Client
Scheme *runtime.Scheme
ConfigFetcher ConfigFetcher
}
// NewScalityUIComponentReconciler creates a new ScalityUIComponentReconciler
func NewScalityUIComponentReconciler(client client.Client, scheme *runtime.Scheme) *ScalityUIComponentReconciler {
return &ScalityUIComponentReconciler{
Client: client,
Scheme: scheme,
ConfigFetcher: &K8sServiceProxyFetcher{},
}
}
// +kubebuilder:rbac:groups=ui.scality.com,resources=scalityuicomponents,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=ui.scality.com,resources=scalityuicomponents/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=ui.scality.com,resources=scalityuicomponents/finalizers,verbs=update
func (r *ScalityUIComponentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := ctrl.LoggerFrom(ctx)
scalityUIComponent := &uiv1alpha1.ScalityUIComponent{}
if err := r.Get(ctx, req.NamespacedName, scalityUIComponent); err != nil {
logger.Error(err, "Failed to get ScalityUIComponent")
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// Deployment
deployment := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: scalityUIComponent.Name,
Namespace: scalityUIComponent.Namespace,
},
}
deploymentResult, err := ctrl.CreateOrUpdate(ctx, r.Client, deployment, func() error {
// Set the ScalityUIComponent as the owner of this Deployment
if err := controllerutil.SetControllerReference(scalityUIComponent, deployment, r.Scheme); err != nil {
return err
}
// Preserve existing volumes and annotations if they exist
existingVolumes := deployment.Spec.Template.Spec.Volumes
existingAnnotations := deployment.Spec.Template.Annotations
// Preserve existing volume mounts for each container
var existingVolumeMounts [][]corev1.VolumeMount
if len(deployment.Spec.Template.Spec.Containers) > 0 {
existingVolumeMounts = make([][]corev1.VolumeMount, len(deployment.Spec.Template.Spec.Containers))
for i, container := range deployment.Spec.Template.Spec.Containers {
existingVolumeMounts[i] = container.VolumeMounts
}
}
// Use imagePullSecrets directly
imagePullSecrets := append([]corev1.LocalObjectReference{}, scalityUIComponent.Spec.ImagePullSecrets...)
deployment.Spec = appsv1.DeploymentSpec{
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": scalityUIComponent.Name,
},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": scalityUIComponent.Name,
},
Annotations: existingAnnotations,
},
Spec: corev1.PodSpec{
Volumes: existingVolumes,
ImagePullSecrets: imagePullSecrets,
Containers: []corev1.Container{
{
Name: scalityUIComponent.Name,
Image: scalityUIComponent.Spec.Image,
},
},
},
},
}
// Restore volume mounts for all containers if they existed
if len(existingVolumeMounts) > 0 {
for i := 0; i < len(existingVolumeMounts) && i < len(deployment.Spec.Template.Spec.Containers); i++ {
if len(existingVolumeMounts[i]) > 0 {
deployment.Spec.Template.Spec.Containers[i].VolumeMounts = existingVolumeMounts[i]
}
}
}
// Apply tolerations from CR spec
if scalityUIComponent.Spec.Scheduling != nil && len(scalityUIComponent.Spec.Scheduling.Tolerations) > 0 {
deployment.Spec.Template.Spec.Tolerations = scalityUIComponent.Spec.Scheduling.Tolerations
}
return nil
})
if err != nil {
logger.Error(err, "Failed to create or update Deployment")
return ctrl.Result{}, err
}
logger.Info("Deployment reconciled", "result", deploymentResult)
// Service
service := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: scalityUIComponent.Name,
Namespace: scalityUIComponent.Namespace,
},
}
serviceResult, err := ctrl.CreateOrUpdate(ctx, r.Client, service, func() error {
// Set the ScalityUIComponent as the owner of this Service
if err := controllerutil.SetControllerReference(scalityUIComponent, service, r.Scheme); err != nil {
return err
}
service.Spec = corev1.ServiceSpec{
Selector: map[string]string{
"app": scalityUIComponent.Name,
},
Ports: []corev1.ServicePort{
{
Name: "http",
Port: DefaultServicePort,
Protocol: corev1.ProtocolTCP,
TargetPort: intstr.FromInt(DefaultServicePort),
},
},
}
return nil
})
if err != nil {
logger.Error(err, "Failed to create or update Service")
return ctrl.Result{}, err
}
logger.Info("Service reconciled", "result", serviceResult)
// Process UI component configuration
return r.processUIComponentConfig(ctx, scalityUIComponent)
}
func (r *ScalityUIComponentReconciler) processUIComponentConfig(ctx context.Context, scalityUIComponent *uiv1alpha1.ScalityUIComponent) (ctrl.Result, error) {
logger := ctrl.LoggerFrom(ctx)
// Check if the service is ready
service := &corev1.Service{}
err := r.Get(ctx, client.ObjectKey{Name: scalityUIComponent.Name, Namespace: scalityUIComponent.Namespace}, service)
if err != nil {
logger.Info("Service not ready yet, will retry", "error", err.Error())
return ctrl.Result{RequeueAfter: 5 * time.Second}, nil
}
// Check if the deployment is ready
deployment := &appsv1.Deployment{}
err = r.Get(ctx, client.ObjectKey{Name: scalityUIComponent.Name, Namespace: scalityUIComponent.Namespace}, deployment)
if err != nil {
logger.Info("Deployment not found yet, will retry", "error", err.Error())
return ctrl.Result{RequeueAfter: 5 * time.Second}, nil
}
// Check if deployment has ready replicas
if deployment.Status.ReadyReplicas == 0 {
logger.Info("Deployment not ready yet (0 ready replicas), will retry")
return ctrl.Result{Requeue: true}, nil
}
// Check if configuration was already retrieved successfully
existingCond := meta.FindStatusCondition(scalityUIComponent.Status.Conditions, "ConfigurationRetrieved")
if existingCond != nil && existingCond.Status == metav1.ConditionTrue {
logger.Info("Configuration already retrieved successfully, skipping fetch")
return ctrl.Result{}, nil
}
// Fetch micro-app configuration
configContent, err := r.fetchMicroAppConfig(ctx, scalityUIComponent.Namespace, scalityUIComponent.Name)
if err != nil {
logger.Error(err, "Failed to fetch micro-app configuration")
// Set ConfigurationRetrieved=False condition
meta.SetStatusCondition(&scalityUIComponent.Status.Conditions, metav1.Condition{
Type: "ConfigurationRetrieved",
Status: metav1.ConditionFalse,
Reason: "FetchFailed",
Message: fmt.Sprintf("Failed to fetch configuration: %v", err),
})
// Update the status
if statusErr := r.Status().Update(ctx, scalityUIComponent); statusErr != nil {
logger.Error(statusErr, "Failed to update ScalityUIComponent status after fetch failure")
}
return ctrl.Result{Requeue: true}, nil
}
// Parse and apply configuration
return r.parseAndApplyConfig(ctx, scalityUIComponent, configContent)
}
func (r *ScalityUIComponentReconciler) parseAndApplyConfig(ctx context.Context,
scalityUIComponent *uiv1alpha1.ScalityUIComponent, configContent string) (ctrl.Result, error) {
logger := ctrl.LoggerFrom(ctx)
var config MicroAppConfig
if err := json.Unmarshal([]byte(configContent), &config); err != nil {
logger.Error(err, "Failed to parse micro-app configuration")
// Set ConfigurationRetrieved=False condition with ParseFailed reason
meta.SetStatusCondition(&scalityUIComponent.Status.Conditions, metav1.Condition{
Type: "ConfigurationRetrieved",
Status: metav1.ConditionFalse,
Reason: "ParseFailed",
Message: fmt.Sprintf("Failed to parse configuration: %v", err),
})
// Update the status even on parse failure
if statusErr := r.Status().Update(ctx, scalityUIComponent); statusErr != nil {
logger.Error(statusErr, "Failed to update ScalityUIComponent status after parse failure")
}
return ctrl.Result{Requeue: true}, nil
}
// Update status with configuration details
scalityUIComponent.Status.Kind = config.Metadata.Kind
scalityUIComponent.Status.PublicPath = config.Spec.PublicPath
scalityUIComponent.Status.Version = config.Spec.Version
// Set ConfigurationRetrieved=True condition
meta.SetStatusCondition(&scalityUIComponent.Status.Conditions, metav1.Condition{
Type: "ConfigurationRetrieved",
Status: metav1.ConditionTrue,
Reason: "FetchSucceeded",
Message: "Successfully fetched and applied UI component configuration",
})
// Update the status
if err := r.Status().Update(ctx, scalityUIComponent); err != nil {
logger.Error(err, "Failed to update ScalityUIComponent status")
return ctrl.Result{}, err
}
logger.Info("Successfully updated ScalityUIComponent status",
"kind", config.Metadata.Kind,
"publicPath", config.Spec.PublicPath,
"version", config.Spec.Version)
return ctrl.Result{}, nil
}
func (r *ScalityUIComponentReconciler) fetchMicroAppConfig(ctx context.Context, namespace, serviceName string) (string, error) {
return r.ConfigFetcher.FetchConfig(ctx, namespace, serviceName, DefaultServicePort)
}
// SetupWithManager sets up the controller with the Manager.
func (r *ScalityUIComponentReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&uiv1alpha1.ScalityUIComponent{}).
Owns(&appsv1.Deployment{}).
Owns(&corev1.Service{}).
Complete(r)
}