Skip to content

Commit

Permalink
fixed namespace and some changes
Browse files Browse the repository at this point in the history
Signed-off-by: Sanskarzz <[email protected]>
  • Loading branch information
Sanskarzz committed Apr 17, 2024
1 parent 836973b commit bde2e65
Show file tree
Hide file tree
Showing 8 changed files with 32 additions and 70 deletions.
2 changes: 0 additions & 2 deletions sidecar-injector/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ go 1.22.1
require (
github.com/ghodss/yaml v1.0.0
github.com/pkg/errors v0.9.1
github.com/samber/lo v1.39.0
github.com/sirupsen/logrus v1.9.3
github.com/spf13/cobra v1.8.0
k8s.io/api v0.29.3
Expand Down Expand Up @@ -34,7 +33,6 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 // indirect
golang.org/x/net v0.19.0 // indirect
golang.org/x/oauth2 v0.10.0 // indirect
golang.org/x/sys v0.15.0 // indirect
Expand Down
4 changes: 0 additions & 4 deletions sidecar-injector/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/samber/lo v1.39.0 h1:4gTz1wUhNYLhFSKl6O+8peW0v2F4BCY034GRpU9WnuA=
github.com/samber/lo v1.39.0/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
Expand All @@ -94,8 +92,6 @@ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9dec
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 h1:3MTrJm4PyNL9NBqvYDSj3DHl46qQakyfqfWo4jgfaEM=
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
Expand Down
6 changes: 2 additions & 4 deletions sidecar-injector/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,9 @@ func Execute() {

func init() {
rootCmd.Flags().IntVar(&httpdConf.Port, "port", 443, "server port.")
rootCmd.Flags().StringVar(&httpdConf.CertFile, "certFile", "/etc/mutator/certs/cert.pem", "File containing tls certificate")
rootCmd.Flags().StringVar(&httpdConf.KeyFile, "keyFile", "/etc/mutator/certs/key.pem", "File containing tls private key")
rootCmd.Flags().StringVar(&httpdConf.CertFile, "certFile", "/etc/mutator/certs/tls.crt", "File containing tls certificate")
rootCmd.Flags().StringVar(&httpdConf.KeyFile, "keyFile", "/etc/mutator/certs/tls.key", "File containing tls private key")
rootCmd.Flags().BoolVar(&httpdConf.Local, "local", false, "Local run mode")
rootCmd.Flags().StringVar(&(&httpdConf.Patcher).InjectPrefix, "injectPrefix", "sidecar-injector", "Injector Prefix")
rootCmd.Flags().StringVar(&(&httpdConf.Patcher).InjectName, "injectName", "inject", "Injector Name")
rootCmd.Flags().StringVar(&(&httpdConf.Patcher).SidecarDataKey, "sidecarDataKey", "sidecars.yaml", "ConfigMap Sidecar Data Key")
rootCmd.Flags().BoolVar(&debug, "debug", false, "enable debug logs")
}
Expand Down
7 changes: 3 additions & 4 deletions sidecar-injector/pkg/admission/admission.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,11 @@ func (handler *Handler) HandleAdmission(writer http.ResponseWriter, request *htt

// Process Handles the AdmissionRequest via the handler
func (handler *Handler) Process(ctx context.Context, request *admissionv1.AdmissionRequest) ([]PatchOperation, error) {
switch request.Operation {
case admissionv1.Create:

if request.Operation == admissionv1.Create {
return handler.Handler.handleAdmissionCreate(ctx, request)
default:
return nil, fmt.Errorf("unhandled request operations type %s", request.Operation)
}
return nil, fmt.Errorf("unhandled request operation %s", request.Operation)
}

func validateRequest(req *http.Request) error {
Expand Down
2 changes: 1 addition & 1 deletion sidecar-injector/pkg/admission/podpatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ import (
)

type PodPatcher interface {
PatchPodCreate(ctx context.Context, namespace string, pod corev1.Pod) ([]PatchOperation, error)
PatchPodCreate(ctx context.Context, pod corev1.Pod) ([]PatchOperation, error)
}
2 changes: 1 addition & 1 deletion sidecar-injector/pkg/admission/podrequesthandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func (handler *PodAdmissionRequestHandler) handleAdmissionCreate(ctx context.Con
if err != nil {
return nil, err
}
return handler.PodHandler.PatchPodCreate(ctx, request.Namespace, pod)
return handler.PodHandler.PatchPodCreate(ctx, pod)
}

func unmarshalPod(rawObject []byte) (corev1.Pod, error) {
Expand Down
1 change: 1 addition & 0 deletions sidecar-injector/pkg/httpd/simpleserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ func (simpleServer *SimpleServer) Start() error {
if simpleServer.Local {
return server.ListenAndServe()
}
log.Infof("Starting tls server on port %d", simpleServer.Port)
return server.ListenAndServeTLS(simpleServer.CertFile, simpleServer.KeyFile)
}

Expand Down
78 changes: 24 additions & 54 deletions sidecar-injector/pkg/webhook/sidecarhandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (

"github.com/ghodss/yaml"
"github.com/kyverno/kyverno-envoy-plugin/sidecar-injector/pkg/admission"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
Expand All @@ -28,40 +27,11 @@ type Sidecar struct {
// SidecarInjectorPatcher Sidecar Injector patcher
type SidecarInjectorPatcher struct {
K8sClient kubernetes.Interface
InjectPrefix string
InjectName string
SidecarDataKey string
AllowAnnotationOverrides bool
AllowLabelOverrides bool
}

func (patcher *SidecarInjectorPatcher) sideCarInjectionAnnotation() string {
return patcher.InjectPrefix + "/" + patcher.InjectName
}

func (patcher *SidecarInjectorPatcher) configmapSidecarNames(namespace string, pod corev1.Pod) []string {
podName := pod.GetName()
if podName == "" {
podName = pod.GetGenerateName()
}
annotations := map[string]string{}
if pod.GetAnnotations() != nil {
annotations = pod.GetAnnotations()
}
if sidecars, ok := annotations[patcher.sideCarInjectionAnnotation()]; ok {
parts := lo.Map[string, string](strings.Split(sidecars, ","), func(part string, _ int) string {
return strings.TrimSpace(part)
})

if len(parts) > 0 {
log.Infof("sideCar injection for %v/%v: sidecars: %v", namespace, podName, sidecars)
return parts
}
}
log.Infof("Skipping mutation for [%v]. No action required", pod.GetName())
return nil
}

func createArrayPatches[T any](newCollection []T, existingCollection []T, path string) []admission.PatchOperation {
var patches []admission.PatchOperation
for index, item := range newCollection {
Expand Down Expand Up @@ -118,37 +88,37 @@ func escapeJSONPath(k string) string {
}

// PatchPodCreate Handle Pod Create Patch
func (patcher *SidecarInjectorPatcher) PatchPodCreate(ctx context.Context, namespace string, pod corev1.Pod) ([]admission.PatchOperation, error) {
func (patcher *SidecarInjectorPatcher) PatchPodCreate(ctx context.Context, pod corev1.Pod) ([]admission.PatchOperation, error) {
namespace := "sidecar-injector"
podName := pod.GetName()
if podName == "" {
podName = pod.GetGenerateName()
}
var patches []admission.PatchOperation
if configmapSidecarNames := patcher.configmapSidecarNames(namespace, pod); configmapSidecarNames != nil {
for _, configmapSidecarName := range configmapSidecarNames {
configmapSidecar, err := patcher.K8sClient.CoreV1().ConfigMaps(namespace).Get(ctx, configmapSidecarName, metav1.GetOptions{})
if k8serrors.IsNotFound(err) {
log.Warnf("sidecar configmap %s/%s was not found", namespace, configmapSidecarName)
} else if err != nil {
log.Errorf("error fetching sidecar configmap %s/%s - %v", namespace, configmapSidecarName, err)
} else if sidecarsStr, ok := configmapSidecar.Data[patcher.SidecarDataKey]; ok {
var sidecars []Sidecar
if err := yaml.Unmarshal([]byte(sidecarsStr), &sidecars); err != nil {
log.Errorf("error unmarshalling %s from configmap %s/%s", patcher.SidecarDataKey, pod.GetNamespace(), configmapSidecarName)
}
if sidecars != nil {
for _, sidecar := range sidecars {
patches = append(patches, createArrayPatches(sidecar.InitContainers, pod.Spec.InitContainers, "/spec/initContainers")...)
patches = append(patches, createArrayPatches(sidecar.Containers, pod.Spec.Containers, "/spec/containers")...)
patches = append(patches, createArrayPatches(sidecar.Volumes, pod.Spec.Volumes, "/spec/volumes")...)
patches = append(patches, createArrayPatches(sidecar.ImagePullSecrets, pod.Spec.ImagePullSecrets, "/spec/imagePullSecrets")...)
patches = append(patches, createObjectPatches(sidecar.Annotations, pod.Annotations, "/metadata/annotations", patcher.AllowAnnotationOverrides)...)
patches = append(patches, createObjectPatches(sidecar.Labels, pod.Labels, "/metadata/labels", patcher.AllowLabelOverrides)...)
}
log.Debugf("sidecar patches being applied for %v/%v: patches: %v", namespace, podName, patches)
}
configmapSidecarName := "kyverno-envoy-sidecar"
log.Infof("sideCar injection for %v/%v: sidecars: %v", namespace, podName, configmapSidecarName)
configmapSidecar, err := patcher.K8sClient.CoreV1().ConfigMaps(namespace).Get(ctx, configmapSidecarName, metav1.GetOptions{})
if k8serrors.IsNotFound(err) {
log.Warnf("sidecar configmap %s/%s was not found", namespace, configmapSidecarName)
} else if err != nil {
log.Errorf("error fetching sidecar configmap %s/%s - %v", namespace, configmapSidecarName, err)
} else if sidecarsStr, ok := configmapSidecar.Data[patcher.SidecarDataKey]; ok {
var sidecars []Sidecar
if err := yaml.Unmarshal([]byte(sidecarsStr), &sidecars); err != nil {
log.Errorf("error unmarshalling %s from configmap %s/%s", patcher.SidecarDataKey, pod.GetNamespace(), configmapSidecarName)
}
if sidecars != nil {
for _, sidecar := range sidecars {
patches = append(patches, createArrayPatches(sidecar.InitContainers, pod.Spec.InitContainers, "/spec/initContainers")...)
patches = append(patches, createArrayPatches(sidecar.Containers, pod.Spec.Containers, "/spec/containers")...)
patches = append(patches, createArrayPatches(sidecar.Volumes, pod.Spec.Volumes, "/spec/volumes")...)
patches = append(patches, createArrayPatches(sidecar.ImagePullSecrets, pod.Spec.ImagePullSecrets, "/spec/imagePullSecrets")...)
patches = append(patches, createObjectPatches(sidecar.Annotations, pod.Annotations, "/metadata/annotations", patcher.AllowAnnotationOverrides)...)
patches = append(patches, createObjectPatches(sidecar.Labels, pod.Labels, "/metadata/labels", patcher.AllowLabelOverrides)...)
}
log.Debugf("sidecar patches being applied for %v/%v: patches: %v", namespace, podName, patches)
}
}

return patches, nil
}

0 comments on commit bde2e65

Please sign in to comment.