func setupWebhook()

in cmd/manager/main.go [1011:1086]


func setupWebhook(
	ctx context.Context,
	mgr manager.Manager,
	params operator.Parameters,
	webhookCertDir string,
	clientset kubernetes.Interface,
	exposedNodeLabels esvalidation.NodeLabels,
	managedNamespaces []string,
	tracer *apm.Tracer) {
	manageWebhookCerts := viper.GetBool(operator.ManageWebhookCertsFlag)
	if manageWebhookCerts {
		if err := reconcileWebhookCertsAndAddController(ctx, mgr, params.CertRotation, clientset, tracer); err != nil {
			log.Error(err, "unable to setup the webhook certificates")
			os.Exit(1)
		}
	}

	checker := commonlicense.NewLicenseChecker(mgr.GetClient(), params.OperatorNamespace)
	// setup webhooks for supported types
	webhookObjects := []interface {
		runtime.Object
		admission.Validator
		WebhookPath() string
	}{
		&agentv1alpha1.Agent{},
		&apmv1.ApmServer{},
		&apmv1beta1.ApmServer{},
		&beatv1beta1.Beat{},
		&entv1.EnterpriseSearch{},
		&entv1beta1.EnterpriseSearch{},
		&esv1beta1.Elasticsearch{},
		&kbv1.Kibana{},
		&kbv1beta1.Kibana{},
		&emsv1alpha1.ElasticMapsServer{},
		&policyv1alpha1.StackConfigPolicy{},
	}
	for _, obj := range webhookObjects {
		commonwebhook.SetupValidatingWebhookWithConfig(&commonwebhook.Config{
			Manager:          mgr,
			WebhookPath:      obj.WebhookPath(),
			ManagedNamespace: managedNamespaces,
			Validator:        obj,
			LicenseChecker:   checker,
		})
	}

	// Logstash, Elasticsearch and ElasticsearchAutoscaling validating webhooks are wired up differently, in order to access the k8s client
	esvalidation.RegisterWebhook(mgr, params.ValidateStorageClass, exposedNodeLabels, checker, managedNamespaces)
	esavalidation.RegisterWebhook(mgr, params.ValidateStorageClass, checker, managedNamespaces)
	lsvalidation.RegisterWebhook(mgr, params.ValidateStorageClass, managedNamespaces)

	// wait for the secret to be populated in the local filesystem before returning
	interval := time.Second * 1
	timeout := time.Second * 30
	keyPath := filepath.Join(webhookCertDir, certificates.CertFileName)
	log.Info("Polling for the webhook certificate to be available", "path", keyPath)
	//nolint:staticcheck
	err := wait.PollImmediateWithContext(ctx, interval, timeout, func(_ context.Context) (bool, error) {
		_, err := os.Stat(keyPath)
		// err could be that the file does not exist, but also that permission was denied or something else
		if os.IsNotExist(err) {
			log.V(1).Info("Webhook certificate file not present on filesystem yet", "path", keyPath)

			return false, nil
		} else if err != nil {
			log.Error(err, "Error checking if webhook secret path exists", "path", keyPath)
			return false, err
		}
		log.V(1).Info("Webhook certificate file present on filesystem", "path", keyPath)
		return true, nil
	})
	if err != nil {
		log.Error(err, "Timeout elapsed waiting for webhook certificate to be available", "path", keyPath, "timeout_seconds", timeout.Seconds())
		os.Exit(1)
	}
}