85 lines
2.4 KiB
Go
85 lines
2.4 KiB
Go
// Package router — NSWatcher for multi-tenant mode.
|
|
//
|
|
// Listens for Namespaces labeled fission.io/managed=true and calls
|
|
// HTTPTriggerSet.AddNamespace so the router picks up HTTPTriggers and
|
|
// Functions in tenant namespaces without a restart.
|
|
package router
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"go.uber.org/zap"
|
|
corev1 "k8s.io/api/core/v1"
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
k8sInformers "k8s.io/client-go/informers"
|
|
"k8s.io/client-go/kubernetes"
|
|
k8sCache "k8s.io/client-go/tools/cache"
|
|
|
|
"github.com/fission/fission/pkg/utils/manager"
|
|
)
|
|
|
|
const routerManagedNSLabel = "fission.io/managed"
|
|
|
|
// StartNSWatcher registers a Kubernetes Namespace Informer for the router.
|
|
// Whenever a Namespace with label fission.io/managed=true appears (or is relabeled),
|
|
// the router immediately subscribes to HTTPTriggers and Functions in that namespace.
|
|
func StartNSWatcher(
|
|
ctx context.Context,
|
|
logger *zap.Logger,
|
|
kubeClient kubernetes.Interface,
|
|
ts *HTTPTriggerSet,
|
|
mgr manager.Interface,
|
|
) {
|
|
factory := k8sInformers.NewSharedInformerFactoryWithOptions(
|
|
kubeClient,
|
|
30*time.Minute,
|
|
k8sInformers.WithTweakListOptions(func(opts *metav1.ListOptions) {
|
|
opts.LabelSelector = routerManagedNSLabel + "=true"
|
|
}),
|
|
)
|
|
|
|
nsInformer := factory.Core().V1().Namespaces().Informer()
|
|
|
|
_, _ = nsInformer.AddEventHandler(k8sCache.ResourceEventHandlerFuncs{
|
|
AddFunc: func(obj interface{}) {
|
|
ns := routerNSName(obj)
|
|
if ns == "" {
|
|
return
|
|
}
|
|
if err := ts.AddNamespace(ctx, ns, mgr); err != nil {
|
|
logger.Error("router.NSWatcher: AddNamespace failed",
|
|
zap.String("namespace", ns), zap.Error(err))
|
|
}
|
|
},
|
|
UpdateFunc: func(_, newObj interface{}) {
|
|
nsObj, ok := newObj.(*corev1.Namespace)
|
|
if !ok || nsObj.Labels[routerManagedNSLabel] != "true" {
|
|
return
|
|
}
|
|
if err := ts.AddNamespace(ctx, nsObj.Name, mgr); err != nil {
|
|
logger.Error("router.NSWatcher: AddNamespace failed",
|
|
zap.String("namespace", nsObj.Name), zap.Error(err))
|
|
}
|
|
},
|
|
})
|
|
|
|
mgr.Add(ctx, func(ctx context.Context) {
|
|
logger.Info("router.NSWatcher: started",
|
|
zap.String("label", routerManagedNSLabel+"=true"))
|
|
factory.Start(ctx.Done())
|
|
factory.WaitForCacheSync(ctx.Done())
|
|
logger.Info("router.NSWatcher: cache synced — watching for new namespaces")
|
|
<-ctx.Done()
|
|
logger.Info("router.NSWatcher: stopped")
|
|
})
|
|
}
|
|
|
|
func routerNSName(obj interface{}) string {
|
|
nsObj, ok := obj.(*corev1.Namespace)
|
|
if !ok {
|
|
return ""
|
|
}
|
|
return nsObj.Name
|
|
}
|