github.com/kubewharf/katalyst-core@v0.5.3/pkg/client/control/noc.go (about) 1 /* 2 Copyright 2022 The Katalyst 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 control 18 19 import ( 20 "context" 21 "encoding/json" 22 "fmt" 23 24 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 25 "k8s.io/apimachinery/pkg/types" 26 "k8s.io/apimachinery/pkg/util/jsonmergepatch" 27 28 "github.com/kubewharf/katalyst-api/pkg/apis/overcommit/v1alpha1" 29 clientset "github.com/kubewharf/katalyst-api/pkg/client/clientset/versioned" 30 "github.com/kubewharf/katalyst-core/pkg/util/general" 31 ) 32 33 type NocUpdater interface { 34 PatchNocStatus(ctx context.Context, oldNoc, newNoc *v1alpha1.NodeOvercommitConfig) (*v1alpha1.NodeOvercommitConfig, error) 35 } 36 37 type DummyNocUpdater struct{} 38 39 func (d *DummyNocUpdater) PatchNocStatus(_ context.Context, _, newNoc *v1alpha1.NodeOvercommitConfig) (*v1alpha1.NodeOvercommitConfig, error) { 40 return newNoc, nil 41 } 42 43 func NewRealNocUpdater(client clientset.Interface) NocUpdater { 44 return &RealNocUpdater{ 45 client: client, 46 } 47 } 48 49 type RealNocUpdater struct { 50 client clientset.Interface 51 } 52 53 func (r *RealNocUpdater) PatchNocStatus(ctx context.Context, oldNoc, newNoc *v1alpha1.NodeOvercommitConfig) (*v1alpha1.NodeOvercommitConfig, error) { 54 if oldNoc == nil || newNoc == nil { 55 return nil, fmt.Errorf("can't patch a nil noc") 56 } 57 58 oldData, err := json.Marshal(v1alpha1.NodeOvercommitConfig{Status: oldNoc.Status}) 59 if err != nil { 60 return nil, err 61 } 62 newData, err := json.Marshal(v1alpha1.NodeOvercommitConfig{Status: newNoc.Status}) 63 if err != nil { 64 return nil, err 65 } 66 67 patchBytes, err := jsonmergepatch.CreateThreeWayJSONMergePatch(oldData, newData, oldData) 68 if err != nil { 69 return nil, fmt.Errorf("failed to create merge patch for nodeOvercommitConfig %s: %v", 70 oldNoc.Name, err) 71 } 72 if general.JsonPathEmpty(patchBytes) { 73 return newNoc, nil 74 } 75 76 return r.client.OvercommitV1alpha1().NodeOvercommitConfigs().Patch(ctx, oldNoc.Name, types.MergePatchType, patchBytes, metav1.PatchOptions{}, "status") 77 }