|
| 1 | +// Copyright © 2019 Banzai Cloud |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package objectmatch |
| 16 | + |
| 17 | +import ( |
| 18 | + "encoding/json" |
| 19 | + |
| 20 | + "github.com/goph/emperror" |
| 21 | + v1 "k8s.io/api/core/v1" |
| 22 | + kubernetescorev1 "k8s.io/kubernetes/pkg/apis/core/v1" |
| 23 | +) |
| 24 | + |
| 25 | +type nodeMatcher struct { |
| 26 | + objectMatcher ObjectMatcher |
| 27 | +} |
| 28 | + |
| 29 | +func NewNodeMatcher(objectMatcher ObjectMatcher) *nodeMatcher { |
| 30 | + return &nodeMatcher{ |
| 31 | + objectMatcher: objectMatcher, |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +func (m nodeMatcher) Match(oldOrig, newOrig *v1.Node) (bool, error) { |
| 36 | + |
| 37 | + old := oldOrig.DeepCopy() |
| 38 | + new := newOrig.DeepCopy() |
| 39 | + |
| 40 | + kubernetescorev1.SetObjectDefaults_Node(new) |
| 41 | + |
| 42 | + type Node struct { |
| 43 | + ObjectMeta |
| 44 | + Spec v1.NodeSpec |
| 45 | + } |
| 46 | + |
| 47 | + oldData, err := json.Marshal(Node{ |
| 48 | + ObjectMeta: m.objectMatcher.GetObjectMeta(old.ObjectMeta), |
| 49 | + Spec: old.Spec, |
| 50 | + }) |
| 51 | + if err != nil { |
| 52 | + return false, emperror.WrapWith(err, "could not marshal old object", "name", old.Name) |
| 53 | + } |
| 54 | + |
| 55 | + newObject := Node{ |
| 56 | + ObjectMeta: m.objectMatcher.GetObjectMeta(new.ObjectMeta), |
| 57 | + Spec: new.Spec, |
| 58 | + } |
| 59 | + |
| 60 | + newData, err := json.Marshal(newObject) |
| 61 | + if err != nil { |
| 62 | + return false, emperror.WrapWith(err, "could not marshal new object", "name", new.Name) |
| 63 | + } |
| 64 | + |
| 65 | + matched, err := m.objectMatcher.MatchJSON(oldData, newData, newObject) |
| 66 | + if err != nil { |
| 67 | + return false, emperror.WrapWith(err, "could not match objects", "name", new.Name) |
| 68 | + } |
| 69 | + |
| 70 | + return matched, nil |
| 71 | +} |
0 commit comments