|
| 1 | +// Copyright (c) 2024 Aiven, Helsinki, Finland. https://aiven.io/ |
| 2 | + |
| 3 | +package controllers |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "strconv" |
| 10 | + |
| 11 | + avngen "github.com/aiven/go-client-codegen" |
| 12 | + "github.com/aiven/go-client-codegen/handler/clickhouse" |
| 13 | + "github.com/aiven/go-client-codegen/handler/service" |
| 14 | + "github.com/go-logr/logr" |
| 15 | + "k8s.io/apimachinery/pkg/api/meta" |
| 16 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 17 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 18 | + |
| 19 | + "github.com/aiven/aiven-operator/api/v1alpha1" |
| 20 | +) |
| 21 | + |
| 22 | +//+kubebuilder:rbac:groups=aiven.io,resources=clickhouseusers,verbs=get;list;watch;create;update;patch;delete |
| 23 | +//+kubebuilder:rbac:groups=aiven.io,resources=clickhouseusers/status,verbs=get;update;patch |
| 24 | +//+kubebuilder:rbac:groups=aiven.io,resources=clickhouseusers/finalizers,verbs=get;create;update |
| 25 | + |
| 26 | +// ClickhouseUserControllerV2 reconciles a ClickhouseUser object |
| 27 | +type ClickhouseUserControllerV2 struct { |
| 28 | + client.Client |
| 29 | + avnGen avngen.Client |
| 30 | +} |
| 31 | + |
| 32 | +func newClickhouseUserReconcilerV2(c Controller) reconcilerType { |
| 33 | + return &Reconciler[*v1alpha1.ClickhouseUser]{ |
| 34 | + Controller: c, |
| 35 | + newAivenGeneratedClient: NewAivenGeneratedClient, |
| 36 | + newObj: func() *v1alpha1.ClickhouseUser { |
| 37 | + return &v1alpha1.ClickhouseUser{} |
| 38 | + }, |
| 39 | + newController: func(avnGen avngen.Client) AivenController[*v1alpha1.ClickhouseUser] { |
| 40 | + return &ClickhouseUserControllerV2{ |
| 41 | + Client: c.Client, |
| 42 | + avnGen: avnGen, |
| 43 | + } |
| 44 | + }, |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +func (r *ClickhouseUserControllerV2) Observe(ctx context.Context, user *v1alpha1.ClickhouseUser) (Observation, error) { |
| 49 | + obs := Observation{ |
| 50 | + ResourceExists: false, |
| 51 | + ResourceUpToDate: false, |
| 52 | + SecretDetails: nil, |
| 53 | + } |
| 54 | + |
| 55 | + check, err := checkServiceIsOperational(ctx, r.avnGen, user.Spec.Project, user.Spec.ServiceName) |
| 56 | + if err != nil { |
| 57 | + if errors.Is(err, errServicePoweredOff) { |
| 58 | + return obs, fmt.Errorf("%w: %w", errPreconditionNotMet, err) |
| 59 | + } |
| 60 | + return obs, err |
| 61 | + } |
| 62 | + if !check { |
| 63 | + return obs, errPreconditionNotMet |
| 64 | + } |
| 65 | + |
| 66 | + list, err := r.avnGen.ServiceClickHouseUserList(ctx, user.Spec.Project, user.Spec.ServiceName) |
| 67 | + if err != nil { |
| 68 | + return obs, err |
| 69 | + } |
| 70 | + for _, u := range list { |
| 71 | + if u.Name == user.GetUsername() { |
| 72 | + obs.ResourceExists = true |
| 73 | + user.Status.UUID = u.Uuid |
| 74 | + break |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + if obs.ResourceExists { |
| 79 | + // TODO: extend the logic with more checks if needed |
| 80 | + obs.ResourceUpToDate = IsReadyToUse(user) |
| 81 | + } |
| 82 | + |
| 83 | + return obs, nil |
| 84 | +} |
| 85 | + |
| 86 | +// Create implements AivenClient for ClickhouseUser. |
| 87 | +func (r *ClickhouseUserControllerV2) Create(ctx context.Context, user *v1alpha1.ClickhouseUser) (CreateResult, error) { |
| 88 | + logr.FromContextOrDiscard(ctx).Info("generation wasn't processed, creation or updating instance on aiven side") |
| 89 | + a := user.GetAnnotations() |
| 90 | + delete(a, processedGenerationAnnotation) |
| 91 | + delete(a, instanceIsRunningAnnotation) |
| 92 | + |
| 93 | + // Validates the secret password if it exists |
| 94 | + _, err := GetPasswordFromSecret(ctx, r.Client, user) |
| 95 | + if err != nil { |
| 96 | + return CreateResult{}, fmt.Errorf("failed to get password from secret: %w", err) |
| 97 | + } |
| 98 | + |
| 99 | + if user.Status.UUID == "" { |
| 100 | + req := clickhouse.ServiceClickHouseUserCreateIn{ |
| 101 | + Name: user.GetUsername(), |
| 102 | + } |
| 103 | + rsp, err := r.avnGen.ServiceClickHouseUserCreate(ctx, user.Spec.Project, user.Spec.ServiceName, &req) |
| 104 | + if err != nil { |
| 105 | + logr.FromContextOrDiscard(ctx).Info( |
| 106 | + "unable to create or update %s: %s/%s, retrying: %s", |
| 107 | + user.GetObjectKind().GroupVersionKind().Kind, |
| 108 | + user.GetNamespace(), |
| 109 | + user.GetName(), |
| 110 | + err, |
| 111 | + ) |
| 112 | + return CreateResult{}, err |
| 113 | + } |
| 114 | + user.Status.UUID = rsp.Uuid |
| 115 | + } |
| 116 | + |
| 117 | + logr.FromContextOrDiscard(ctx).Info( |
| 118 | + "processed instance, updating annotations", |
| 119 | + "generation", user.GetGeneration(), |
| 120 | + "annotations", user.GetAnnotations(), |
| 121 | + ) |
| 122 | + |
| 123 | + // We don't really know if an instance is created or updated because: |
| 124 | + // 1. The go client's retry mechanism may create an instance successfully but receive a 5xx error, |
| 125 | + // causing the next attempt to get a conflict error |
| 126 | + // 2. Remote state may be temporarily inconsistent, so GET checks can return false positives/negatives |
| 127 | + // 3. Some handlers implement their own retry logic and keep trying to create instances until success |
| 128 | + // Therefore, we can't rely on "exists" checks to determine the operation type |
| 129 | + const reason = "CreatedOrUpdated" |
| 130 | + meta.SetStatusCondition( |
| 131 | + user.Conditions(), |
| 132 | + getInitializedCondition( |
| 133 | + reason, |
| 134 | + "Successfully created or updated the instance in Aiven", |
| 135 | + ), |
| 136 | + ) |
| 137 | + meta.SetStatusCondition( |
| 138 | + user.Conditions(), |
| 139 | + getRunningCondition( |
| 140 | + metav1.ConditionUnknown, |
| 141 | + reason, |
| 142 | + "Successfully created or updated the instance in Aiven, status remains unknown", |
| 143 | + ), |
| 144 | + ) |
| 145 | + metav1.SetMetaDataAnnotation( |
| 146 | + user.GetObjectMeta(), |
| 147 | + processedGenerationAnnotation, |
| 148 | + strconv.FormatInt(user.GetGeneration(), formatIntBaseDecimal), |
| 149 | + ) |
| 150 | + |
| 151 | + return CreateResult{}, nil |
| 152 | +} |
| 153 | + |
| 154 | +// Update implements AivenClient for ClickhouseUser. |
| 155 | +func (r *ClickhouseUserControllerV2) Update(ctx context.Context, user *v1alpha1.ClickhouseUser) (UpdateResult, error) { |
| 156 | + logr.FromContextOrDiscard(ctx).Info("checking if instance is ready") |
| 157 | + |
| 158 | + // Needs to be before o.NoSecret() check because `get` mutates the object's metadata annotations. |
| 159 | + // It set the instanceIsRunningAnnotation annotation when the instance is running on Aiven's side. |
| 160 | + s, err := r.avnGen.ServiceGet(ctx, user.Spec.Project, user.Spec.ServiceName, service.ServiceGetIncludeSecrets(true)) |
| 161 | + if err != nil { |
| 162 | + return UpdateResult{}, err |
| 163 | + } |
| 164 | + |
| 165 | + // User can set password in the secret |
| 166 | + secretPassword, err := GetPasswordFromSecret(ctx, r.Client, user) |
| 167 | + if err != nil { |
| 168 | + return UpdateResult{}, fmt.Errorf("failed to get password from secret: %w", err) |
| 169 | + } |
| 170 | + |
| 171 | + // By design, this handler can't create secret in createOrUpdate method, while the password is returned on create only. |
| 172 | + // The only way to have a secret here is to reset it manually |
| 173 | + req := clickhouse.ServiceClickHousePasswordResetIn{} |
| 174 | + if secretPassword != "" { |
| 175 | + req.Password = &secretPassword |
| 176 | + } |
| 177 | + |
| 178 | + password, err := r.avnGen.ServiceClickHousePasswordReset(ctx, user.Spec.Project, user.Spec.ServiceName, user.Status.UUID, &req) |
| 179 | + if err != nil { |
| 180 | + return UpdateResult{}, err |
| 181 | + } |
| 182 | + |
| 183 | + prefix := getSecretPrefix(user) |
| 184 | + stringData := map[string]string{ |
| 185 | + prefix + "HOST": s.ServiceUriParams["host"], |
| 186 | + prefix + "PORT": s.ServiceUriParams["port"], |
| 187 | + prefix + "PASSWORD": password, |
| 188 | + prefix + "USERNAME": user.GetUsername(), |
| 189 | + // todo: remove in future releases |
| 190 | + "HOST": s.ServiceUriParams["host"], |
| 191 | + "PORT": s.ServiceUriParams["port"], |
| 192 | + "PASSWORD": password, |
| 193 | + "USERNAME": user.GetUsername(), |
| 194 | + } |
| 195 | + |
| 196 | + meta.SetStatusCondition(&user.Status.Conditions, |
| 197 | + getRunningCondition(metav1.ConditionTrue, "CheckRunning", |
| 198 | + "Instance is running on Aiven side")) |
| 199 | + metav1.SetMetaDataAnnotation(&user.ObjectMeta, instanceIsRunningAnnotation, "true") |
| 200 | + |
| 201 | + result := UpdateResult{ |
| 202 | + SecretDetails: make(map[string][]byte, len(stringData)), |
| 203 | + } |
| 204 | + for k, v := range stringData { |
| 205 | + result.SecretDetails[k] = []byte(v) |
| 206 | + } |
| 207 | + |
| 208 | + return result, nil |
| 209 | +} |
| 210 | + |
| 211 | +// Delete implements AivenClient for ClickhouseUser. |
| 212 | +// It mirrors the current delete behaviour used in reconcile2. |
| 213 | +func (r *ClickhouseUserControllerV2) Delete(ctx context.Context, user *v1alpha1.ClickhouseUser) error { |
| 214 | + // Not processed yet |
| 215 | + if user.Status.UUID == "" { |
| 216 | + return nil |
| 217 | + } |
| 218 | + |
| 219 | + // skip deletion for built-in users that cannot be deleted |
| 220 | + if isBuiltInUser(user.Name) { |
| 221 | + // built-in users like 'default' cannot be deleted, this is expected behavior |
| 222 | + // we consider this a successful deletion since we can't and shouldn't delete built-in users |
| 223 | + return nil |
| 224 | + } |
| 225 | + |
| 226 | + err := r.avnGen.ServiceClickHouseUserDelete(ctx, user.Spec.Project, user.Spec.ServiceName, user.Status.UUID) |
| 227 | + if !isNotFound(err) { |
| 228 | + return err |
| 229 | + } |
| 230 | + |
| 231 | + return nil |
| 232 | +} |
0 commit comments