-
Notifications
You must be signed in to change notification settings - Fork 671
Expand file tree
/
Copy pathusers.go
More file actions
344 lines (297 loc) · 12.6 KB
/
users.go
File metadata and controls
344 lines (297 loc) · 12.6 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
// Copyright 2023 - 2026 Crunchy Data Solutions, Inc.
//
// SPDX-License-Identifier: Apache-2.0
package standalone_pgadmin
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/crunchydata/postgres-operator/internal/logging"
"github.com/crunchydata/postgres-operator/internal/naming"
"github.com/crunchydata/postgres-operator/pkg/apis/postgres-operator.crunchydata.com/v1beta1"
)
type Executor func(
ctx context.Context, stdin io.Reader, stdout, stderr io.Writer, command ...string,
) error
// pgAdminUserForJson is used for user data that is put in the users.json file in the
// pgAdmin secret. IsAdmin and Username come from the user spec, whereas Password is
// generated when the user is created.
type pgAdminUserForJson struct {
// Whether the user has admin privileges or not.
IsAdmin bool `json:"isAdmin"`
// The user's password
Password string `json:"password"`
// The username for User in pgAdmin.
// Must be unique in the pgAdmin's users list.
Username string `json:"username"`
}
// reconcilePGAdminUsers reconciles the users listed in the pgAdmin spec, adding them
// to the pgAdmin secret, and creating/updating them in pgAdmin when appropriate.
func (r *PGAdminReconciler) reconcilePGAdminUsers(ctx context.Context, pgadmin *v1beta1.PGAdmin) error {
const container = naming.ContainerPGAdmin
var podExecutor Executor
log := logging.FromContext(ctx)
// Find the running pgAdmin container. When there is none, return early.
pod := &corev1.Pod{ObjectMeta: naming.StandalonePGAdmin(pgadmin)}
pod.Name += "-0"
err := errors.WithStack(r.Get(ctx, client.ObjectKeyFromObject(pod), pod))
if err != nil {
return client.IgnoreNotFound(err)
}
var running bool
var pgAdminImageSha string
for _, status := range pod.Status.ContainerStatuses {
if status.Name == container {
running = status.State.Running != nil
pgAdminImageSha = status.ImageID
}
}
if terminating := pod.DeletionTimestamp != nil; running && !terminating {
ctx = logging.NewContext(ctx, logging.FromContext(ctx).WithValues("pod", pod.Name))
podExecutor = func(
ctx context.Context, stdin io.Reader, stdout, stderr io.Writer, command ...string,
) error {
return r.PodExec(ctx, pod.Namespace, pod.Name, container, stdin, stdout, stderr, command...)
}
}
if podExecutor == nil {
return nil
}
// If the pgAdmin major or minor version is not in the status or the image
// SHA has changed, get the pgAdmin version and store it in the status.
var pgadminMajorVersion int
if pgadmin.Status.MajorVersion == 0 || pgadmin.Status.MinorVersion == "" ||
pgadmin.Status.ImageSHA != pgAdminImageSha {
// exec into the pgAdmin pod and retrieve the pgAdmin minor version
script := fmt.Sprintf(`
PGADMIN_DIR=%s
cd $PGADMIN_DIR && python3 -c "import config; print(config.APP_VERSION)"
`, pgAdminDir)
var stdin, stdout, stderr bytes.Buffer
if err := podExecutor(ctx, &stdin, &stdout, &stderr,
[]string{"bash", "-ceu", "--", script}...); err != nil {
return err
}
pgadminMinorVersion := strings.TrimSpace(stdout.String())
// ensure minor version is valid before storing in status
parsedMinorVersion, err := strconv.ParseFloat(pgadminMinorVersion, 64)
if err != nil {
return err
}
// Note: "When converting a floating-point number to an integer, the
// fraction is discarded (truncation towards zero)."
// - https://go.dev/ref/spec#Conversions
pgadminMajorVersion = int(parsedMinorVersion)
pgadmin.Status.MinorVersion = pgadminMinorVersion
pgadmin.Status.MajorVersion = pgadminMajorVersion
pgadmin.Status.ImageSHA = pgAdminImageSha
} else {
pgadminMajorVersion = pgadmin.Status.MajorVersion
}
// If the pgAdmin version is not v8 or higher, return early as user management is
// only supported for pgAdmin v8 and higher.
if pgadminMajorVersion < 8 {
// If pgAdmin version is less than v8 and user management is being attempted,
// log a message clarifying that it is only supported for pgAdmin v8 and higher.
if len(pgadmin.Spec.Users) > 0 {
log.Info("User management is only supported for pgAdmin v8 and higher.",
"pgadminVersion", pgadminMajorVersion)
}
return err
}
return r.writePGAdminUsers(ctx, pgadmin, podExecutor)
}
// writePGAdminUsers takes the users in the pgAdmin spec and writes (adds or updates) their data
// to both pgAdmin and the users.json file that is stored in the pgAdmin secret. If a user is
// removed from the spec, its data is removed from users.json, but it is not deleted from pgAdmin.
func (r *PGAdminReconciler) writePGAdminUsers(ctx context.Context, pgadmin *v1beta1.PGAdmin,
exec Executor) error {
log := logging.FromContext(ctx)
existingUserSecret := &corev1.Secret{ObjectMeta: naming.StandalonePGAdmin(pgadmin)}
err := errors.WithStack(
r.Get(ctx, client.ObjectKeyFromObject(existingUserSecret), existingUserSecret))
if client.IgnoreNotFound(err) != nil {
return err
}
intentUserSecret := &corev1.Secret{ObjectMeta: naming.StandalonePGAdmin(pgadmin)}
intentUserSecret.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("Secret"))
intentUserSecret.Annotations = naming.Merge(
pgadmin.Spec.Metadata.GetAnnotationsOrNil(),
)
intentUserSecret.Labels = naming.Merge(
pgadmin.Spec.Metadata.GetLabelsOrNil(),
naming.StandalonePGAdminLabels(pgadmin.Name))
// Initialize secret data map, or copy existing data if not nil
intentUserSecret.Data = make(map[string][]byte)
setupScript := fmt.Sprintf(`
PGADMIN_DIR=%s
cd $PGADMIN_DIR
`, pgAdminDir)
var existingUsersArr []pgAdminUserForJson
if existingUserSecret.Data["users.json"] != nil {
err := json.Unmarshal(existingUserSecret.Data["users.json"], &existingUsersArr)
if err != nil {
return err
}
}
existingUsersMap := make(map[string]pgAdminUserForJson)
for _, user := range existingUsersArr {
existingUsersMap[user.Username] = user
}
var olderThan9_3 bool
// Validate the pgAdmin minor version is in the format "X.Y"
parts := strings.Split(pgadmin.Status.MinorVersion, ".")
if len(parts) != 2 {
return errors.New("invalid pgAdmin minor version: " + pgadmin.Status.MinorVersion)
}
// Parse the major and minor versions
major, _ := strconv.Atoi(parts[0])
minor, _ := strconv.Atoi(parts[1])
// Check if the pgAdmin version is older than 9.3
if major < 9 || (major == 9 && minor < 3) {
olderThan9_3 = true
}
intentUsers := []pgAdminUserForJson{}
for _, user := range pgadmin.Spec.Users {
var stdin, stdout, stderr bytes.Buffer
// starting in pgAdmin 9.3, custom roles are supported and a new flag is used
// - https://github.com/pgadmin-org/pgadmin4/pull/8631
typeFlag := "--role User"
if olderThan9_3 {
typeFlag = "--nonadmin"
}
isAdmin := false
if user.Role == "Administrator" {
typeFlag = "--admin"
isAdmin = true
}
// Get password from secret
userPasswordSecret := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{
Namespace: pgadmin.Namespace,
Name: user.PasswordRef.Name,
}}
err := errors.WithStack(
r.Get(ctx, client.ObjectKeyFromObject(userPasswordSecret), userPasswordSecret))
if err != nil {
log.Error(err, "Could not get user password secret")
continue
}
// Make sure the password isn't nil or empty
password := userPasswordSecret.Data[user.PasswordRef.Key]
if password == nil {
log.Error(nil, `Could not retrieve password from secret. Make sure secret name and key are correct.`)
continue
}
if len(password) == 0 {
log.Error(nil, `Password must not be empty.`)
continue
}
// Assemble user that will be used in add/update command and in updating
// the users.json file in the secret
intentUser := pgAdminUserForJson{
Username: user.Username,
Password: string(password),
IsAdmin: isAdmin,
}
// If the user already exists in users.json and isAdmin or password has
// changed, run the update-user command. If the user already exists in
// users.json, but it hasn't changed, do nothing. If the user doesn't
// exist in users.json, run the add-user command.
if existingUser, present := existingUsersMap[user.Username]; present {
// If Password or IsAdmin have changed, attempt update-user command
if intentUser.IsAdmin != existingUser.IsAdmin || intentUser.Password != existingUser.Password {
script := setupScript + fmt.Sprintf(`python3 setup.py update-user %s --password "%s" "%s"`,
typeFlag, intentUser.Password, intentUser.Username) + "\n"
err = exec(ctx, &stdin, &stdout, &stderr,
[]string{"bash", "-ceu", "--", script}...)
// If any errors occurred during update, we want to log a message,
// add the existing user to users.json since the update was
// unsuccessful, and continue reconciling users.
if err != nil {
log.Error(err, "PodExec failed: ")
intentUsers = append(intentUsers, existingUser)
continue
} else if strings.Contains(strings.TrimSpace(stderr.String()), "UserWarning: pkg_resources is deprecated as an API") {
// Started seeing this error with pgAdmin 9.7 when using Python 3.11.
// Issue appears to resolve with Python 3.13.
log.Info(stderr.String())
} else if strings.TrimSpace(stderr.String()) != "" {
log.Error(errors.New(stderr.String()), fmt.Sprintf("pgAdmin setup.py update-user error for %s: ",
intentUser.Username))
intentUsers = append(intentUsers, existingUser)
continue
}
// If update user fails due to user not found or password length:
// https://github.com/pgadmin-org/pgadmin4/blob/REL-8_5/web/setup.py#L263
// https://github.com/pgadmin-org/pgadmin4/blob/REL-8_5/web/setup.py#L246
if strings.Contains(stdout.String(), "User not found") ||
strings.Contains(stdout.String(), "Password must be") {
log.Info("Failed to update pgAdmin user", "user", intentUser.Username, "error", stdout.String())
r.Recorder.Event(pgadmin,
corev1.EventTypeWarning, "InvalidUserWarning",
fmt.Sprintf("Failed to update pgAdmin user %s: %s",
intentUser.Username, stdout.String()))
intentUsers = append(intentUsers, existingUser)
continue
}
}
} else {
// New user, so attempt add-user command
script := setupScript + fmt.Sprintf(`python3 setup.py add-user %s -- "%s" "%s"`,
typeFlag, intentUser.Username, intentUser.Password) + "\n"
err = exec(ctx, &stdin, &stdout, &stderr,
[]string{"bash", "-ceu", "--", script}...)
// If any errors occurred when attempting to add user, we want to log a message,
// and continue reconciling users.
if err != nil {
log.Error(err, "PodExec failed: ")
continue
}
if strings.Contains(strings.TrimSpace(stderr.String()), "UserWarning: pkg_resources is deprecated as an API") {
// Started seeing this error with pgAdmin 9.7 when using Python 3.11.
// Issue appears to resolve with Python 3.13.
log.Info(stderr.String())
} else if strings.TrimSpace(stderr.String()) != "" {
log.Error(errors.New(stderr.String()), fmt.Sprintf("pgAdmin setup.py add-user error for %s: ",
intentUser.Username))
continue
}
// If add user fails due to invalid username or password length:
// https://github.com/pgadmin-org/pgadmin4/blob/REL-8_5/web/pgadmin/tools/user_management/__init__.py#L457
// https://github.com/pgadmin-org/pgadmin4/blob/REL-8_5/web/setup.py#L374
if strings.Contains(stdout.String(), "Invalid email address") ||
strings.Contains(stdout.String(), "Password must be") {
log.Info(fmt.Sprintf("Failed to create pgAdmin user %s: %s",
intentUser.Username, stdout.String()))
r.Recorder.Event(pgadmin,
corev1.EventTypeWarning, "InvalidUserWarning",
fmt.Sprintf("Failed to create pgAdmin user %s: %s",
intentUser.Username, stdout.String()))
continue
}
}
// If we've gotten here, the user was successfully added or updated or nothing was done
// to the user at all, so we want to add it to the slice of users that will be put in the
// users.json file in the secret.
intentUsers = append(intentUsers, intentUser)
}
// We've at least attempted to reconcile all users in the spec. If errors occurred when attempting
// to add a user, that user will not be in intentUsers. If errors occurred when attempting to
// update a user, the user will be in intentUsers as it existed before. We now want to marshal the
// intentUsers to json and write the users.json file to the secret.
//nolint:gosec // G117: Password is intentionally stored in a Kubernetes Secret.
intentUserSecret.Data["users.json"], _ = json.Marshal(intentUsers)
err = errors.WithStack(r.setControllerReference(pgadmin, intentUserSecret))
if err == nil {
err = errors.WithStack(r.apply(ctx, intentUserSecret))
}
return err
}