github.com/argoproj/argo-events@v1.9.1/sensors/policy/resource-labels.go (about) 1 /* 2 Copyright 2018 BlackRock, Inc. 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 policy 18 19 import ( 20 "context" 21 22 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 23 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" 24 "k8s.io/apimachinery/pkg/util/wait" 25 "k8s.io/client-go/dynamic" 26 27 "github.com/argoproj/argo-events/common" 28 "github.com/argoproj/argo-events/pkg/apis/sensor/v1alpha1" 29 ) 30 31 // ResourceLabels implements trigger policy based on the resource labels 32 type ResourceLabels struct { 33 Trigger *v1alpha1.Trigger 34 Client dynamic.NamespaceableResourceInterface 35 Obj *unstructured.Unstructured 36 } 37 38 func (rl *ResourceLabels) ApplyPolicy(ctx context.Context) error { 39 if rl.Trigger.Policy.K8s == nil || rl.Trigger.Policy.K8s.Labels == nil { 40 return nil 41 } 42 43 // check if success labels match with labels on object 44 completed := false 45 46 b := rl.Trigger.Policy.K8s.Backoff 47 if b == nil { 48 b = &common.DefaultBackoff 49 } 50 backoff, err := common.Convert2WaitBackoff(b) 51 if err != nil { 52 return err 53 } 54 55 err = wait.ExponentialBackoff(*backoff, func() (bool, error) { 56 obj, err := rl.Client.Namespace(rl.Obj.GetNamespace()).Get(ctx, rl.Obj.GetName(), metav1.GetOptions{}) 57 if err != nil { 58 return false, err 59 } 60 61 labels := obj.GetLabels() 62 if labels == nil { 63 return false, nil 64 } 65 66 completed = true 67 68 for key, value := range rl.Trigger.Policy.K8s.Labels { 69 if v, ok := labels[key]; ok { 70 if value != v { 71 completed = false 72 break 73 } 74 continue 75 } 76 completed = false 77 } 78 79 if completed { 80 return true, nil 81 } 82 return false, nil 83 }) 84 85 return err 86 } 87 88 func NewResourceLabels(trigger *v1alpha1.Trigger, client dynamic.NamespaceableResourceInterface, obj *unstructured.Unstructured) *ResourceLabels { 89 return &ResourceLabels{ 90 Trigger: trigger, 91 Client: client, 92 Obj: obj, 93 } 94 }