From 989159a20ca24fd1a68d84d29a03617a4d5742fc Mon Sep 17 00:00:00 2001 From: Marc Khouzam Date: Thu, 3 Oct 2024 22:51:16 -0400 Subject: [PATCH] Avoid writing to the config file if not necessary Writing to the config file to update the server list has a small cost. However, since this is done repeatedly for each configured context, this cost can accumulate when users have a lot of contexts. In my case, with 27 contexts (not realistic but I was testing) the slow down increased by about 0.65 seconds on my M1 Mac, making the startup jump from around 0.35 seconds to 1 second. This may be due to repeatedly writing to the configuration files. The synchronization of the servers is done for every single CLI command (since it is in an init()), which means that if there is a slow down, it affects every single CLI command, even printing help and shell completion. Although doing this synchronization in an init() is probably overkill, it would be acceptable if actually writing to the config files was limited to when it was necessary. This is because updating the server list does not actually need to be done all the time but only if there is a discrepency. Tis commit checks if there is actually any missing servers by comparing the list of contexts with the list of servers, and only if there are missing servers will it trigger the update. Signed-off-by: Marc Khouzam --- pkg/config/context.go | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/pkg/config/context.go b/pkg/config/context.go index c9555310e..375088eb4 100644 --- a/pkg/config/context.go +++ b/pkg/config/context.go @@ -7,6 +7,7 @@ import ( "github.com/pkg/errors" "github.com/vmware-tanzu/tanzu-plugin-runtime/config" + "github.com/vmware-tanzu/tanzu-plugin-runtime/config/types" ) // SyncContextsAndServers populate or sync contexts and servers @@ -16,7 +17,11 @@ func SyncContextsAndServers() error { return errors.Wrap(err, "failed to get client config") } - config.PopulateContexts(cfg) + hasChanged := config.PopulateContexts(cfg) + needsSync := doServersNeedUpdate(cfg) + if !hasChanged && !needsSync { + return nil + } // Now write the context to the configuration file. This will also create any missing server for its corresponding context for _, c := range cfg.KnownContexts { @@ -36,3 +41,22 @@ func SyncContextsAndServers() error { } return nil } + +func doServersNeedUpdate(cfg *types.ClientConfig) bool { + if cfg == nil { + return false + } + + for _, c := range cfg.KnownContexts { + if c.ContextType == types.ContextTypeTanzu || cfg.HasServer(c.Name) { //nolint:staticcheck // Deprecated + // context of type "tanzu" don't get synched + // or context already present in servers; skip + continue + } + // Found a context that is not in the servers. We need to update + // the servers section + return true + } + + return false +}