From e26e333b7e084a20e4a2d854626da5d3906e1fe1 Mon Sep 17 00:00:00 2001 From: Erik Wilson Date: Wed, 7 Oct 2020 12:35:44 -0700 Subject: [PATCH] Add network policy controller CacheSyncOrTimeout --- pkg/agent/netpol/network_policy_controller.go | 4 ++++ pkg/agent/netpol/utils.go | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/pkg/agent/netpol/network_policy_controller.go b/pkg/agent/netpol/network_policy_controller.go index b18b806f68..5e729674cb 100644 --- a/pkg/agent/netpol/network_policy_controller.go +++ b/pkg/agent/netpol/network_policy_controller.go @@ -1683,6 +1683,10 @@ func NewNetworkPolicyController( npInformer := informerFactory.Networking().V1().NetworkPolicies().Informer() informerFactory.Start(stopCh) + if err := CacheSyncOrTimeout(informerFactory, stopCh, 1*time.Minute); err != nil { + return nil, errors.New("Failed to synchronize cache: " + err.Error()) + } + // if config.MetricsEnabled { // //Register the metrics for this controller // prometheus.MustRegister(metrics.ControllerIPtablesSyncTime) diff --git a/pkg/agent/netpol/utils.go b/pkg/agent/netpol/utils.go index 1ba3c3cc58..f263581724 100644 --- a/pkg/agent/netpol/utils.go +++ b/pkg/agent/netpol/utils.go @@ -12,8 +12,10 @@ import ( "net" "os/exec" "strings" + "time" apiv1 "k8s.io/api/core/v1" + "k8s.io/client-go/informers" ) var ( @@ -537,3 +539,19 @@ func GetNodeIP(node *apiv1.Node) (net.IP, error) { } return nil, errors.New("host IP unknown") } + +// CacheSync performs cache synchronization under timeout limit +func CacheSyncOrTimeout(informerFactory informers.SharedInformerFactory, stopCh <-chan struct{}, cacheSyncTimeout time.Duration) error { + syncOverCh := make(chan struct{}) + go func() { + informerFactory.WaitForCacheSync(stopCh) + close(syncOverCh) + }() + + select { + case <-time.After(cacheSyncTimeout): + return errors.New(cacheSyncTimeout.String() + " timeout") + case <-syncOverCh: + return nil + } +}