in pkg/handler/handler.go [358:439]
func (m *Modifier) MutatePod(ar *v1beta1.AdmissionReview) *v1beta1.AdmissionResponse {
badRequest := &v1beta1.AdmissionResponse{
Result: &metav1.Status{
Message: "bad content",
},
}
if ar == nil {
return badRequest
}
req := ar.Request
if req == nil {
return badRequest
}
var pod corev1.Pod
if err := json.Unmarshal(req.Object.Raw, &pod); err != nil {
klog.Errorf("Could not unmarshal raw object: %v", err)
klog.Errorf("Object: %v", string(req.Object.Raw))
return &v1beta1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
}
pod.Namespace = req.Namespace
// Some mutation parameters can be overridden via pod or serviceaccount
// annotations. The serviceaccount cache already parsed the serviceaccount
// annotations and flags such that annotations take precedence.
// audience: serviceaccount annotation > flag
// regionalSTS: serviceaccount annotation > flag
// tokenExpiration: pod annotation > serviceaccount annotation > flag
podRole, audience, regionalSTS, tokenExpiration := m.Cache.Get(pod.Spec.ServiceAccountName, pod.Namespace)
// determine whether to perform mutation
if podRole == "" {
klog.V(4).Infof("Pod was not mutated. Reason: "+
"Service account did not have the right annotations or was not found in the cache. %s",
logContext(pod.Name,
pod.GenerateName,
pod.Spec.ServiceAccountName,
pod.Namespace))
return &v1beta1.AdmissionResponse{
Allowed: true,
}
}
// parse pod annotations in case they override/set values otherwise dictated
// by serviceaccount annotation or flag
tokenExpiration, containersToSkip := m.parsePodAnnotations(&pod, tokenExpiration)
patch, changed := m.getPodSpecPatch(&pod, podRole, audience, regionalSTS, tokenExpiration, containersToSkip)
patchBytes, err := json.Marshal(patch)
if err != nil {
klog.Errorf("Error marshaling pod update: %v", err.Error())
return &v1beta1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
}
// TODO: klog structured logging can make this better
if changed {
klog.V(3).Infof("Pod was mutated. %s",
logContext(pod.Name, pod.GenerateName, pod.Spec.ServiceAccountName, pod.Namespace))
} else {
klog.V(3).Infof("Pod was not mutated. Reason: "+
"Required volume mounts and env variables were already present. %s",
logContext(pod.Name, pod.GenerateName, pod.Spec.ServiceAccountName, pod.Namespace))
}
return &v1beta1.AdmissionResponse{
Allowed: true,
Patch: patchBytes,
PatchType: func() *v1beta1.PatchType {
pt := v1beta1.PatchTypeJSONPatch
return &pt
}(),
}
}