|
| 1 | +/* |
| 2 | +Copyright 2026 Red Hat |
| 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 statefulset |
| 18 | + |
| 19 | +import ( |
| 20 | + corev1 "k8s.io/api/core/v1" |
| 21 | +) |
| 22 | + |
| 23 | +// MergeContainersByName merges desired container specs into existing containers |
| 24 | +// matched by name. It starts from the desired container and preserves only the |
| 25 | +// server-defaulted fields (TerminationMessagePath, TerminationMessagePolicy, |
| 26 | +// ImagePullPolicy) from the existing container. All other fields come from the |
| 27 | +// desired spec, which ensures that new fields added in future Kubernetes |
| 28 | +// versions are not silently dropped. |
| 29 | +// |
| 30 | +// When container counts differ or a desired container name is not found in |
| 31 | +// existing, the existing slice is replaced with the desired containers. |
| 32 | +func MergeContainersByName(existing *[]corev1.Container, desired []corev1.Container) { |
| 33 | + if len(*existing) != len(desired) { |
| 34 | + *existing = desired |
| 35 | + return |
| 36 | + } |
| 37 | + |
| 38 | + existingByName := make(map[string]int, len(*existing)) |
| 39 | + for i := range *existing { |
| 40 | + existingByName[(*existing)[i].Name] = i |
| 41 | + } |
| 42 | + |
| 43 | + for _, d := range desired { |
| 44 | + idx, ok := existingByName[d.Name] |
| 45 | + if !ok { |
| 46 | + *existing = desired |
| 47 | + return |
| 48 | + } |
| 49 | + // Preserve server-defaulted fields from the existing container |
| 50 | + // only when the desired spec doesn't explicitly set them. |
| 51 | + if d.ImagePullPolicy == "" { |
| 52 | + d.ImagePullPolicy = (*existing)[idx].ImagePullPolicy |
| 53 | + } |
| 54 | + if d.TerminationMessagePath == "" { |
| 55 | + d.TerminationMessagePath = (*existing)[idx].TerminationMessagePath |
| 56 | + } |
| 57 | + if d.TerminationMessagePolicy == "" { |
| 58 | + d.TerminationMessagePolicy = (*existing)[idx].TerminationMessagePolicy |
| 59 | + } |
| 60 | + (*existing)[idx] = d |
| 61 | + } |
| 62 | +} |
0 commit comments