...

Source file src/github.com/chaos-mesh/chaos-mesh/api/webhook/inject.go

Documentation: github.com/chaos-mesh/chaos-mesh/api/webhook

     1  // Copyright 2019 Chaos Mesh Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package webhook
    15  
    16  import (
    17  	"context"
    18  	"net/http"
    19  
    20  	"github.com/chaos-mesh/chaos-mesh/controllers/metrics"
    21  	controllerCfg "github.com/chaos-mesh/chaos-mesh/pkg/config"
    22  	"github.com/chaos-mesh/chaos-mesh/pkg/webhook/config"
    23  	"github.com/chaos-mesh/chaos-mesh/pkg/webhook/inject"
    24  
    25  	ctrl "sigs.k8s.io/controller-runtime"
    26  	"sigs.k8s.io/controller-runtime/pkg/client"
    27  	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
    28  
    29  	v1 "k8s.io/api/core/v1"
    30  )
    31  
    32  var log = ctrl.Log.WithName("inject-webhook")
    33  
    34  // +kubebuilder:webhook:path=/inject-v1-pod,mutating=false,failurePolicy=fail,groups="",resources=pods,verbs=create;update,versions=v1,name=vpod.kb.io
    35  
    36  // PodInjector is pod template config injector
    37  type PodInjector struct {
    38  	client        client.Client
    39  	decoder       *admission.Decoder
    40  	Config        *config.Config
    41  	ControllerCfg *controllerCfg.ChaosControllerConfig
    42  	Metrics       *metrics.ChaosCollector
    43  }
    44  
    45  // Handle is pod injector handler
    46  func (v *PodInjector) Handle(ctx context.Context, req admission.Request) admission.Response {
    47  	pod := &v1.Pod{}
    48  
    49  	err := v.decoder.Decode(req, pod)
    50  	if err != nil {
    51  		return admission.Errored(http.StatusBadRequest, err)
    52  	}
    53  
    54  	log.Info("Get request from pod:", "pod", pod)
    55  
    56  	return admission.Response{
    57  		AdmissionResponse: *inject.Inject(&req.AdmissionRequest, v.client, v.Config, v.ControllerCfg, v.Metrics),
    58  	}
    59  }
    60  
    61  // InjectClient is pod injector client
    62  func (v *PodInjector) InjectClient(c client.Client) error {
    63  	v.client = c
    64  	return nil
    65  }
    66  
    67  // InjectDecoder is pod injector decoder
    68  func (v *PodInjector) InjectDecoder(d *admission.Decoder) error {
    69  	v.decoder = d
    70  	return nil
    71  }
    72