-
Notifications
You must be signed in to change notification settings - Fork 74
/
custom_roles.go
285 lines (216 loc) · 8.33 KB
/
custom_roles.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
package atlasproject
import (
"errors"
"fmt"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"go.mongodb.org/atlas/mongodbatlas"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/api"
akov2 "github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/api/v1"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/api/v1/status"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/controller/workflow"
)
func ensureCustomRoles(workflowCtx *workflow.Context, project *akov2.AtlasProject) workflow.Result {
currentCustomRoles, err := fetchCustomRoles(workflowCtx, project.ID())
if err != nil {
return workflow.Terminate(workflow.ProjectCustomRolesReady, err.Error())
}
ops := calculateChanges(currentCustomRoles, project.Spec.CustomRoles)
deleteStatus := deleteCustomRoles(workflowCtx, project.ID(), ops.Delete)
updateStatus := updateCustomRoles(workflowCtx, project.ID(), ops.Update)
createStatus := createCustomRoles(workflowCtx, project.ID(), ops.Create)
result := syncCustomRolesStatus(workflowCtx, project.Spec.CustomRoles, createStatus, updateStatus, deleteStatus)
if !result.IsOk() {
workflowCtx.SetConditionFromResult(api.ProjectCustomRolesReadyType, result)
return result
}
workflowCtx.SetConditionTrue(api.ProjectCustomRolesReadyType)
if len(project.Spec.CustomRoles) == 0 {
workflowCtx.UnsetCondition(api.ProjectCustomRolesReadyType)
}
return result
}
func fetchCustomRoles(ctx *workflow.Context, projectID string) ([]akov2.CustomRole, error) {
data, _, err := ctx.Client.CustomDBRoles.List(ctx.Context, projectID, nil)
if err != nil {
return nil, fmt.Errorf("failed to retrieve custom roles from atlas: %w", err)
}
if data == nil {
return []akov2.CustomRole{}, nil
}
ctx.Log.Debugw("Got Custom Roles", "NumItems", len(*data))
return mapToOperator(data), nil
}
func mapToOperator(atlasCustomRoles *[]mongodbatlas.CustomDBRole) []akov2.CustomRole {
customRoles := make([]akov2.CustomRole, 0, len(*atlasCustomRoles))
for _, atlasCustomRole := range *atlasCustomRoles {
inheritedRoles := make([]akov2.Role, 0, len(atlasCustomRole.InheritedRoles))
for _, atlasInheritedRole := range atlasCustomRole.InheritedRoles {
inheritedRoles = append(inheritedRoles, akov2.Role{
Name: atlasInheritedRole.Role,
Database: atlasInheritedRole.Db,
})
}
actions := make([]akov2.Action, 0, len(atlasCustomRole.Actions))
for _, atlasAction := range atlasCustomRole.Actions {
resources := make([]akov2.Resource, 0, len(atlasAction.Resources))
for _, atlasResource := range atlasAction.Resources {
resources = append(resources, akov2.Resource{
Cluster: atlasResource.Cluster,
Database: atlasResource.DB,
Collection: atlasResource.Collection,
})
}
actions = append(actions, akov2.Action{
Name: atlasAction.Action,
Resources: resources,
})
}
customRoles = append(customRoles, akov2.CustomRole{
Actions: actions,
InheritedRoles: inheritedRoles,
Name: atlasCustomRole.RoleName,
})
}
return customRoles
}
func deleteCustomRoles(ctx *workflow.Context, projectID string, toDelete map[string]akov2.CustomRole) map[string]status.CustomRole {
ctx.Log.Debugw("Custom Roles to be deleted", "NumItems", len(toDelete))
statuses := map[string]status.CustomRole{}
for _, customRole := range toDelete {
_, err := ctx.Client.CustomDBRoles.Delete(ctx.Context, projectID, customRole.Name)
opStatus, errorMsg := evaluateOperation(err)
statuses[customRole.Name] = status.CustomRole{
Name: customRole.Name,
Status: opStatus,
Error: errorMsg,
}
if errorMsg != "" {
ctx.Log.Warnf("Failed to delete custom role \"%s\": %s", customRole.Name, errorMsg)
} else {
ctx.Log.Debugw("Removed Custom Role in current AtlasProject", "custom role:", customRole.Name)
}
}
return statuses
}
func updateCustomRoles(ctx *workflow.Context, projectID string, toUpdate map[string]akov2.CustomRole) map[string]status.CustomRole {
ctx.Log.Debugw("Custom Roles to be updated", "NumItems", len(toUpdate))
statuses := map[string]status.CustomRole{}
for _, customRole := range toUpdate {
data := customRole.ToAtlas()
// Patch fails when sending the role name in the body, needs clarification with cloud team
data.RoleName = ""
_, _, err := ctx.Client.CustomDBRoles.Update(ctx.Context, projectID, customRole.Name, data)
opStatus, errorMsg := evaluateOperation(err)
statuses[customRole.Name] = status.CustomRole{
Name: customRole.Name,
Status: opStatus,
Error: errorMsg,
}
if errorMsg != "" {
ctx.Log.Warnf("Failed to update custom role \"%s\": %s", customRole.Name, errorMsg)
} else {
ctx.Log.Debugw("Updated Custom Role in current AtlasProject", "custom role:", customRole.Name)
}
}
return statuses
}
func createCustomRoles(ctx *workflow.Context, projectID string, toCreate map[string]akov2.CustomRole) map[string]status.CustomRole {
ctx.Log.Debugw("Custom Roles to be added", "NumItems", len(toCreate))
statuses := map[string]status.CustomRole{}
for _, customRole := range toCreate {
_, _, err := ctx.Client.CustomDBRoles.Create(ctx.Context, projectID, customRole.ToAtlas())
opStatus, errorMsg := evaluateOperation(err)
statuses[customRole.Name] = status.CustomRole{
Name: customRole.Name,
Status: opStatus,
Error: errorMsg,
}
if errorMsg != "" {
ctx.Log.Warnf("Failed to create custom role \"%s\": %s", customRole.Name, errorMsg)
} else {
ctx.Log.Debugw("Created Custom Role in current AtlasProject", "custom role:", customRole.Name)
}
}
return statuses
}
func mapCustomRolesByName(customRoles []akov2.CustomRole) map[string]akov2.CustomRole {
customRolesByName := map[string]akov2.CustomRole{}
for _, customRole := range customRoles {
customRolesByName[customRole.Name] = customRole
}
return customRolesByName
}
type CustomRolesOperations struct {
Create map[string]akov2.CustomRole
Update map[string]akov2.CustomRole
Delete map[string]akov2.CustomRole
}
func calculateChanges(currentCustomRoles []akov2.CustomRole, desiredCustomRoles []akov2.CustomRole) CustomRolesOperations {
currentCustomRolesByName := mapCustomRolesByName(currentCustomRoles)
desiredCustomRolesByName := mapCustomRolesByName(desiredCustomRoles)
ops := CustomRolesOperations{
Create: map[string]akov2.CustomRole{},
Update: map[string]akov2.CustomRole{},
Delete: map[string]akov2.CustomRole{},
}
for _, currentCustomRole := range currentCustomRoles {
if _, ok := desiredCustomRolesByName[currentCustomRole.Name]; !ok {
ops.Delete[currentCustomRole.Name] = currentCustomRole
}
}
for _, desiredCustomRole := range desiredCustomRoles {
customRole, ok := currentCustomRolesByName[desiredCustomRole.Name]
if !ok {
ops.Create[desiredCustomRole.Name] = desiredCustomRole
continue
}
if d := cmp.Diff(desiredCustomRole, customRole, cmpopts.EquateEmpty()); d != "" {
ops.Update[desiredCustomRole.Name] = desiredCustomRole
}
}
return ops
}
func evaluateOperation(err error) (status.CustomRoleStatus, string) {
if err != nil {
return status.CustomRoleStatusFailed, err.Error()
}
return status.CustomRoleStatusOK, ""
}
func syncCustomRolesStatus(ctx *workflow.Context, desiredCustomRoles []akov2.CustomRole, created, updated, deleted map[string]status.CustomRole) workflow.Result {
statuses := make([]status.CustomRole, 0, len(desiredCustomRoles))
var err error
for _, customRole := range desiredCustomRoles {
stat, ok := deleted[customRole.Name]
if ok {
if stat.Status == status.CustomRoleStatusFailed {
statuses = append(statuses, stat)
err = errors.Join(err, fmt.Errorf(stat.Error))
}
continue
}
if stat, ok = updated[customRole.Name]; ok {
statuses = append(statuses, stat)
if stat.Status == status.CustomRoleStatusFailed {
err = errors.Join(err, fmt.Errorf(stat.Error))
}
continue
}
if stat, ok = created[customRole.Name]; ok {
statuses = append(statuses, stat)
if stat.Status == status.CustomRoleStatusFailed {
err = errors.Join(err, fmt.Errorf(stat.Error))
}
continue
}
statuses = append(statuses, status.CustomRole{
Name: customRole.Name,
Status: status.CustomRoleStatusOK,
})
}
ctx.EnsureStatusOption(status.AtlasProjectSetCustomRolesOption(&statuses))
if err != nil {
return workflow.Terminate(workflow.ProjectCustomRolesReady, fmt.Sprintf("failed to apply changes to custom roles: %s", err.Error()))
}
return workflow.OK()
}