-
Notifications
You must be signed in to change notification settings - Fork 259
/
Copy pathcontact_controller.go
286 lines (247 loc) · 9.63 KB
/
contact_controller.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
// Copyright 2024 Google LLC
//
// 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.
// +tool:controller
// proto.service: google.cloud.essentialcontacts.v1.EssentialContactsService
// proto.message: google.cloud.essentialcontacts.v1.Contact
// crd.type: EssentialContactsContact
// crd.version: v1alpha1
package essentialcontacts
import (
"context"
"fmt"
"reflect"
gcp "cloud.google.com/go/essentialcontacts/apiv1"
pb "cloud.google.com/go/essentialcontacts/apiv1/essentialcontactspb"
refv1beta1 "github.com/GoogleCloudPlatform/k8s-config-connector/apis/refs/v1beta1"
"google.golang.org/protobuf/types/known/fieldmaskpb"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/client"
krm "github.com/GoogleCloudPlatform/k8s-config-connector/apis/essentialcontacts/v1alpha1"
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/config"
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/controller/direct"
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/controller/direct/directbase"
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/controller/direct/registry"
)
func init() {
registry.RegisterModel(krm.EssentialContactsContactGVK, NewContactModel)
}
func NewContactModel(ctx context.Context, config *config.ControllerConfig) (directbase.Model, error) {
return &contactModel{config: *config}, nil
}
var _ directbase.Model = &contactModel{}
type contactModel struct {
config config.ControllerConfig
}
func (m *contactModel) AdapterForObject(ctx context.Context, reader client.Reader, u *unstructured.Unstructured) (directbase.Adapter, error) {
obj := &krm.EssentialContactsContact{}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object, &obj); err != nil {
return nil, fmt.Errorf("error converting to %T: %w", obj, err)
}
id, err := krm.NewContactIdentity(ctx, reader, obj)
if err != nil {
return nil, err
}
// Get GCP client
gcpClient, err := newGCPClient(ctx, &m.config)
if err != nil {
return nil, err
}
client, err := gcpClient.newEssentialContactsClient(ctx)
if err != nil {
return nil, err
}
return &contactAdapter{
gcpClient: client,
id: id,
desired: obj,
reader: reader,
}, nil
}
func (m *contactModel) AdapterForURL(ctx context.Context, url string) (directbase.Adapter, error) {
// TODO: Support URLs
return nil, nil
}
type contactAdapter struct {
gcpClient *gcp.Client
id *krm.ContactIdentity
desired *krm.EssentialContactsContact
actual *pb.Contact
reader client.Reader
}
var _ directbase.Adapter = &contactAdapter{}
// Find retrieves the GCP resource.
// Return true means the object is found. This triggers Adapter `Update` call.
// Return false means the object is not found. This triggers Adapter `Create` call.
// Return a non-nil error requeues the requests.
func (a *contactAdapter) Find(ctx context.Context) (bool, error) {
log := klog.FromContext(ctx)
log.V(2).Info("getting essential contact", "name", a.id)
// This resource has a server-generated ID. This means user should not know
// the ID before the resource is created, and 'metadata.name' won't be used
// as the default resource ID. So empty value for 'spec.resourceID' should
// also be valid:
// 1. When 'spec.resourceID' is not set or set to an empty value, the
// intention is to create the resource.
// 2. When 'spec.resourceID' is set, the intention is to acquire an existing
// resource.
// 2.1. When 'spec.resourceID' is set but the corresponding GCP resource
// is not found, then it is a real error.
if a.id.ID() == "" {
log.V(2).Info("no resource ID in get indicates the create intention", "name", a.id)
return false, nil
}
req := &pb.GetContactRequest{Name: a.id.String()}
actual, err := a.gcpClient.GetContact(ctx, req)
if err != nil {
if direct.IsNotFound(err) {
return false, nil
}
return false, fmt.Errorf("getting essential contact %q: %w", a.id, err)
}
a.actual = actual
return true, nil
}
// Create creates the resource in GCP based on `spec` and update the Config Connector object `status` based on the GCP response.
func (a *contactAdapter) Create(ctx context.Context, createOp *directbase.CreateOperation) error {
log := klog.FromContext(ctx)
log.V(2).Info("creating essential contact", "name", a.id)
mapCtx := &direct.MapContext{}
desired := a.desired.DeepCopy()
resource := EssentialContactsContactSpec_ToProto(mapCtx, &desired.Spec)
if mapCtx.Err() != nil {
return mapCtx.Err()
}
req := &pb.CreateContactRequest{
Parent: a.id.Parent().String(),
Contact: resource,
}
created, err := a.gcpClient.CreateContact(ctx, req)
if err != nil {
return fmt.Errorf("creating essential contact %s: %w", a.id, err)
}
log.V(2).Info("successfully created essential contact", "name", a.id)
status := &krm.EssentialContactsContactStatus{}
status.ObservedState = EssentialContactsContactObservedState_FromProto(mapCtx, created)
if mapCtx.Err() != nil {
return mapCtx.Err()
}
status.ExternalRef = direct.LazyPtr(created.Name)
return createOp.UpdateStatus(ctx, status, nil)
}
// Update updates the resource in GCP based on `spec` and update the Config Connector object `status` based on the GCP response.
func (a *contactAdapter) Update(ctx context.Context, updateOp *directbase.UpdateOperation) error {
log := klog.FromContext(ctx)
log.V(2).Info("updating essential contact", "name", a.id)
mapCtx := &direct.MapContext{}
desired := a.desired.DeepCopy()
resource := EssentialContactsContactSpec_ToProto(mapCtx, &desired.Spec)
if mapCtx.Err() != nil {
return mapCtx.Err()
}
resource.Name = a.id.String() // Set name for update request
paths := []string{}
if !reflect.DeepEqual(resource.NotificationCategorySubscriptions, a.actual.NotificationCategorySubscriptions) {
paths = append(paths, "notification_category_subscriptions")
}
if !reflect.DeepEqual(resource.LanguageTag, a.actual.LanguageTag) {
paths = append(paths, "language_tag")
}
var updated *pb.Contact
if len(paths) == 0 {
log.V(2).Info("no field needs update", "name", a.id)
updated = a.actual
} else {
req := &pb.UpdateContactRequest{
Contact: resource,
UpdateMask: &fieldmaskpb.FieldMask{Paths: paths},
}
var err error
updated, err = a.gcpClient.UpdateContact(ctx, req)
if err != nil {
return fmt.Errorf("updating essential contact %s: %w", a.id, err)
}
log.V(2).Info("successfully updated essential contact", "name", a.id)
}
status := &krm.EssentialContactsContactStatus{}
status.ObservedState = EssentialContactsContactObservedState_FromProto(mapCtx, updated)
if mapCtx.Err() != nil {
return mapCtx.Err()
}
status.ExternalRef = direct.LazyPtr(updated.Name)
// Handle potential status-only updates if KCC resource was acquired.
if len(paths) == 0 && a.desired.Status.ExternalRef == nil {
status.ObservedState.ValidationState = a.desired.Status.ObservedState.ValidationState // email is immutable but needed for acquisition
}
return updateOp.UpdateStatus(ctx, status, nil)
}
// Export maps the GCP object to a Config Connector resource `spec`.
func (a *contactAdapter) Export(ctx context.Context) (*unstructured.Unstructured, error) {
if a.actual == nil {
return nil, fmt.Errorf("Find() not called")
}
u := &unstructured.Unstructured{}
obj := &krm.EssentialContactsContact{}
mapCtx := &direct.MapContext{}
obj.Spec = direct.ValueOf(EssentialContactsContactSpec_FromProto(mapCtx, a.actual))
if mapCtx.Err() != nil {
return nil, mapCtx.Err()
}
// Set parent ref based on the actual name format
parentIdentity, resourceID, err := krm.ParseContactExternal(a.id.String())
if err != nil {
return nil, fmt.Errorf("parsing parent from actual name %q: %w", a.id, err)
}
if parentIdentity.ProjectID != "" {
obj.Spec.ProjectRef = &refv1beta1.ProjectRef{
External: parentIdentity.String(),
}
} else if parentIdentity.FolderID != "" {
obj.Spec.FolderRef = &refv1beta1.FolderRef{
External: parentIdentity.String(),
}
} else if parentIdentity.OrganizationID != "" {
obj.Spec.OrganizationRef = &refv1beta1.OrganizationRef{
External: parentIdentity.String(),
}
} else {
return nil, fmt.Errorf("unknown parent type in name %q", a.actual.Name)
}
uObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
if err != nil {
return nil, err
}
u.SetName(resourceID)
u.SetGroupVersionKind(krm.EssentialContactsContactGVK)
u.Object = uObj
return u, nil
}
// Delete the resource from GCP service when the corresponding Config Connector resource is deleted.
func (a *contactAdapter) Delete(ctx context.Context, deleteOp *directbase.DeleteOperation) (bool, error) {
log := klog.FromContext(ctx)
log.V(2).Info("deleting essential contact", "name", a.id)
req := &pb.DeleteContactRequest{Name: a.id.String()}
err := a.gcpClient.DeleteContact(ctx, req)
if err != nil {
if direct.IsNotFound(err) {
// Return success if not found (assume it was already deleted).
log.V(2).Info("skipping delete for non-existent essential contact, assuming it was already deleted", "name", a.id)
return true, nil
}
return false, fmt.Errorf("deleting essential contact %s: %w", a.id, err)
}
log.V(2).Info("successfully deleted essential contact", "name", a.id)
return true, nil
}