|
| 1 | +/* |
| 2 | +Copyright 2021 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package finalizer |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "fmt" |
| 22 | + |
| 23 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 24 | + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" |
| 25 | +) |
| 26 | + |
| 27 | +func NewFinalizers() Finalizers { |
| 28 | + return finalizers(map[string]Finalizer{}) |
| 29 | +} |
| 30 | + |
| 31 | +func (f finalizers) Register(key string, finalizer Finalizer) error { |
| 32 | + if _, ok := f[key]; ok { |
| 33 | + return fmt.Errorf("finalizer for key %q already registered") |
| 34 | + } |
| 35 | + f[key] = finalizer |
| 36 | + return nil |
| 37 | +} |
| 38 | + |
| 39 | +func (f finalizers) Finalize(ctx context.Context, obj client.Object) (bool, error) { |
| 40 | + needsUpdate := false |
| 41 | + for key, finalizer := range f { |
| 42 | + if obj.GetDeletionTimestamp() == nil && !controllerutil.ContainsFinalizer(obj, key) { |
| 43 | + controllerutil.AddFinalizer(obj, key) |
| 44 | + needsUpdate = true |
| 45 | + } else if obj.GetDeletionTimestamp() != nil && controllerutil.ContainsFinalizer(obj, key) { |
| 46 | + _, err := finalizer.Finalize(ctx, obj) |
| 47 | + if err != nil { |
| 48 | + return true, fmt.Errorf("finalize failed for key %q: %v", key, err) |
| 49 | + } |
| 50 | + controllerutil.RemoveFinalizer(obj, key) |
| 51 | + needsUpdate = true |
| 52 | + } |
| 53 | + } |
| 54 | + return needsUpdate, nil |
| 55 | +} |
0 commit comments