generated from crossplane/provider-template
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathuser.go
240 lines (199 loc) · 8.07 KB
/
user.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
/*
Copyright 2022 The Crossplane Authors.
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 user
import (
"context"
"fmt"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/crossplane/crossplane-runtime/pkg/connection"
"github.com/crossplane/crossplane-runtime/pkg/controller"
"github.com/crossplane/crossplane-runtime/pkg/event"
"github.com/crossplane/crossplane-runtime/pkg/ratelimiter"
"github.com/crossplane/crossplane-runtime/pkg/reconciler/managed"
"github.com/crossplane/crossplane-runtime/pkg/resource"
"github.com/statnett/provider-cloudian/apis/user/v1alpha1"
apisv1alpha1 "github.com/statnett/provider-cloudian/apis/v1alpha1"
"github.com/statnett/provider-cloudian/internal/features"
"github.com/statnett/provider-cloudian/internal/sdk/cloudian"
)
const (
errNotUser = "managed resource is not a User custom resource"
errTrackPCUsage = "cannot track ProviderConfig usage"
errGetPC = "cannot get ProviderConfig"
errGetCreds = "cannot get credentials"
errNewClient = "cannot create new Service"
errCreateUser = "cannot create User"
errDeleteUser = "cannot delete User"
errListUsers = "cannot list Users"
errGetUser = "cannot get User"
)
// A NoOpService does nothing.
type NoOpService struct{}
var (
newCloudianService = func(providerConfig *apisv1alpha1.ProviderConfig, authHeader string) (*cloudian.Client, error) {
// FIXME: Don't require InsecureSkipVerify
return cloudian.NewClient(
providerConfig.Spec.Endpoint,
authHeader,
cloudian.WithInsecureTLSVerify(true),
), nil
}
)
// Setup adds a controller that reconciles User managed resources.
func Setup(mgr ctrl.Manager, o controller.Options) error {
name := managed.ControllerName(v1alpha1.UserGroupKind)
cps := []managed.ConnectionPublisher{managed.NewAPISecretPublisher(mgr.GetClient(), mgr.GetScheme())}
if o.Features.Enabled(features.EnableAlphaExternalSecretStores) {
cps = append(cps, connection.NewDetailsManager(mgr.GetClient(), apisv1alpha1.StoreConfigGroupVersionKind))
}
r := managed.NewReconciler(mgr,
resource.ManagedKind(v1alpha1.UserGroupVersionKind),
managed.WithExternalConnecter(&connector{
kube: mgr.GetClient(),
usage: resource.NewProviderConfigUsageTracker(mgr.GetClient(), &apisv1alpha1.ProviderConfigUsage{}),
newServiceFn: newCloudianService}),
managed.WithLogger(o.Logger.WithValues("controller", name)),
managed.WithPollInterval(o.PollInterval),
managed.WithRecorder(event.NewAPIRecorder(mgr.GetEventRecorderFor(name))),
managed.WithConnectionPublishers(cps...))
return ctrl.NewControllerManagedBy(mgr).
Named(name).
WithOptions(o.ForControllerRuntime()).
WithEventFilter(resource.DesiredStateChanged()).
For(&v1alpha1.User{}).
Complete(ratelimiter.NewReconciler(name, r, o.GlobalRateLimiter))
}
// A connector is expected to produce an ExternalClient when its Connect method
// is called.
type connector struct {
kube client.Client
usage resource.Tracker
newServiceFn func(providerConfig *apisv1alpha1.ProviderConfig, authHeader string) (*cloudian.Client, error)
}
// Connect typically produces an ExternalClient by:
// 1. Tracking that the managed resource is using a ProviderConfig.
// 2. Getting the managed resource's ProviderConfig.
// 3. Getting the credentials specified by the ProviderConfig.
// 4. Using the credentials to form a client.
func (c *connector) Connect(ctx context.Context, mg resource.Managed) (managed.ExternalClient, error) {
cr, ok := mg.(*v1alpha1.User)
if !ok {
return nil, errors.New(errNotUser)
}
if err := c.usage.Track(ctx, mg); err != nil {
return nil, errors.Wrap(err, errTrackPCUsage)
}
pc := &apisv1alpha1.ProviderConfig{}
if err := c.kube.Get(ctx, types.NamespacedName{Name: cr.GetProviderConfigReference().Name}, pc); err != nil {
return nil, errors.Wrap(err, errGetPC)
}
cd := pc.Spec.AuthHeader
authHeader, err := resource.CommonCredentialExtractor(ctx, cd.Source, c.kube, cd.CommonCredentialSelectors)
if err != nil {
return nil, errors.Wrap(err, errGetCreds)
}
svc, err := c.newServiceFn(pc, string(authHeader))
if err != nil {
return nil, errors.Wrap(err, errNewClient)
}
return &external{cloudianService: svc}, nil
}
// An ExternalClient observes, then either creates, updates, or deletes an
// external resource to ensure it reflects the managed resource's desired state.
type external struct {
// A 'client' used to connect to the external resource API. In practice this
// would be something like an AWS SDK client.
cloudianService *cloudian.Client
}
func (c *external) Observe(ctx context.Context, mg resource.Managed) (managed.ExternalObservation, error) {
cr, ok := mg.(*v1alpha1.User)
if !ok {
return managed.ExternalObservation{}, errors.New(errNotUser)
}
users, err := c.cloudianService.ListUsers(ctx, cr.Spec.ForProvider.GroupID, nil)
if err != nil {
return managed.ExternalObservation{}, errors.Wrap(err, errListUsers)
}
upToDate := isUpToDate(cr.Spec.ForProvider, users)
return managed.ExternalObservation{
// Return false when the external resource does not exist. This lets
// the managed resource reconciler know that it needs to call Create to
// (re)create the resource, or that it has successfully been deleted.
ResourceExists: upToDate,
// Return false when the external resource exists, but it not up to date
// with the desired managed resource state. This lets the managed
// resource reconciler know that it needs to call Update.
ResourceUpToDate: upToDate,
// Return any details that may be required to connect to the external
// resource. These will be stored as the connection secret.
ConnectionDetails: managed.ConnectionDetails{},
}, nil
}
func isUpToDate(spec v1alpha1.UserParameters, users []cloudian.User) bool {
for _, user := range users {
if user.UserID == spec.UserID {
return true
}
}
return false
}
func (c *external) Create(ctx context.Context, mg resource.Managed) (managed.ExternalCreation, error) {
cr, ok := mg.(*v1alpha1.User)
if !ok {
return managed.ExternalCreation{}, errors.New(errNotUser)
}
user := cloudian.User{
GroupID: cr.Spec.ForProvider.GroupID,
UserID: cr.Spec.ForProvider.UserID,
}
if err := c.cloudianService.CreateUser(ctx, user); err != nil {
return managed.ExternalCreation{}, errors.Wrap(err, errCreateUser)
}
return managed.ExternalCreation{
// Optionally return any details that may be required to connect to the
// external resource. These will be stored as the connection secret.
ConnectionDetails: managed.ConnectionDetails{},
}, nil
}
func (c *external) Update(ctx context.Context, mg resource.Managed) (managed.ExternalUpdate, error) {
cr, ok := mg.(*v1alpha1.User)
if !ok {
return managed.ExternalUpdate{}, errors.New(errNotUser)
}
fmt.Printf("Pretending to Update (no managed fields to update): %+v", cr)
return managed.ExternalUpdate{
// Optionally return any details that may be required to connect to the
// external resource. These will be stored as the connection secret.
ConnectionDetails: managed.ConnectionDetails{},
}, nil
}
func (c *external) Delete(ctx context.Context, mg resource.Managed) (managed.ExternalDelete, error) {
cr, ok := mg.(*v1alpha1.User)
if !ok {
return managed.ExternalDelete{}, errors.New(errNotUser)
}
user := cloudian.User{
GroupID: cr.Spec.ForProvider.GroupID,
UserID: cr.Spec.ForProvider.UserID,
}
if err := c.cloudianService.DeleteUser(ctx, user); err != nil {
return managed.ExternalDelete{}, errors.Wrap(err, errDeleteUser)
}
return managed.ExternalDelete{}, nil
}
func (c *external) Disconnect(ctx context.Context) error {
return nil
}