From 9f9ec93591638b0b533c6f900a6d9e16940a7326 Mon Sep 17 00:00:00 2001 From: Jhon Honce Date: Fri, 1 Oct 2021 14:51:28 -0700 Subject: [PATCH] [WIP] API middleware handler to update network list API middleware handler to update memory list of networks if Config.Network.NetworkConfigDir is newer. Fixes #11828 Signed-off-by: Jhon Honce --- pkg/api/server/handler_cache_networks.go | 55 ++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 pkg/api/server/handler_cache_networks.go diff --git a/pkg/api/server/handler_cache_networks.go b/pkg/api/server/handler_cache_networks.go new file mode 100644 index 0000000000..c3fe0cbafe --- /dev/null +++ b/pkg/api/server/handler_cache_networks.go @@ -0,0 +1,55 @@ +package server + +import ( + "net/http" + "os" + "sync" + + "github.com/containers/podman/v3/libpod" + api "github.com/containers/podman/v3/pkg/api/types" + "github.com/gorilla/mux" + "github.com/sirupsen/logrus" +) + +var ( + previousNetworkUpdate os.FileInfo + networkUpdateSync sync.Once +) + +// cacheNetworksHandler refreshes the in-memory network cache if the +// network configuration directory has been changed +func cacheNetworksHandler() mux.MiddlewareFunc { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) + cfg, err := runtime.GetConfig() + if err != nil { + logrus.Infof("Failed to retrieve podman configuration: %v", err) + } else { + netCfg := cfg.Network.NetworkConfigDir + + // First pass of this handler is for initialization. + // 1+ passes will update memory network cache/configuration if the modification + // time of the network configuration directory changes. + networkUpdateSync.Do(func() { + var err error + previousNetworkUpdate, err = os.Stat(netCfg) + logrus.Infof("Failed to access %q: %v", netCfg, err) + }) + + if now, err := os.Stat(netCfg); err != nil { + logrus.Infof("Failed to access %q: %v", netCfg, err) + } else { + if now.ModTime().After(previousNetworkUpdate.ModTime()) { + // + // Reload network cache/configuration + // + previousNetworkUpdate = now + } + } + } + + h.ServeHTTP(w, r) + }) + } +}