Skip to content

Commit

Permalink
fix: K8s trigger patch operation (#643)
Browse files Browse the repository at this point in the history
  • Loading branch information
VaibhavPage authored May 7, 2020
1 parent 1db7e26 commit 27b34b6
Showing 1 changed file with 20 additions and 13 deletions.
33 changes: 20 additions & 13 deletions sensors/triggers/standard-k8s/starndard-k8s.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
"github.com/imdario/mergo"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
apierr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
Expand Down Expand Up @@ -116,36 +115,44 @@ func (k8sTrigger *StandardK8sTrigger) Execute(resource interface{}) (interface{}
}
obj.SetNamespace(namespace)

// If object not found, create the object. No need to have a separate `Create` switch case.
oldObj, err := k8sTrigger.namespableDynamicClient.Namespace(namespace).Get(obj.GetName(), metav1.GetOptions{})
if err != nil {
if !apierr.IsNotFound(err) {
return nil, err
}
return k8sTrigger.namespableDynamicClient.Namespace(namespace).Create(obj, metav1.CreateOptions{})
}

op := v1alpha1.Update
if trigger.Template.K8s.Operation != "" && trigger.Template.K8s.Operation != v1alpha1.Create {
op := v1alpha1.Create
if trigger.Template.K8s.Operation != "" {
op = trigger.Template.K8s.Operation
}

switch op {
case v1alpha1.Create:
k8sTrigger.Logger.Infoln("creating the object...")
return k8sTrigger.namespableDynamicClient.Namespace(namespace).Create(obj, metav1.CreateOptions{})

case v1alpha1.Update:
k8sTrigger.Logger.Infoln("updating the object...")

oldObj, err := k8sTrigger.namespableDynamicClient.Namespace(namespace).Get(obj.GetName(), metav1.GetOptions{})
if err != nil {
return nil, err
}

if err := mergo.Merge(oldObj, obj, mergo.WithOverride); err != nil {
return nil, errors.Errorf("failed to update the object. err: %+v\n", err)
}

return k8sTrigger.namespableDynamicClient.Namespace(namespace).Update(oldObj, metav1.UpdateOptions{})

case v1alpha1.Patch:
// defaults to "application/merge-patch+json"
k8sTrigger.Logger.Infoln("patching the object...")

if k8sTrigger.Trigger.Template.K8s.PatchStrategy == "" {
k8sTrigger.Trigger.Template.K8s.PatchStrategy = k8stypes.MergePatchType
}

body, err := obj.MarshalJSON()
if err != nil {
return nil, errors.Errorf("failed to marshal object into JSON schema. err: %+v\n", err)
}

return k8sTrigger.namespableDynamicClient.Namespace(namespace).Patch(obj.GetName(), k8sTrigger.Trigger.Template.K8s.PatchStrategy, body, metav1.PatchOptions{})

default:
return nil, errors.Errorf("unknown operation type %s", string(op))
}
Expand Down

0 comments on commit 27b34b6

Please sign in to comment.