1 /* 2 Copyright 2020 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 autoscaling 18 19 // DropRoundTripHorizontalPodAutoscalerAnnotations removes any annotations used to serialize round-tripped fields from later API versions, 20 // and returns false if no changes were made and the original input object was returned. 21 // It should always be called when converting internal -> external versions, prior 22 // to setting any of the custom annotations: 23 // 24 // annotations, copiedAnnotations := DropRoundTripHorizontalPodAutoscalerAnnotations(externalObj.Annotations) 25 // externalObj.Annotations = annotations 26 // 27 // if internal.SomeField != nil { 28 // if !copiedAnnotations { 29 // externalObj.Annotations = DeepCopyStringMap(externalObj.Annotations) 30 // copiedAnnotations = true 31 // } 32 // externalObj.Annotations[...] = json.Marshal(...) 33 // } 34 func DropRoundTripHorizontalPodAutoscalerAnnotations(in map[string]string) (out map[string]string, copied bool) { 35 _, hasMetricsSpecs := in[MetricSpecsAnnotation] 36 _, hasBehaviorSpecs := in[BehaviorSpecsAnnotation] 37 _, hasMetricsStatuses := in[MetricStatusesAnnotation] 38 _, hasConditions := in[HorizontalPodAutoscalerConditionsAnnotation] 39 if hasMetricsSpecs || hasBehaviorSpecs || hasMetricsStatuses || hasConditions { 40 out = DeepCopyStringMap(in) 41 delete(out, MetricSpecsAnnotation) 42 delete(out, BehaviorSpecsAnnotation) 43 delete(out, MetricStatusesAnnotation) 44 delete(out, HorizontalPodAutoscalerConditionsAnnotation) 45 return out, true 46 } 47 return in, false 48 } 49 50 // DeepCopyStringMap returns a copy of the input map. 51 // If input is nil, an empty map is returned. 52 func DeepCopyStringMap(in map[string]string) map[string]string { 53 out := make(map[string]string, len(in)) 54 for k, v := range in { 55 out[k] = v 56 } 57 return out 58 } 59