-
Notifications
You must be signed in to change notification settings - Fork 204
/
logmetric_controller.go
391 lines (327 loc) · 12.4 KB
/
logmetric_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
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
// 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.
package logging
import (
"context"
"fmt"
"reflect"
api "google.golang.org/api/logging/v2"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
krm "github.com/GoogleCloudPlatform/k8s-config-connector/apis/resources/logging/v1beta1"
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/apis/k8s/v1alpha1"
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/controller"
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/controller/direct/directbase"
)
const ctrlName = "logmetric-controller"
// AddLogMetricController creates a new controller and adds it to the Manager.
// The Manager will set fields on the Controller and start it when the Manager is started.
func AddLogMetricController(mgr manager.Manager, config *controller.Config, opts directbase.Deps) error {
gvk := krm.LoggingLogMetricGVK
// todo(acpana): plumb context throughout direct
ctx := context.TODO()
gcpClient, err := newGCPClient(ctx, config)
if err != nil {
return err
}
m := &logMetricModel{gcpClient: gcpClient}
return directbase.Add(mgr, gvk, m, opts)
}
func GetModel(ctx context.Context, config *controller.Config) (directbase.Model, error) {
gcpClient, err := newGCPClient(ctx, config)
if err != nil {
return nil, err
}
return &logMetricModel{gcpClient: gcpClient}, nil
}
type logMetricModel struct {
*gcpClient
}
// model implements the Model interface.
var _ directbase.Model = &logMetricModel{}
type logMetricAdapter struct {
resourceID string
projectID string
desired *krm.LoggingLogMetric
actual *api.LogMetric
logMetricClient *api.ProjectsMetricsService
}
var _ directbase.Adapter = &logMetricAdapter{}
// AdapterForObject implements the Model interface.
func (m *logMetricModel) AdapterForObject(ctx context.Context, reader client.Reader, u *unstructured.Unstructured) (directbase.Adapter, error) {
projectMetricsService, err := m.newProjectMetricsService(ctx)
if err != nil {
return nil, err
}
obj := &krm.LoggingLogMetric{}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object, &obj); err != nil {
return nil, fmt.Errorf("error converting to %T: %w", obj, err)
}
resourceID := ValueOf(obj.Spec.ResourceID)
if resourceID == "" {
resourceID = obj.GetName()
}
if resourceID == "" {
return nil, fmt.Errorf("cannot resolve resource ID")
}
projectRef, err := ResolveProject(ctx, reader, obj, &obj.Spec.ProjectRef)
if err != nil {
return nil, err
}
projectID := projectRef.ProjectID
if projectID == "" {
return nil, fmt.Errorf("cannot resolve project")
}
if err := LogBucketRef_ConvertToExternal(ctx, reader, obj, &obj.Spec.LoggingLogBucketRef); err != nil {
return nil, err
}
return &logMetricAdapter{
resourceID: resourceID,
projectID: projectID,
desired: obj,
logMetricClient: projectMetricsService,
}, nil
}
func (a *logMetricAdapter) Find(ctx context.Context) (bool, error) {
if a.resourceID == "" {
return false, nil
}
logMetric, err := a.logMetricClient.Get(a.fullyQualifiedName()).Context(ctx).Do()
if err != nil {
if IsNotFound(err) {
return false, nil
}
return false, fmt.Errorf("getting logMetric %q: %w", a.fullyQualifiedName(), err)
}
a.actual = logMetric
return true, nil
}
// Delete implements the Adapter interface.
func (a *logMetricAdapter) Delete(ctx context.Context) (bool, error) {
// Already deleted
if a.resourceID == "" {
return false, nil
}
_, err := a.logMetricClient.Delete(a.fullyQualifiedName()).Context(ctx).Do()
if err != nil {
if IsNotFound(err) {
return false, nil
}
return false, fmt.Errorf("deleting log metric %s: %w", a.fullyQualifiedName(), err)
}
return true, nil
}
func (a *logMetricAdapter) Create(ctx context.Context, u *unstructured.Unstructured) error {
log := klog.FromContext(ctx).WithName(ctrlName)
log.V(2).Info("creating object", "u", u)
projectID := a.projectID
if projectID == "" {
return fmt.Errorf("project is empty")
}
if a.resourceID == "" {
return fmt.Errorf("resourceID is empty")
}
filter := a.desired.Spec.Filter
if filter == "" {
return fmt.Errorf("filter is empty")
}
if a.desired.Spec.LoggingLogBucketRef != nil {
bucket, err := LogBucketRef_Parse(ctx, a.desired.Spec.LoggingLogBucketRef.External)
if err != nil {
return err
}
// validate that the bucket is in the same project
if bucket.ProjectID() != a.projectID {
return fmt.Errorf("LoggingLogBucket %q is not in the same project %q", bucket.FQN(), a.projectID)
}
}
logMetric := convertKCCtoAPI(&a.desired.Spec)
logMetric.Name = a.resourceID
createRequest := a.logMetricClient.Create("projects/"+projectID, logMetric)
log.V(2).Info("creating logMetric", "request", &createRequest, "name", logMetric.Name)
created, err := createRequest.Context(ctx).Do()
if err != nil {
return fmt.Errorf("logMetric %s creation failed: %w", logMetric.Name, err)
}
log.V(2).Info("created logMetric", "logMetric", created)
resourceID := created.Name
if err := unstructured.SetNestedField(u.Object, resourceID, "spec", "resourceID"); err != nil {
return fmt.Errorf("setting spec.resourceID: %w", err)
}
status := &krm.LoggingLogMetricStatus{}
if err := logMetricStatusToKRM(created, status); err != nil {
return err
}
return setStatus(u, status)
}
func logMetricStatusToKRM(in *api.LogMetric, out *krm.LoggingLogMetricStatus) error {
out.CreateTime = LazyPtr(in.CreateTime)
out.UpdateTime = LazyPtr(in.UpdateTime)
out.MetricDescriptor = convertAPItoKRM_MetricDescriptorStatus(in.MetricDescriptor)
return nil
}
func (a *logMetricAdapter) Update(ctx context.Context, u *unstructured.Unstructured) error {
latest := a.actual
if a.hasChanges(ctx, u) {
update := new(api.LogMetric)
*update = *a.actual
if ValueOf(a.desired.Spec.Description) != a.actual.Description {
update.Description = ValueOf(a.desired.Spec.Description)
}
if ValueOf(a.desired.Spec.Disabled) != a.actual.Disabled {
update.Disabled = ValueOf(a.desired.Spec.Disabled)
}
if a.desired.Spec.Filter != a.actual.Filter {
// todo acpana: revisit UX, err out if filter of desired is empty
if a.desired.Spec.Filter != "" {
update.Filter = a.desired.Spec.Filter
} else {
// filter is a REQUIRED field
update.Filter = a.actual.Filter
}
}
if !compareMetricDescriptors(a.desired.Spec.MetricDescriptor, a.actual.MetricDescriptor) {
if err := validateImmutableFieldsUpdated(a.desired.Spec.MetricDescriptor, a.actual.MetricDescriptor); err != nil {
return fmt.Errorf("logMetric update failed: %w", err)
}
update.MetricDescriptor = convertKCCtoAPIForMetricDescriptor(a.desired.Spec.MetricDescriptor)
}
if !reflect.DeepEqual(a.desired.Spec.LabelExtractors, a.actual.LabelExtractors) {
update.LabelExtractors = a.desired.Spec.LabelExtractors
}
if !compareBucketOptions(a.desired.Spec.BucketOptions, a.actual.BucketOptions) {
update.BucketOptions = convertKCCtoAPIForBucketOptions(a.desired.Spec.BucketOptions)
}
if ValueOf(a.desired.Spec.ValueExtractor) != a.actual.ValueExtractor {
update.ValueExtractor = ValueOf(a.desired.Spec.ValueExtractor)
}
if a.desired.Spec.LoggingLogBucketRef != nil && a.desired.Spec.LoggingLogBucketRef.External != a.actual.BucketName {
update.BucketName = a.desired.Spec.LoggingLogBucketRef.External
}
// DANGER: this is an upsert; it will create the LogMetric if it doesn't exists
// but this behavior is consistent with the DCL backed behavior we provide for this resource.
// todo acpana: look for / switch to a better method and/or use etags etc
updated, err := a.logMetricClient.Update(a.fullyQualifiedName(), update).Context(ctx).Do()
if err != nil {
return fmt.Errorf("logMetric update failed: %w", err)
}
latest = updated
}
status := &krm.LoggingLogMetricStatus{}
if err := logMetricStatusToKRM(latest, status); err != nil {
return err
}
// actualUpdate may not contain the description for the metric descriptor.
if latest.Description != "" {
if status.MetricDescriptor != nil {
status.MetricDescriptor.Description = &latest.Description
}
}
return setStatus(u, status)
}
func (a *logMetricAdapter) hasChanges(ctx context.Context, u *unstructured.Unstructured) bool {
log := klog.FromContext(ctx)
if u.GetGeneration() != getObservedGeneration(u) {
log.V(2).Info("generation does not match", "generation", u.GetGeneration(), "observedGeneration", getObservedGeneration(u))
return true
}
gcpUpdateTime := a.actual.UpdateTime
if gcpUpdateTime == "" {
log.V(2).Info("updateTime is not set in GCP")
return true
}
obj := &krm.LoggingLogMetric{}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object, &obj); err != nil {
log.Error(err, "error converting from unstructured")
return true
}
if obj.Status.UpdateTime == nil {
log.V(2).Info("status.updateTime is not set")
return true
}
if gcpUpdateTime != ValueOf(obj.Status.UpdateTime) {
log.V(2).Info("status.updateTime does not match gcp updateTime", "status.updateTime", obj.Status.UpdateTime, "gcpUpdateTime", gcpUpdateTime)
return true
}
if obj.Status.Conditions != nil {
// if there was a previously failing update let's make sure we give
// the update a chance to heal or keep marking it as failed
ready := false
for _, condition := range obj.Status.Conditions {
if condition.Type == v1alpha1.ReadyConditionType {
if condition.Status == corev1.ConditionTrue {
ready = true
}
}
}
if !ready {
log.V(2).Info("status.conditions indicates object is not ready yet")
return true
}
}
log.V(2).Info("status.updateTime matches gcp updateTime", "status.updateTime", obj.Status.UpdateTime, "gcpUpdateTime", gcpUpdateTime)
return false
}
func (a *logMetricAdapter) Export(ctx context.Context) (*unstructured.Unstructured, error) {
if a.actual == nil {
return nil, fmt.Errorf("logMetric %q not found", a.fullyQualifiedName())
}
un, err := convertAPItoKRM_LoggingLogMetric(a.actual)
if err != nil {
return nil, fmt.Errorf("error converting logMetric to unstructured %w", err)
}
// TODO(acpana): revisit if we want to include mutable but unreadable fields in our export
if a.desired != nil {
if a.desired.Spec.MetricDescriptor != nil && a.desired.Spec.MetricDescriptor.LaunchStage != nil {
if err := unstructured.SetNestedField(un.Object,
*a.desired.Spec.MetricDescriptor.LaunchStage,
"spec", "metricDescriptor", "launchStage",
); err != nil {
return nil, fmt.Errorf("could not set metricDescriptor.launchStage mutable but unreadable field %w", err)
}
}
if a.desired.Spec.MetricDescriptor != nil && a.desired.Spec.MetricDescriptor.Metadata != nil {
if a.desired.Spec.MetricDescriptor.Metadata.IngestDelay != nil {
if err := unstructured.SetNestedField(un.Object,
*a.desired.Spec.MetricDescriptor.Metadata.IngestDelay,
"spec", "metricDescriptor", "metadata", "ingestDelay",
); err != nil {
return nil, fmt.Errorf("could not set metricDescriptor.metadata.ingestDelay mutable but unreadable field %w", err)
}
}
if a.desired.Spec.MetricDescriptor.Metadata.SamplePeriod != nil {
if err := unstructured.SetNestedField(un.Object,
*a.desired.Spec.MetricDescriptor.Metadata.SamplePeriod,
"spec", "metricDescriptor", "metadata", "samplePeriod",
); err != nil {
return nil, fmt.Errorf("could not set metricDescriptor.metadata.samplePeriod mutable but unreadable field %w", err)
}
}
}
}
return un, nil
}
func (a *logMetricAdapter) fullyQualifiedName() string {
return MakeFQN(a.projectID, a.resourceID)
}
// MakeFQN constructions a fully qualified name for a LogMetric resources
// to be used in API calls. The format expected is: "projects/[PROJECT_ID]/metrics/[METRIC_ID]".
// Func assumes values are well formed and validated.
func MakeFQN(projectID, metricID string) string {
return fmt.Sprintf("projects/%s/metrics/%s", projectID, metricID)
}