-
Notifications
You must be signed in to change notification settings - Fork 20
/
common.go
298 lines (248 loc) · 8.06 KB
/
common.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
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
package controllers
import (
"context"
"errors"
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
"github.com/aiven/aiven-go-client/v2"
avngen "github.com/aiven/go-client-codegen"
"github.com/aiven/go-client-codegen/handler/service"
"github.com/liip/sheriff"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"github.com/aiven/aiven-operator/api/v1alpha1"
)
const (
conditionTypeRunning = "Running"
conditionTypeInitialized = "Initialized"
ConditionTypeError = "Error"
secretProtectionFinalizer = "finalizers.aiven.io/needed-to-delete-services"
instanceDeletionFinalizer = "finalizers.aiven.io/delete-remote-resource"
processedGenerationAnnotation = "controllers.aiven.io/generation-was-processed"
instanceIsRunningAnnotation = "controllers.aiven.io/instance-is-running"
deletionPolicyAnnotation = "controllers.aiven.io/deletion-policy"
deletionPolicyOrphan = "Orphan"
deletionPolicyDelete = "Delete"
)
type errCondition string
const (
errConditionDelete errCondition = "Delete"
errConditionPreconditions errCondition = "Preconditions"
errConditionCreateOrUpdate errCondition = "CreateOrUpdate"
)
var errTerminationProtectionOn = errors.New("termination protection is on")
func checkServiceIsOperational(ctx context.Context, avnGen avngen.Client, project, serviceName string) (bool, error) {
s, err := avnGen.ServiceGet(ctx, project, serviceName)
if err != nil {
// if service is not found, it is not running
if isNotFound(err) {
// this will swallow an error if the project doesn't exist and object is not project
return false, nil
}
return false, err
}
return serviceIsOperational(s.State), nil
}
// serviceIsOperational returns "true" when a service is in operational state, i.e. "running"
func serviceIsOperational[T service.ServiceStateType | string](state T) bool {
s := service.ServiceStateType(state)
return s == service.ServiceStateTypeRebalancing || serviceIsRunning(s)
}
// serviceIsRunning returns "true" when a service is RUNNING state on Aive side
func serviceIsRunning[T service.ServiceStateType | string](state T) bool {
return service.ServiceStateType(state) == service.ServiceStateTypeRunning
}
func getInitializedCondition(reason, message string) metav1.Condition {
return metav1.Condition{
Type: conditionTypeInitialized,
Status: metav1.ConditionTrue,
Reason: reason,
Message: message,
}
}
func getRunningCondition(status metav1.ConditionStatus, reason, message string) metav1.Condition {
return metav1.Condition{
Type: conditionTypeRunning,
Status: status,
Reason: reason,
Message: message,
}
}
func getErrorCondition(reason errCondition, err error) metav1.Condition {
return metav1.Condition{
Type: ConditionTypeError,
Status: metav1.ConditionUnknown,
Reason: string(reason),
Message: err.Error(),
}
}
func isMarkedForDeletion(o client.Object) bool {
return !o.GetDeletionTimestamp().IsZero()
}
func addFinalizer(ctx context.Context, client client.Client, o client.Object, f string) error {
controllerutil.AddFinalizer(o, f)
return client.Update(ctx, o)
}
func removeFinalizer(ctx context.Context, client client.Client, o client.Object, f string) error {
controllerutil.RemoveFinalizer(o, f)
return client.Update(ctx, o)
}
func isAlreadyProcessed(o client.Object) bool {
return o.GetAnnotations()[processedGenerationAnnotation] == strconv.FormatInt(o.GetGeneration(), formatIntBaseDecimal)
}
// IsAlreadyRunning returns true if object is ready to use
func IsAlreadyRunning(o client.Object) bool {
_, found := o.GetAnnotations()[instanceIsRunningAnnotation]
return found
}
func optionalStringPointer(u string) *string {
if len(u) == 0 {
return nil
}
return &u
}
func isAivenServerError(err error) bool {
var status int
var old aiven.Error
var gen avngen.Error
switch {
case errors.As(err, &old):
status = old.Status
case errors.As(err, &gen):
status = gen.Status
}
return status >= http.StatusInternalServerError
}
// userAgent is a helper function to create a User-Agent string used for the Go client.
func userAgent(kubeVersion, operatorVersion string) string {
// Remove the leading "v" from the version strings, if present.
// This is to unify the version format across the Terraform Provider and the Kubernetes Operator.
//
// Cf. terraform-provider-aiven/A.B.C/X.Y.Z vs. k8s-operator/vA.B.C/vX.Y.Z.
kubeVersion = strings.TrimPrefix(kubeVersion, "v")
operatorVersion = strings.TrimPrefix(operatorVersion, "v")
return fmt.Sprintf("k8s-operator/%s/%s", kubeVersion, operatorVersion)
}
// NewAivenClient returns Aiven client (aiven/aiven-go-client/v2)
func NewAivenClient(token, kubeVersion, operatorVersion string) (*aiven.Client, error) {
return aiven.NewTokenClient(token, userAgent(kubeVersion, operatorVersion))
}
// NewAivenGeneratedClient returns Aiven generated client client (aiven/go-client-codegen)
func NewAivenGeneratedClient(token, kubeVersion, operatorVersion string) (avngen.Client, error) {
return avngen.NewClient(avngen.TokenOpt(token), avngen.UserAgentOpt(userAgent(kubeVersion, operatorVersion)))
}
func fromAnyPointer[T any](v *T) T {
if v != nil {
return *v
}
var t T
return t
}
type objWithSecret interface {
GetName() string
GetNamespace() string
GetObjectKind() schema.ObjectKind
GetConnInfoSecretTarget() v1alpha1.ConnInfoSecretTarget
}
func newSecret(o objWithSecret, stringData map[string]string, addPrefix bool) *corev1.Secret {
target := o.GetConnInfoSecretTarget()
meta := metav1.ObjectMeta{
Name: o.GetName(),
Namespace: o.GetNamespace(),
Annotations: target.Annotations,
Labels: target.Labels,
}
if target.Name != "" {
meta.Name = target.Name
}
// fixme: set this as default behaviour
// when legacy secrets removed
if addPrefix {
prefix := getSecretPrefix(o)
for k, v := range stringData {
delete(stringData, k)
stringData[prefix+k] = v
}
}
return &corev1.Secret{
ObjectMeta: meta,
StringData: stringData,
}
}
// getSecretPrefix returns user's prefix or kind name
func getSecretPrefix(o objWithSecret) string {
target := o.GetConnInfoSecretTarget()
if target.Prefix != "" {
return target.Prefix
}
kind := o.GetObjectKind()
return strings.ToUpper(kind.GroupVersionKind().Kind) + "_"
}
// userConfigurationToAPI converts user config into a map
func userConfigurationToAPI(c any, groups ...string) (map[string]any, error) {
if c == nil || (reflect.ValueOf(c).Kind() == reflect.Ptr && reflect.ValueOf(c).IsNil()) {
return map[string]any{}, nil
}
o := &sheriff.Options{
Groups: groups,
}
i, err := sheriff.Marshal(o, c)
if err != nil {
return nil, err
}
m, ok := i.(map[string]interface{})
if !ok {
// It is an empty pointer
// sheriff just returned the very same object
return map[string]any{}, nil
}
return m, nil
}
func CreateUserConfiguration(userConfig any) (map[string]any, error) {
return userConfigurationToAPI(userConfig, "create", "update")
}
func UpdateUserConfiguration(userConfig any) (map[string]any, error) {
return userConfigurationToAPI(userConfig, "update")
}
// isNotFound works both for old and new client errors
func isNotFound(err error) bool {
return isAivenError(err, http.StatusNotFound)
}
// isAlreadyExists works both for old and new client errors
func isAlreadyExists(err error) bool {
return aiven.IsAlreadyExists(err) || avngen.IsAlreadyExists(err)
}
func NewNotFound(msg string) error {
return aiven.Error{Status: http.StatusNotFound, Message: msg}
}
func isDeleted(err error) (bool, error) {
if isNotFound(err) {
return true, nil
}
return err == nil, err
}
// isAivenError returns true if the error comes from the old or new client and has given http code
func isAivenError(err error, code int) bool {
var oldErr aiven.Error
if errors.As(err, &oldErr) {
return oldErr.Status == code
}
var newErr avngen.Error
if errors.As(err, &newErr) {
return newErr.Status == code
}
return false
}
func toPtr[T comparable](v T) *T {
var empty T
if empty == v {
return nil
}
return &v
}