...

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  	v1 "k8s.io/api/core/v1"
    21  	ctrl "sigs.k8s.io/controller-runtime"
    22  	"sigs.k8s.io/controller-runtime/pkg/client"
    23  	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
    24  
    25  	"github.com/chaos-mesh/chaos-mesh/controllers/metrics"
    26  	controllerCfg "github.com/chaos-mesh/chaos-mesh/pkg/config"
    27  	"github.com/chaos-mesh/chaos-mesh/pkg/webhook/config"
    28  	"github.com/chaos-mesh/chaos-mesh/pkg/webhook/inject"
    29  )
    30  
    31  var log = ctrl.Log.WithName("inject-webhook")
    32  
    33  // +kubebuilder:webhook:path=/inject-v1-pod,mutating=false,failurePolicy=fail,groups="",resources=pods,verbs=create;update,versions=v1,name=vpod.kb.io
    34  
    35  // PodInjector is pod template config injector
    36  type PodInjector struct {
    37  	client        client.Client
    38  	decoder       *admission.Decoder
    39  	Config        *config.Config
    40  	ControllerCfg *controllerCfg.ChaosControllerConfig
    41  	Metrics       *metrics.ChaosCollector
    42  }
    43  
    44  // Handle is pod injector handler
    45  func (v *PodInjector) Handle(ctx context.Context, req admission.Request) admission.Response {
    46  	pod := &v1.Pod{}
    47  
    48  	err := v.decoder.Decode(req, pod)
    49  	if err != nil {
    50  		return admission.Errored(http.StatusBadRequest, err)
    51  	}
    52  
    53  	log.Info("Get request from pod:", "pod", pod)
    54  
    55  	return admission.Response{
    56  		AdmissionResponse: *inject.Inject(&req.AdmissionRequest, v.client, v.Config, v.ControllerCfg, v.Metrics),
    57  	}
    58  }
    59  
    60  // InjectClient is pod injector client
    61  func (v *PodInjector) InjectClient(c client.Client) error {
    62  	v.client = c
    63  	return nil
    64  }
    65  
    66  // InjectDecoder is pod injector decoder
    67  func (v *PodInjector) InjectDecoder(d *admission.Decoder) error {
    68  	v.decoder = d
    69  	return nil
    70  }
    71