/
crds.go
253 lines (221 loc) · 7.69 KB
/
crds.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
// Copyright 2023 MongoDB Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package features
import (
"errors"
"fmt"
"strings"
"github.com/Masterminds/semver/v3"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/kubernetes/operator/crds"
apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
)
const (
LatestOperatorMajorVersion = "2.2.0"
maxDepth = 100
ResourceVersion = "mongodb.com/atlas-resource-version"
ResourceAtlasProject = "atlasprojects"
ResourceAtlasDeployment = "atlasdeployments"
ResourceAtlasDatabaseUser = "atlasdatabaseusers"
ResourceAtlasBackupSchedule = "atlasbackupschedules"
ResourceAtlasBackupPolicy = "atlasbackuppolicies"
ResourceAtlasTeam = "atlasteams"
ResourceAtlasDataFederation = "atlasdatafederations"
ResourceAtlasFederatedAuth = "atlasfederatedauths"
)
var (
ErrVersionNotSupportedFmt = "version '%s' is not supported"
ErrDownloadResourceFailedFmt = "can not download resource '%s': %v"
ErrDocumentIsEmpty = errors.New("document is empty")
ErrDocumentHasNoVersions = errors.New("document contains no versions")
ErrDocumentHasNoSchema = errors.New("document contains no Schema")
ErrDocumentHasNoSpec = errors.New("document contains no Spec")
versionsToResourcesMap = map[string][]resource{
"2.0.0": {
resource{ResourceAtlasDatabaseUser, NopPatcher()},
resource{ResourceAtlasProject, NopPatcher()},
resource{ResourceAtlasDeployment, NopPatcher()},
resource{ResourceAtlasBackupSchedule, NopPatcher()},
resource{ResourceAtlasBackupPolicy, PatcherFunc(UnknownBackupPolicyFrequencyTypesPruner)},
resource{ResourceAtlasTeam, NopPatcher()},
resource{ResourceAtlasDataFederation, NopPatcher()},
resource{ResourceAtlasFederatedAuth, NopPatcher()},
},
"2.1.0": {
resource{ResourceAtlasDatabaseUser, NopPatcher()},
resource{ResourceAtlasProject, NopPatcher()},
resource{ResourceAtlasDeployment, NopPatcher()},
resource{ResourceAtlasBackupSchedule, NopPatcher()},
resource{ResourceAtlasBackupPolicy, PatcherFunc(UnknownBackupPolicyFrequencyTypesPruner)},
resource{ResourceAtlasTeam, NopPatcher()},
resource{ResourceAtlasDataFederation, NopPatcher()},
resource{ResourceAtlasFederatedAuth, NopPatcher()},
},
"2.2.0": {
resource{ResourceAtlasDatabaseUser, NopPatcher()},
resource{ResourceAtlasProject, NopPatcher()},
resource{ResourceAtlasDeployment, NopPatcher()},
resource{ResourceAtlasBackupSchedule, NopPatcher()},
resource{ResourceAtlasBackupPolicy, NopPatcher()},
resource{ResourceAtlasTeam, NopPatcher()},
resource{ResourceAtlasDataFederation, NopPatcher()},
resource{ResourceAtlasFederatedAuth, NopPatcher()},
},
}
)
type resource struct {
name string
patcher Patcher
}
func majorVersion(version string) string {
v := semver.MustParse(version)
return semver.New(v.Major(), v.Minor(), 0, "", "").String()
}
func GetResourcesForVersion(version string) ([]string, bool) {
resources, ok := versionsToResourcesMap[majorVersion(version)]
if !ok {
return nil, false
}
result := make([]string, 0, len(resources))
for i := range resources {
result = append(result, resources[i].name)
}
return result, true
}
func SupportedVersions() []string {
result := make([]string, 0, len(versionsToResourcesMap))
for version := range versionsToResourcesMap {
result = append(result, version)
}
return result
}
func CRDCompatibleVersion(operatorVersion string) (string, error) {
operatorVersionSem, err := semver.NewVersion(operatorVersion)
if err != nil {
return "", fmt.Errorf("operator version %s is invalid", operatorVersion)
}
latestCRDVersionSem, err := semver.NewVersion(LatestOperatorMajorVersion)
if err != nil {
return "", fmt.Errorf("CRD version %s is invalid", LatestOperatorMajorVersion)
}
if operatorVersionSem.GreaterThan(latestCRDVersionSem) {
return LatestOperatorMajorVersion, nil
}
return semver.New(
operatorVersionSem.Major(),
operatorVersionSem.Minor(),
0,
"",
"").String(), nil
}
type AtlasCRDs struct {
resources map[string]*apiextensions.JSONSchemaProps
patchers map[string]Patcher
}
func (a *AtlasCRDs) Patch(obj runtime.Object) error {
// Despite marked as unsafe this pluralizer works well on our types.
plural, _ := meta.UnsafeGuessKindToResource(obj.GetObjectKind().GroupVersionKind())
crdSpec, ok := a.resources[plural.Resource]
if !ok {
return nil
}
patcher, ok := a.patchers[plural.Resource]
if !ok {
return nil
}
return patcher.Patch(crdSpec, obj)
}
func NewAtlasCRDs(crdProvider crds.AtlasOperatorCRDProvider, version string) (*AtlasCRDs, error) {
resources, versionFound := versionsToResourcesMap[majorVersion(version)]
if !versionFound {
return nil, fmt.Errorf(ErrVersionNotSupportedFmt, version)
}
result := &AtlasCRDs{
resources: map[string]*apiextensions.JSONSchemaProps{},
patchers: map[string]Patcher{},
}
for _, resource := range resources {
crd, err := crdProvider.GetAtlasOperatorResource(resource.name, version)
if err != nil {
return nil, fmt.Errorf(ErrDownloadResourceFailedFmt, resource, err)
}
// we only interested in the Spec section of a document
root, err := getCRDRoot(crd)
if err != nil {
return nil, fmt.Errorf("failed to process CRD '%s:%s'. err: %w", resource, version, err)
}
result.resources[resource.name] = root
result.patchers[resource.name] = resource.patcher
}
return result, nil
}
// FeatureExist
// resourceName: one of SupportedResources
// featurePath: dot-separated string - path in CRD spec to check.
func (a *AtlasCRDs) FeatureExist(resourceName, featurePath string) bool {
if res, ok := a.resources[resourceName]; ok {
if pathExists(featurePath, res) {
return true
}
}
return false
}
func pathExists(path string, data *apiextensions.JSONSchemaProps) bool {
parts := strings.Split(path, ".")
if len(parts) == 0 || data == nil {
return false
}
var lookup func(path []string, data *apiextensions.JSONSchemaProps, depth int) bool
lookup = func(path []string, data *apiextensions.JSONSchemaProps, depth int) bool {
if len(path) == 0 {
return true
}
if depth == 0 || data == nil {
return false
}
if props, ok := data.Properties[path[0]]; ok {
return lookup(path[1:], &props, depth-1)
} else if data.Items != nil {
if len(data.Items.JSONSchemas) == 0 {
return lookup(path, data.Items.Schema, depth-1)
}
for i := 0; i < len(data.Items.JSONSchemas); i++ {
if lookup(path, &data.Items.JSONSchemas[i], depth-1) {
return true
}
}
return false
}
return false
}
return lookup(parts, data, maxDepth)
}
func getCRDRoot(document *apiextensions.CustomResourceDefinition) (*apiextensions.JSONSchemaProps, error) {
if document == nil {
return nil, ErrDocumentIsEmpty
}
if len(document.Spec.Versions) == 0 {
return nil, ErrDocumentHasNoVersions
}
// There is only one version of Atlas CRDs atm
if document.Spec.Versions[0].Schema == nil || document.Spec.Versions[0].Schema.OpenAPIV3Schema == nil {
return nil, ErrDocumentHasNoSchema
}
specs, ok := document.Spec.Versions[0].Schema.OpenAPIV3Schema.Properties["spec"]
if !ok {
return nil, ErrDocumentHasNoSpec
}
return &specs, nil
}