Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webhook readability #209

Merged
merged 4 commits into from
Apr 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions pkg/webhook/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ limitations under the License.
package webhook

import (
"encoding/json"
"fmt"

corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/klog/v2"
)

type Config struct {
Expand Down Expand Up @@ -54,3 +59,91 @@ func LoadConfig(containerImage, imagePullPolicy, cpuRequest, cpuLimit, memoryReq
func FakeConfig() *Config {
return LoadConfig("fake-repo/fake-sidecar-image:v999.999.999-gke.0@sha256:c9cd4cde857ab8052f416609184e2900c0004838231ebf1c3817baa37f21d847", "Always", "250m", "250m", "256Mi", "256Mi", "5Gi", "5Gi")
}

func prepareResourceList(c *Config) (corev1.ResourceList, corev1.ResourceList) {
limitsResourceList := corev1.ResourceList{}
requestsResourceList := corev1.ResourceList{}

checkZeroQuantity := func(rl map[corev1.ResourceName]resource.Quantity, rn corev1.ResourceName, q resource.Quantity) {
if !q.IsZero() {
rl[rn] = q
}
}

checkZeroQuantity(limitsResourceList, corev1.ResourceCPU, c.CPULimit)
checkZeroQuantity(limitsResourceList, corev1.ResourceMemory, c.MemoryLimit)
checkZeroQuantity(limitsResourceList, corev1.ResourceEphemeralStorage, c.EphemeralStorageLimit)
checkZeroQuantity(requestsResourceList, corev1.ResourceCPU, c.CPURequest)
checkZeroQuantity(requestsResourceList, corev1.ResourceMemory, c.MemoryRequest)
checkZeroQuantity(requestsResourceList, corev1.ResourceEphemeralStorage, c.EphemeralStorageRequest)

return limitsResourceList, requestsResourceList
}

// populateResource assigns request and limits based on the following conditions:
// 1. If both of the request and limit are unset, assign the default values.
// 2. If one of the request or limit is set and another is unset, enforce them to be set as the same.
//
// Note: when the annotation limit is zero and request is unset, we set request to use the default value.
func populateResource(requestQuantity, limitQuantity *resource.Quantity, defaultRequestQuantity, defaultLimitQuantity resource.Quantity) {
// Use defaults when no annotations are set.
if requestQuantity.Format == "" && limitQuantity.Format == "" {
*requestQuantity = defaultRequestQuantity
*limitQuantity = defaultLimitQuantity
}

// Set request to equal default when limit is zero/unlimited and request is unset.
if limitQuantity.IsZero() && requestQuantity.Format == "" {
*requestQuantity = defaultRequestQuantity
}

// Set request to equal limit when request annotation is not provided.
if requestQuantity.Format == "" {
*requestQuantity = *limitQuantity
}

// Set limit to equal request when limit annotation is not provided.
if limitQuantity.Format == "" {
*limitQuantity = *requestQuantity
}
}

// prepareConfig overwrittes config values set by user input from pod annotations,
// remaining values that are not specified by user are kept as the default config values.
func (si *SidecarInjector) prepareConfig(annotations map[string]string) (*Config, error) {
config := &Config{
ContainerImage: si.Config.ContainerImage,
ImagePullPolicy: si.Config.ImagePullPolicy,
}

jsonData, err := json.Marshal(annotations)
if err != nil {
return nil, fmt.Errorf("failed to marshal pod annotations: %w", err)
}

if err := json.Unmarshal(jsonData, config); err != nil {
return nil, fmt.Errorf("failed to parse sidecar container resource allocation from pod annotations: %w", err)
}

populateResource(&config.CPURequest, &config.CPULimit, si.Config.CPURequest, si.Config.CPULimit)
populateResource(&config.MemoryRequest, &config.MemoryLimit, si.Config.MemoryRequest, si.Config.MemoryLimit)
populateResource(&config.EphemeralStorageRequest, &config.EphemeralStorageLimit, si.Config.EphemeralStorageRequest, si.Config.EphemeralStorageLimit)

return config, nil
}

func LogPodMutation(pod *corev1.Pod, sidecarConfig *Config) {
klog.Infof("mutating Pod. Name: %q, GenerateName: %q, Namespace: %q, Sidecar Image: %s, CPU Request: %q, CPU limit: %q, Memory request: %q, Memory limit: %q, Ephemeral storage request: %q, Ephemeral storage limit: %q, Pull policy: %s",
pod.Name,
pod.GenerateName,
pod.Namespace,
sidecarConfig.ContainerImage,
sidecarConfig.CPURequest.String(),
sidecarConfig.CPULimit.String(),
sidecarConfig.MemoryRequest.String(),
sidecarConfig.MemoryLimit.String(),
sidecarConfig.EphemeralStorageRequest.String(),
sidecarConfig.EphemeralStorageLimit.String(),
sidecarConfig.ImagePullPolicy,
)
}
101 changes: 101 additions & 0 deletions pkg/webhook/injection.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
Copyright 2018 The Kubernetes Authors.
Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package webhook

import (
"fmt"

corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/version"
"k8s.io/klog/v2"
)

const IstioSidecarName = "istio-proxy"

func (si *SidecarInjector) supportsNativeSidecar() (bool, error) {
clusterNodes, err := si.NodeLister.List(labels.Everything())
if err != nil {
return false, fmt.Errorf("failed to get cluster nodes: %w", err)
}

supportsNativeSidecar := true
for _, node := range clusterNodes {
nodeVersion, err := version.ParseGeneric(node.Status.NodeInfo.KubeletVersion)
if !nodeVersion.AtLeast(minimumSupportedVersion) || err != nil {
if err != nil {
klog.Errorf(`invalid node gke version: could not get node "%s" k8s release from version "%s": "%v"`, node.Name, nodeVersion, err)
}
supportsNativeSidecar = false

break
}
}

if len(clusterNodes) == 0 {
// Rely on cluster version in the event there's no nodes to reference.
if si.ServerVersion != nil {
supportsNativeSidecar = si.ServerVersion.AtLeast(minimumSupportedVersion)
} else {
supportsNativeSidecar = false
}
}

return supportsNativeSidecar, nil
}

func injectSidecarContainer(pod *corev1.Pod, config *Config, supportsNativeSidecar bool) {
if supportsNativeSidecar {
pod.Spec.InitContainers = insert(pod.Spec.InitContainers, GetNativeSidecarContainerSpec(config), getInjectIndex(pod.Spec.InitContainers))
} else {
pod.Spec.Containers = insert(pod.Spec.Containers, GetSidecarContainerSpec(config), getInjectIndex(pod.Spec.Containers))
}
}

func insert(a []corev1.Container, value corev1.Container, index int) []corev1.Container {
// For index == len(a)
if len(a) == index {
return append(a, value)
}

// For index < len(a)
a = append(a[:index+1], a[index:]...)
a[index] = value

return a
}

func getInjectIndex(containers []corev1.Container) int {
idx, present := containerPresent(containers, IstioSidecarName)
if present {
return idx + 1
}

return 0
}

// Checks by name matching that the container is present in container list.
func containerPresent(containers []corev1.Container, container string) (int, bool) {
for idx, c := range containers {
if c.Name == container {
return idx, true
}
}

return -1, false
}
Loading