-
Notifications
You must be signed in to change notification settings - Fork 157
/
provider.go
362 lines (296 loc) · 10.6 KB
/
provider.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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/*
Copyright 2021 The Kubermatic Kubernetes Platform contributors.
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 nutanix
import (
"context"
"errors"
"fmt"
"net/http"
nutanixv3 "github.com/embik/nutanix-client-go/pkg/client/v3"
"go.uber.org/zap"
kubermaticv1 "k8c.io/kubermatic/v2/pkg/apis/kubermatic/v1"
kuberneteshelper "k8c.io/kubermatic/v2/pkg/kubernetes"
"k8c.io/kubermatic/v2/pkg/log"
"k8c.io/kubermatic/v2/pkg/provider"
"k8s.io/utils/pointer"
)
const (
ClusterCategoryName = "KKPCluster"
ProjectCategoryName = "KKPProject"
categoryDescription = "automatically created by KKP"
categoryValuePrefix = "kubernetes-"
DefaultProject = "default"
categoryCleanupFinalizer = "kubermatic.k8c.io/cleanup-nutanix-categories"
)
type Nutanix struct {
dc *kubermaticv1.DatacenterSpecNutanix
log *zap.SugaredLogger
secretKeySelector provider.SecretKeySelectorValueFunc
}
var _ provider.ReconcilingCloudProvider = &Nutanix{}
func NewCloudProvider(dc *kubermaticv1.Datacenter, secretKeyGetter provider.SecretKeySelectorValueFunc) (*Nutanix, error) {
if dc.Spec.Nutanix == nil {
return nil, errors.New("datacenter is not a Nutanix datacenter")
}
return &Nutanix{
dc: dc.Spec.Nutanix,
log: log.Logger,
secretKeySelector: secretKeyGetter,
}, nil
}
func (n *Nutanix) InitializeCloudProvider(ctx context.Context, cluster *kubermaticv1.Cluster, update provider.ClusterUpdater) (*kubermaticv1.Cluster, error) {
return n.reconcileCluster(ctx, cluster, update, false)
}
func (n *Nutanix) ReconcileCluster(ctx context.Context, cluster *kubermaticv1.Cluster, update provider.ClusterUpdater) (*kubermaticv1.Cluster, error) {
return n.reconcileCluster(ctx, cluster, update, true)
}
func (n *Nutanix) CleanUpCloudProvider(ctx context.Context, cluster *kubermaticv1.Cluster, update provider.ClusterUpdater) (*kubermaticv1.Cluster, error) {
if !kuberneteshelper.HasFinalizer(cluster, categoryCleanupFinalizer) {
return cluster, nil
}
client, err := GetClientSet(n.dc, cluster.Spec.Cloud.Nutanix, n.secretKeySelector)
if err != nil {
return nil, err
}
logger := n.log.With("cluster", cluster.Name)
logger.Info("removing category values")
if err = deleteCategoryValues(ctx, client, cluster); err != nil {
return nil, err
}
return update(ctx, cluster.Name, func(cluster *kubermaticv1.Cluster) {
kuberneteshelper.RemoveFinalizer(cluster, categoryCleanupFinalizer)
})
}
func (n *Nutanix) DefaultCloudSpec(_ context.Context, spec *kubermaticv1.CloudSpec) error {
// default csi
if spec.Nutanix.CSI != nil {
if spec.Nutanix.CSI.Port == nil {
spec.Nutanix.CSI.Port = pointer.Int32Ptr(9440)
}
}
return nil
}
func (n *Nutanix) ValidateCloudSpec(ctx context.Context, spec kubermaticv1.CloudSpec) error {
if spec.Nutanix == nil {
return errors.New("not a Nutanix spec")
}
client, err := GetClientSet(n.dc, spec.Nutanix, n.secretKeySelector)
if err != nil {
return err
}
if spec.Nutanix.ProjectName != "" {
// check for project existence
_, err = GetProjectByName(ctx, client, spec.Nutanix.ProjectName)
if err != nil {
return err
}
}
// validate csi is set - required for new clusters
if spec.Nutanix.CSI == nil {
return errors.New("CSI not configured")
}
return nil
}
func (n *Nutanix) ValidateCloudSpecUpdate(_ context.Context, oldSpec kubermaticv1.CloudSpec, newSpec kubermaticv1.CloudSpec) error {
if oldSpec.Nutanix == nil || newSpec.Nutanix == nil {
return errors.New("'nutanix' spec is empty")
}
if oldSpec.Nutanix.ClusterName != newSpec.Nutanix.ClusterName {
return fmt.Errorf("updating Nutanix cluster name is not supported (was %s, updated to %s)", oldSpec.Nutanix.ClusterName, newSpec.Nutanix.ClusterName)
}
if oldSpec.Nutanix.ProjectName != newSpec.Nutanix.ProjectName {
return fmt.Errorf("updating Nutanix project name is not supported (was %s, updated to %s)", oldSpec.Nutanix.ProjectName, newSpec.Nutanix.ProjectName)
}
return nil
}
func (n *Nutanix) reconcileCluster(ctx context.Context, cluster *kubermaticv1.Cluster, update provider.ClusterUpdater, force bool) (*kubermaticv1.Cluster, error) {
logger := n.log.With("cluster", cluster.Name)
client, err := GetClientSet(n.dc, cluster.Spec.Cloud.Nutanix, n.secretKeySelector)
if err != nil {
return nil, err
}
logger.Info("reconciling category and value")
if err := reconcileCategoryAndValue(ctx, client, cluster); err != nil {
return nil, fmt.Errorf("failed to reconcile category and cluster value: %w", err)
}
cluster, err = update(ctx, cluster.Name, func(cluster *kubermaticv1.Cluster) {
kuberneteshelper.AddFinalizer(cluster, categoryCleanupFinalizer)
})
if err != nil {
return nil, err
}
return cluster, nil
}
func deleteCategoryValues(ctx context.Context, client *ClientSet, cluster *kubermaticv1.Cluster) error {
projectID, ok := cluster.Labels[kubermaticv1.ProjectIDLabelKey]
if ok {
_, err := client.Prism.V3.GetCategoryValue(ctx, ProjectCategoryName, projectID)
if err != nil {
nutanixError, parseErr := ParseNutanixError(err)
// failed to parse nutanix error? likely auth issues
if parseErr != nil {
return parseErr
}
if nutanixError.Code != http.StatusNotFound {
return err
}
} else {
// we need to make sure that no resources are attached
// to the project category before trying to delete it.
query, err := client.Prism.V3.GetCategoryQuery(ctx, &nutanixv3.CategoryQueryInput{
UsageType: pointer.String("APPLIED_TO"),
GroupMemberCount: pointer.Int64(0),
CategoryFilter: &nutanixv3.CategoryFilter{
Type: pointer.String("CATEGORIES_MATCH_ANY"),
KindList: []*string{},
Params: map[string][]string{
ProjectCategoryName: {projectID},
},
},
})
if err != nil {
return err
}
// no results mean it is safe to clean up this category value.
if len(query.Results) == 0 {
if err = client.Prism.V3.DeleteCategoryValue(ctx, ProjectCategoryName, projectID); err != nil {
return err
}
} else {
// we will loop over the results and see if any of them match our category for the cluster.
// if we hit a matching resource, an error is returned, as there is some leftover resource.
// other entities not linked to our cluster are fine and can be ignored.
for _, result := range query.Results {
if result != nil {
for _, entity := range result.EntityAnyReferenceList {
if entity != nil {
if val, ok := entity.Categories[ClusterCategoryName]; ok && val == CategoryValue(cluster.Name) {
return fmt.Errorf("entities associated with category '%s=%s' still exist", ClusterCategoryName, CategoryValue(cluster.Name))
}
}
}
}
}
}
}
}
_, err := client.Prism.V3.GetCategoryValue(ctx, ClusterCategoryName, CategoryValue(cluster.Name))
if err != nil {
nutanixError, parseErr := ParseNutanixError(err)
// failed to parse nutanix error? likely auth issues
if parseErr != nil {
return parseErr
}
if nutanixError.Code != http.StatusNotFound {
return err
}
} else if err = client.Prism.V3.DeleteCategoryValue(ctx, ClusterCategoryName, CategoryValue(cluster.Name)); err != nil {
return err
}
return nil
}
func reconcileCategoryAndValue(ctx context.Context, client *ClientSet, cluster *kubermaticv1.Cluster) error {
// check if category (key) is present, create it if not
_, err := client.Prism.V3.GetCategoryKey(ctx, ClusterCategoryName)
if err != nil {
nutanixError, err := ParseNutanixError(err)
// failed to parse nutanix error? likely auth issues
if err != nil {
return err
}
if nutanixError.Code == http.StatusNotFound {
_, err := client.Prism.V3.CreateOrUpdateCategoryKey(ctx, &nutanixv3.CategoryKey{
Name: pointer.String(ClusterCategoryName),
Description: pointer.String(categoryDescription),
})
if err != nil {
return err
}
} else {
return err
}
}
// check if category value is present, create it if not
_, err = client.Prism.V3.GetCategoryValue(ctx, ClusterCategoryName, CategoryValue(cluster.Name))
if err != nil {
nutanixError, err := ParseNutanixError(err)
// failed to parse nutanix error? likely auth issues
if err != nil {
return err
}
if nutanixError.Code == http.StatusNotFound {
_, err := client.Prism.V3.CreateOrUpdateCategoryValue(ctx, ClusterCategoryName, &nutanixv3.CategoryValue{
Value: pointer.String(CategoryValue(cluster.Name)),
Description: pointer.String(fmt.Sprintf("value for Kubernetes cluster %s", cluster.Name)),
})
if err != nil {
return err
}
} else {
return err
}
}
projectID, ok := cluster.Labels[kubermaticv1.ProjectIDLabelKey]
if ok {
_, err = client.Prism.V3.GetCategoryKey(ctx, ProjectCategoryName)
if err != nil {
nutanixError, err := ParseNutanixError(err)
// failed to parse nutanix error? likely auth issues
if err != nil {
return err
}
if nutanixError.Code == http.StatusNotFound {
_, err := client.Prism.V3.CreateOrUpdateCategoryKey(ctx, &nutanixv3.CategoryKey{
Name: pointer.String(ProjectCategoryName),
Description: pointer.String(categoryDescription),
})
if err != nil {
return err
}
} else {
return err
}
}
_, err = client.Prism.V3.GetCategoryValue(ctx, ProjectCategoryName, projectID)
if err != nil {
nutanixError, err := ParseNutanixError(err)
// failed to parse nutanix error? likely auth issues
if err != nil {
return err
}
if nutanixError.Code == http.StatusNotFound {
_, err := client.Prism.V3.CreateOrUpdateCategoryValue(ctx, ProjectCategoryName, &nutanixv3.CategoryValue{
Value: pointer.String(projectID),
Description: pointer.String(fmt.Sprintf("value for KKP project %s", projectID)),
})
if err != nil {
return err
}
} else {
return err
}
}
}
return nil
}
func CategoryValue(clusterName string) string {
return categoryValuePrefix + clusterName
}
func ValidateCredentials(ctx context.Context, endpoint string, port *int32, allowInsecure *bool, proxyURL, username, password string) error {
cli, err := GetClientSetWithCreds(endpoint, port, allowInsecure, proxyURL, username, password)
if err != nil {
return err
}
_, err = cli.Prism.V3.ListAllImage(ctx, "")
return err
}