knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/injection/injection.go (about)

     1  /*
     2  Copyright 2019 The Knative Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package injection
    18  
    19  import (
    20  	"context"
    21  
    22  	"go.uber.org/zap"
    23  	"k8s.io/client-go/rest"
    24  
    25  	"knative.dev/pkg/controller"
    26  	"knative.dev/pkg/logging"
    27  	"knative.dev/pkg/signals"
    28  )
    29  
    30  // EnableInjectionOrDie enables Knative Client Injection, and provides a
    31  // callback to start the informers. Both Context and Config are optional.
    32  // Returns context with rest config set and a callback to start the informers
    33  // after watches have been set.
    34  //
    35  // Typical integration:
    36  // ```go
    37  //
    38  //	ctx, startInformers := injection.EnableInjectionOrDie(signals.NewContext(), nil)
    39  //	... start watches with informers, if required ...
    40  //	startInformers()
    41  //
    42  // ```
    43  func EnableInjectionOrDie(ctx context.Context, cfg *rest.Config) (context.Context, func()) {
    44  	if ctx == nil {
    45  		ctx = signals.NewContext()
    46  	}
    47  	if cfg == nil {
    48  		cfg = ParseAndGetRESTConfigOrDie()
    49  	}
    50  
    51  	// Respect user provided settings, but if omitted customize the default behavior.
    52  	if cfg.QPS == 0 {
    53  		cfg.QPS = rest.DefaultQPS
    54  	}
    55  	if cfg.Burst == 0 {
    56  		cfg.Burst = rest.DefaultBurst
    57  	}
    58  	ctx = WithConfig(ctx, cfg)
    59  
    60  	ctx, informers := Default.SetupInformers(ctx, cfg)
    61  
    62  	return ctx, func() {
    63  		logging.FromContext(ctx).Info("Starting informers...")
    64  		if err := controller.StartInformers(ctx.Done(), informers...); err != nil {
    65  			logging.FromContext(ctx).Fatalw("Failed to start informers", zap.Error(err))
    66  		}
    67  	}
    68  }