|
| 1 | +/* |
| 2 | +Copyright 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 webhooks |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + |
| 22 | + appsv1 "k8s.io/api/apps/v1" |
| 23 | + ctrl "sigs.k8s.io/controller-runtime" |
| 24 | + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" |
| 25 | + |
| 26 | + "tpu-slice-controller/internal/core" |
| 27 | +) |
| 28 | + |
| 29 | +type StatefulSetWebhook struct{} |
| 30 | + |
| 31 | +func SetupStatefulSetWebhookWithManager(mgr ctrl.Manager) error { |
| 32 | + return ctrl.NewWebhookManagedBy(mgr, &appsv1.StatefulSet{}). |
| 33 | + WithDefaulter(&StatefulSetWebhook{}). |
| 34 | + Complete() |
| 35 | +} |
| 36 | + |
| 37 | +// +kubebuilder:webhook:path=/mutate-apps-v1-statefulset,mutating=true,failurePolicy=fail,sideEffects=None,groups=apps,resources=statefulsets,verbs=create,versions=v1,name=mstatefulset.slice-controller.kb.io,admissionReviewVersions=v1 |
| 38 | + |
| 39 | +var _ admission.Defaulter[*appsv1.StatefulSet] = &StatefulSetWebhook{} |
| 40 | + |
| 41 | +func (r *StatefulSetWebhook) Default(ctx context.Context, sts *appsv1.StatefulSet) error { |
| 42 | + log := ctrl.LoggerFrom(ctx).WithName("statefulset-webhook") |
| 43 | + log.V(5).Info("Defaulting StatefulSet") |
| 44 | + |
| 45 | + if !core.IsRelevantPodTemplateSpec(sts.Spec.Template) { |
| 46 | + log.V(5).Info("Skipping non-TPUv7 StatefulSet") |
| 47 | + return nil |
| 48 | + } |
| 49 | + |
| 50 | + tpuTopology := core.GetTPUTopology(sts.Spec.Template) |
| 51 | + if sts.Spec.Template.Spec.NodeSelector == nil { |
| 52 | + sts.Spec.Template.Spec.NodeSelector = make(map[string]string) |
| 53 | + } |
| 54 | + if _, ok := sts.Spec.Template.Spec.NodeSelector[core.TPUTopologyAnnotation]; !ok { |
| 55 | + sts.Spec.Template.Spec.NodeSelector[core.TPUTopologyAnnotation] = tpuTopology |
| 56 | + } |
| 57 | + |
| 58 | + return nil |
| 59 | +} |
0 commit comments