diff --git a/ipn/ipnlocal/diskcache.go b/ipn/ipnlocal/diskcache.go index 065876a03..2077393e3 100644 --- a/ipn/ipnlocal/diskcache.go +++ b/ipn/ipnlocal/diskcache.go @@ -78,7 +78,12 @@ func (b *LocalBackend) ensureDiskCacheLocked() error { return err } if c := b.diskCache; c.cache == nil || c.dir != dir { - b.diskCache.cache = netmapcache.NewCache(netmapcache.FileStore(dir)) + b.closeDiskCacheLocked() // if we changed the dir, close the previous cache. + store, err := netmapcache.NewStore(b.ctx, dir) + if err != nil { + return fmt.Errorf("unable to open store: %s", err) + } + b.diskCache.cache = netmapcache.NewCache(store) b.diskCache.dir = dir } return nil @@ -94,7 +99,13 @@ func (b *LocalBackend) loadDiskCacheLocked() (om *netmap.NetworkMap, ok bool) { return nil, false } if c := b.diskCache; c.cache == nil || c.dir != dir { - b.diskCache.cache = netmapcache.NewCache(netmapcache.FileStore(dir)) + b.closeDiskCacheLocked() // if we changed the dir, close the previous cache. + store, err := netmapcache.NewStore(b.currentNode().Context(), dir) + if err != nil { + b.logf("unable to open store: %s", err) + return nil, false + } + b.diskCache.cache = netmapcache.NewCache(store) b.diskCache.dir = dir } nm, err := b.diskCache.cache.Load(b.currentNode().Context()) @@ -114,28 +125,30 @@ func (b *LocalBackend) discardDiskCacheLocked() { if b.diskCache.cache == nil { return // nothing to do, we do not have a cache } - // Reaching here, we have a cache directory that needs to be purged. - // Log errors but do not fail for them. - store := netmapcache.FileStore(b.diskCache.dir) - if err := b.clearStoreLocked(b.currentNode().Context(), store); err != nil { + // Reaching here, we have a cache that needs to be purged. + // Log errors but do not fail for them. Clear both the configured store and + // the fallback FileStore. This could be the same store twice, in which case + // the second clear will do nothing. We do this so that clients built with + // only the default FileStore support will not persist stale cache data after + // switching to a different storage implementation. + if err := b.diskCache.cache.Clear(b.ctx); err != nil { b.logf("clearing netmap cache: %v", err) } + store := netmapcache.FileStore(b.diskCache.dir) + if err := store.Clear(b.ctx); err != nil { + b.logf("clearing netmap cache: %v", err) + } + b.closeDiskCacheLocked() b.diskCache = diskCache{} // drop in-memory state } -// clearStoreLocked discards all the keys in the specified store. -func (b *LocalBackend) clearStoreLocked(ctx context.Context, store netmapcache.Store) error { - var errs []error - for key, err := range store.List(ctx, "") { - if err != nil { - errs = append(errs, fmt.Errorf("list cache contest: %w", err)) - break - } - if err := store.Remove(ctx, key); err != nil { - errs = append(errs, fmt.Errorf("discard cache key %q: %w", key, err)) - } +func (b *LocalBackend) closeDiskCacheLocked() { + if b.diskCache.cache == nil { + return // nothing to do, we do not have a cache + } + if err := b.diskCache.cache.Close(b.ctx); err != nil { + b.logf("error closing cache: %v", err) } - return errors.Join(errs...) } // ClearNetmapCache discards stored netmap caches (if any) for profiles for the @@ -149,15 +162,33 @@ func (b *LocalBackend) ClearNetmapCache(ctx context.Context) error { b.mu.Lock() defer b.mu.Unlock() + // Close the active cache before clearing profiles so we can safely re-open + // each profile's store. We hold the lock here to ensure no writes happens to + // the active profile while clearing profiles. + b.closeDiskCacheLocked() + b.diskCache = diskCache{} + var errs []error for _, p := range b.pm.Profiles() { - store := netmapcache.FileStore(b.profileDataPathLocked(p.ID(), "netmap-cache")) - err := b.clearStoreLocked(ctx, store) - if err != nil { - errs = append(errs, fmt.Errorf("clear netmap cache for profile %q: %w", p.ID(), err)) + dir := b.profileDataPathLocked(p.ID(), "netmap-cache") + + // Open and clear the configured store for this profile. + if store, err := netmapcache.OpenStore(ctx, dir); err != nil { + errs = append(errs, fmt.Errorf("open store for profile %q: %w", p.ID(), err)) + } else if store == nil { + continue // store does not exist + } else { + if err := store.Clear(ctx); err != nil { + errs = append(errs, fmt.Errorf("clear netmap cache for profile %q: %w", p.ID(), err)) + } + store.Close(ctx) + } + + // Also clear the FileStore as a fallback for file-based entries left over + // from instances running without a no-file backend. + if err := netmapcache.FileStore(dir).Clear(ctx); err != nil { + errs = append(errs, fmt.Errorf("clear file cache for profile %q: %w", p.ID(), err)) } } - - b.diskCache = diskCache{} // drop in-memory state return errors.Join(errs...) } diff --git a/ipn/ipnlocal/diskcache_test.go b/ipn/ipnlocal/diskcache_test.go index 1e3b4808b..5cdec4ae2 100644 --- a/ipn/ipnlocal/diskcache_test.go +++ b/ipn/ipnlocal/diskcache_test.go @@ -5,8 +5,11 @@ package ipnlocal import ( "net/netip" + "os" "testing" + "tailscale.com/ipn" + "tailscale.com/ipn/ipnlocal/netmapcache" "tailscale.com/tailcfg" "tailscale.com/tstest" "tailscale.com/types/netmap" @@ -204,6 +207,115 @@ func TestOnHomeDERPUpdate(t *testing.T) { }) } +func TestDiscardDiskCacheLocked(t *testing.T) { + b := newTestBackend(t) + nm := newCacheTestNetmap() + b.currentNode().SetNetMap(nm) + + b.mu.Lock() + defer b.mu.Unlock() + + if err := b.writeNetmapToDiskLockedWithPeers(nm); err != nil { + t.Fatalf("write: %v", err) + } + if _, ok := b.loadDiskCacheLocked(); !ok { + t.Fatal("expected cache to be loadable after write") + } + + b.discardDiskCacheLocked() + + if _, ok := b.loadDiskCacheLocked(); ok { + t.Fatal("expected cache to be gone after discard") + } +} + +func TestClearNetmapCache(t *testing.T) { + b := newTestBackend(t) + nm := newCacheTestNetmap() + b.currentNode().SetNetMap(nm) + + // Add the current profile to knownProfiles so ClearNetmapCache can iterate + // over it later. + cp := b.pm.CurrentProfile() + b.pm.knownProfiles[cp.ID()] = cp + + b.mu.Lock() + if err := b.writeNetmapToDiskLockedWithPeers(nm); err != nil { + b.mu.Unlock() + t.Fatalf("write: %v", err) + } + b.mu.Unlock() + + if err := b.ClearNetmapCache(t.Context()); err != nil { + t.Fatalf("ClearNetmapCache: %v", err) + } + + b.mu.Lock() + defer b.mu.Unlock() + if _, ok := b.loadDiskCacheLocked(); ok { + t.Error("expected cache to be gone after ClearNetmapCache") + } +} + +func TestClearNetmapCacheMultiProfile(t *testing.T) { + b := newTestBackend(t) + nm := newCacheTestNetmap() + b.currentNode().SetNetMap(nm) + + // Register two profiles so ClearNetmapCache sees both. + profile2 := (&ipn.LoginProfile{ID: "id-extra"}).View() + + // Add the profiles to knownProfiles so ClearNetmapCache can iterate + // over them later. + cp := b.pm.CurrentProfile() + b.pm.knownProfiles[cp.ID()] = cp + b.pm.knownProfiles[profile2.ID()] = profile2 + + b.mu.Lock() + + // Write netmap for the active profile. + if err := b.writeNetmapToDiskLockedWithPeers(nm); err != nil { + b.mu.Unlock() + t.Fatalf("write profile1: %v", err) + } + + // Seed the second profile's cache directory directly emulating another + // configured profile. + dir2, err := b.profileMkdirAllLocked(profile2.ID(), "netmap-cache") + if err != nil { + b.mu.Unlock() + t.Fatalf("mkdir profile2: %v", err) + } + store2 := netmapcache.FileStore(dir2) + if err := store2.Store(t.Context(), "self", []byte(`{"Node":{}}`)); err != nil { + b.mu.Unlock() + t.Fatalf("seed profile2: %v", err) + } + + b.mu.Unlock() + + if err := b.ClearNetmapCache(t.Context()); err != nil { + t.Fatalf("ClearNetmapCache: %v", err) + } + + // Verify that the active profile is cleared. + b.mu.Lock() + _, ok := b.loadDiskCacheLocked() + b.mu.Unlock() + if ok { + t.Error("profile1 cache still present after ClearNetmapCache") + } + + // Verify that the directory for the simulated cached profile is empty. + entries, err := os.ReadDir(dir2) + if err != nil && !os.IsNotExist(err) { + t.Fatalf("ReadDir cached profile: %v", err) + } + if len(entries) > 0 { + t.Errorf("directory for cached profile not cleared: %d entries remain", len(entries)) + } +} + func TestWriteNetmapDoesNotMutateOriginal(t *testing.T) { b := newTestBackend(t) diff --git a/ipn/ipnlocal/local.go b/ipn/ipnlocal/local.go index 8061ab710..4ac4fe0d8 100644 --- a/ipn/ipnlocal/local.go +++ b/ipn/ipnlocal/local.go @@ -1406,6 +1406,7 @@ func (b *LocalBackend) shutdown() { b.notifyCancel() } b.appConnector.Close() + b.closeDiskCacheLocked() b.mu.Unlock() // These shutdown methods wait for goroutines that can acquire b.mu. The @@ -8783,6 +8784,7 @@ func (b *LocalBackend) resetForProfileChangeLocked() error { // down, so no need to do any work. return nil } + b.closeDiskCacheLocked() if buildfeatures.HasDNS { if dm, ok := b.sys.DNSManager.GetOK(); ok { dm.Resolver().ClearNegativeCache() diff --git a/ipn/ipnlocal/netmapcache/default_store.go b/ipn/ipnlocal/netmapcache/default_store.go new file mode 100644 index 000000000..de0bc524e --- /dev/null +++ b/ipn/ipnlocal/netmapcache/default_store.go @@ -0,0 +1,29 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package netmapcache + +import ( + "context" + "errors" + "os" +) + +// TODO(cmol): Add compiler flags when having more stores + +// NewStore creates [Store] for backing the netmapcache. If the [Store] already +// exists, open the existing [Store]. +func NewStore(_ context.Context, dir string) (Store, error) { + return FileStore(dir), nil +} + +// OpenStore opens an existing [Store]. Returns nil, nil, if the store does not +// exist. +func OpenStore(_ context.Context, dir string) (Store, error) { + if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) { + return nil, nil + } else if err != nil { + return nil, err + } + return FileStore(dir), nil +} diff --git a/ipn/ipnlocal/netmapcache/file_store.go b/ipn/ipnlocal/netmapcache/file_store.go new file mode 100644 index 000000000..1980bc2e5 --- /dev/null +++ b/ipn/ipnlocal/netmapcache/file_store.go @@ -0,0 +1,94 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package netmapcache + +import ( + "context" + "encoding/hex" + "errors" + "fmt" + "io/fs" + "iter" + "os" + "path/filepath" + "strings" +) + +// FileStore implements the [Store] interface using a directory of files, in +// which each key is encoded as a filename in the directory. +// The caller is responsible to ensure the directory path exists before +// using the store methods. The string is the absolute path to the directory. +type FileStore string + +// List implements part of the [Store] interface. +func (s FileStore) List(ctx context.Context, prefix string) iter.Seq2[string, error] { + return func(yield func(string, error) bool) { + des, err := os.ReadDir(string(s)) + if os.IsNotExist(err) { + return // nothing to read + } else if err != nil { + yield("", err) + return + } + + // os.ReadDir reports entries already sorted, and the encoding preserves that. + for _, de := range des { + if de.IsDir() { + continue + } + key, err := hex.DecodeString(de.Name()) + if err != nil { + yield("", err) + return + } + name := string(key) + if !strings.HasPrefix(name, prefix) { + continue + } else if !yield(name, nil) { + return + } + } + } +} + +// Load implements part of the [Store] interface. +func (s FileStore) Load(ctx context.Context, key string) ([]byte, error) { + data, err := os.ReadFile(filepath.Join(string(s), hex.EncodeToString([]byte(key)))) + if errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("key %q not found: %w", key, ErrKeyNotFound) + } + return data, err +} + +// Store implements part of the [Store] interface. +func (s FileStore) Store(ctx context.Context, key string, value []byte) error { + return os.WriteFile(filepath.Join(string(s), hex.EncodeToString([]byte(key))), value, 0600) +} + +// Remove implements part of the [Store] interface. +func (s FileStore) Remove(ctx context.Context, key string) error { + err := os.Remove(filepath.Join(string(s), hex.EncodeToString([]byte(key)))) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + return err +} + +// Close implements part of the [Store] interface. +func (s FileStore) Close(context.Context) error { return nil } + +// Clear implements part of the [Store] interface. +func (s FileStore) Clear(ctx context.Context) error { + var errs []error + for key, err := range s.List(ctx, "") { + if err != nil { + errs = append(errs, fmt.Errorf("list cache contents: %w", err)) + break + } + if err := s.Remove(ctx, key); err != nil { + errs = append(errs, fmt.Errorf("discard cache key %q: %w", key, err)) + } + } + return errors.Join(errs...) +} diff --git a/ipn/ipnlocal/netmapcache/netmapcache.go b/ipn/ipnlocal/netmapcache/netmapcache.go index 9f0454881..66c6b5d34 100644 --- a/ipn/ipnlocal/netmapcache/netmapcache.go +++ b/ipn/ipnlocal/netmapcache/netmapcache.go @@ -10,16 +10,11 @@ import ( "cmp" "context" "crypto/sha256" - "encoding/hex" jsonv1 "encoding/json" "errors" "fmt" - "io/fs" "iter" - "os" - "path/filepath" "slices" - "strings" "time" "tailscale.com/feature/buildfeatures" @@ -123,63 +118,6 @@ func (c *Cache) removeUnwantedKeys(ctx context.Context) error { return errors.Join(errs...) } -// FileStore implements the [Store] interface using a directory of files, in -// which each key is encoded as a filename in the directory. -// The caller is responsible to ensure the directory path exists before -// using the store methods. -type FileStore string - -// List implements part of the [Store] interface. -func (s FileStore) List(ctx context.Context, prefix string) iter.Seq2[string, error] { - return func(yield func(string, error) bool) { - des, err := os.ReadDir(string(s)) - if os.IsNotExist(err) { - return // nothing to read - } else if err != nil { - yield("", err) - return - } - - // os.ReadDir reports entries already sorted, and the encoding preserves that. - for _, de := range des { - key, err := hex.DecodeString(de.Name()) - if err != nil { - yield("", err) - return - } - name := string(key) - if !strings.HasPrefix(name, prefix) { - continue - } else if !yield(name, nil) { - return - } - } - } -} - -// Load implements part of the [Store] interface. -func (s FileStore) Load(ctx context.Context, key string) ([]byte, error) { - data, err := os.ReadFile(filepath.Join(string(s), hex.EncodeToString([]byte(key)))) - if errors.Is(err, os.ErrNotExist) { - return nil, fmt.Errorf("key %q not found: %w", key, ErrKeyNotFound) - } - return data, err -} - -// Store implements part of the [Store] interface. -func (s FileStore) Store(ctx context.Context, key string, value []byte) error { - return os.WriteFile(filepath.Join(string(s), hex.EncodeToString([]byte(key))), value, 0600) -} - -// Remove implements part of the [Store] interface. -func (s FileStore) Remove(ctx context.Context, key string) error { - err := os.Remove(filepath.Join(string(s), hex.EncodeToString([]byte(key)))) - if errors.Is(err, fs.ErrNotExist) { - return nil - } - return err -} - // cacheKey is a type wrapper for strings used as cache keys. type cacheKey string @@ -424,6 +362,14 @@ func (c *Cache) readJSON(ctx context.Context, key cacheKey, value any) error { return nil } +func (c *Cache) Clear(ctx context.Context) error { + return c.store.Clear(ctx) +} + +func (c *Cache) Close(ctx context.Context) error { + return c.store.Close(ctx) +} + // Store is the interface to persistent key-value storage used by a [Cache]. type Store interface { // List lists all the stored keys having the specified prefixes, in @@ -445,6 +391,18 @@ type Store interface { // Remove removes the specified key from the store. If the key does not exist, // Remove reports success (nil). Remove(ctx context.Context, key string) error + + // Clear removes all entries from the store. On success, the store must + // contain no keys. In case of error, the implementation should attempt + // to remove as much as possible before giving up and reporting an error. + Clear(ctx context.Context) error + + // Close closes the Store, releasing any resources held by the + // implementation, but retaining all data previously written. + // After caling Close, the cache will not apply any further + // operations to the receiver. If the implementation does not + // require any cleanup, Close must return nil. + Close(ctx context.Context) error } // cacheDigest computes a string digest of the specified data, for use in diff --git a/ipn/ipnlocal/netmapcache/netmapcache_test.go b/ipn/ipnlocal/netmapcache/netmapcache_test.go index deb88d36b..f90f17618 100644 --- a/ipn/ipnlocal/netmapcache/netmapcache_test.go +++ b/ipn/ipnlocal/netmapcache/netmapcache_test.go @@ -206,7 +206,6 @@ func TestRoundTrip(t *testing.T) { if diff := diffNetMaps(cmap, testMap); diff != "" { t.Fatalf("Cached map differs (-got, +want):\n%s", diff) } - }) } @@ -468,6 +467,58 @@ func TestPartial(t *testing.T) { }) } +func TestClearStore(t *testing.T) { + s := make(testStore) + c := netmapcache.NewCache(s) + + // Initialize the cache with the test map so we get a baseline. + if err := c.Store(t.Context(), testMap); err != nil { + t.Fatalf("Store initial netmap: %s", err) + } + + if got, err := c.Load(t.Context()); err != nil { + t.Errorf("error loading netmap: %s", err) + } else if len(got.Peers) == 0 { + t.Errorf("expected peers in netmap, got none. Loaded netmap: %+v", got) + } + + if err := c.Clear(t.Context()); err != nil { + t.Errorf("error clearing netmap: %s", err) + } + + if len(s) > 0 { + t.Errorf("expected testStore to be empty, got: %+v", s) + } +} + +func TestOpenStore(t *testing.T) { + t.Run("non_exist", func(t *testing.T) { + if store, err := netmapcache.OpenStore(t.Context(), "/not/here"); store != nil || err != nil { + t.Errorf("expected a nil store and a nil error, got store: %+v, err: %s", store, err) + } + }) + + t.Run("exist", func(t *testing.T) { + dir := t.TempDir() + store, err := netmapcache.NewStore(t.Context(), dir) + if err != nil { + t.Fatalf("error creating store: %s", err) + } + if err := store.Store(t.Context(), "key", []byte("value")); err != nil { + t.Fatalf("error storing data in store: %s", err) + } + if err := store.Close(t.Context()); err != nil { + t.Fatalf("error closing store: %s", err) + } + if store, err := netmapcache.OpenStore(t.Context(), dir); store == nil || err != nil { + t.Errorf("expected a store and a nil error, got store: %+v, err: %s", store, err) + } + if err := store.Close(t.Context()); err != nil { + t.Fatalf("error closing store: %s", err) + } + }) +} + // testStore is an in-memory implementation of the [netmapcache.Store] interface. type testStore map[string][]byte @@ -513,6 +564,9 @@ func diffNetMaps(got, want *netmap.NetworkMap) string { ) } +func (t testStore) Clear(context.Context) error { clear(t); return nil } +func (t testStore) Close(context.Context) error { return nil } + func eqViewsSlice[T any](eqVal func(x, y T) bool) func(a, b views.Slice[T]) bool { return func(a, b views.Slice[T]) bool { if a.Len() != b.Len() { diff --git a/ipn/ipnlocal/serve_test.go b/ipn/ipnlocal/serve_test.go index ca08873db..161e653e2 100644 --- a/ipn/ipnlocal/serve_test.go +++ b/ipn/ipnlocal/serve_test.go @@ -1364,12 +1364,14 @@ func newTestBackend(t *testing.T, opts ...any) *LocalBackend { sys.Set(e) sys.Set(new(mem.Store)) + // Create temp dir before setting up the backend and the shutdown to ensure + // cleanup can happen nicely with the full file system. + dir := t.TempDir() b, err := NewLocalBackend(logf, logid.PublicID{}, sys, 0) if err != nil { t.Fatal(err) } t.Cleanup(b.Shutdown) - dir := t.TempDir() b.SetVarRoot(dir) pm := must.Get(newProfileManager(new(mem.Store), logf, health.NewTracker(bus)))