github.com/telepresenceio/telepresence/v2@v2.20.0-pro.6.0.20240517030216-236ea954e789/pkg/informer/context.go (about)

     1  package informer
     2  
     3  import (
     4  	"context"
     5  
     6  	"k8s.io/client-go/informers"
     7  
     8  	"github.com/datawire/k8sapi/pkg/k8sapi"
     9  )
    10  
    11  type factoryKey string
    12  
    13  func WithFactory(ctx context.Context, ns string) context.Context {
    14  	var opts []informers.SharedInformerOption
    15  	if ns != "" {
    16  		opts = append(opts, informers.WithNamespace(ns))
    17  	}
    18  	factory := informers.NewSharedInformerFactoryWithOptions(k8sapi.GetK8sInterface(ctx), 0, opts...)
    19  	return context.WithValue(ctx, factoryKey(ns), factory)
    20  }
    21  
    22  func GetFactory(ctx context.Context, ns string) informers.SharedInformerFactory {
    23  	if f, ok := ctx.Value(factoryKey(ns)).(informers.SharedInformerFactory); ok {
    24  		return f
    25  	}
    26  	// Check if cluster-global a factory is available, unless that was what was
    27  	// originally requested.
    28  	if ns != "" {
    29  		if f, ok := ctx.Value(factoryKey("")).(informers.SharedInformerFactory); ok {
    30  			return f
    31  		}
    32  	}
    33  	return nil
    34  }